babylon.max.js 5.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017
  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. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  477. var preparedSourceCode = this._processPrecision(sourceCode);
  478. if (this._engine.webGLVersion == 1) {
  479. callback(preparedSourceCode);
  480. return;
  481. }
  482. // Already converted
  483. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  484. callback(preparedSourceCode.replace("#version 300 es", ""));
  485. return;
  486. }
  487. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  488. // Remove extensions
  489. // #extension GL_OES_standard_derivatives : enable
  490. // #extension GL_EXT_shader_texture_lod : enable
  491. // #extension GL_EXT_frag_depth : enable
  492. // #extension GL_EXT_draw_buffers : require
  493. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  494. var result = preparedSourceCode.replace(regex, "");
  495. // Migrate to GLSL v300
  496. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  497. result = result.replace(/attribute[ \t]/g, "in ");
  498. result = result.replace(/[ \t]attribute/g, " in");
  499. if (isFragment) {
  500. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  501. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/texture2D\s*\(/g, "texture(");
  503. result = result.replace(/textureCube\s*\(/g, "texture(");
  504. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  505. result = result.replace(/gl_FragColor/g, "glFragColor");
  506. result = result.replace(/gl_FragData/g, "glFragData");
  507. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  508. }
  509. callback(result);
  510. };
  511. Effect.prototype._processIncludes = function (sourceCode, callback) {
  512. var _this = this;
  513. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  514. var match = regex.exec(sourceCode);
  515. var returnValue = new String(sourceCode);
  516. while (match != null) {
  517. var includeFile = match[1];
  518. // Uniform declaration
  519. if (includeFile.indexOf("__decl__") !== -1) {
  520. includeFile = includeFile.replace(/__decl__/, "");
  521. if (this._engine.supportsUniformBuffers) {
  522. includeFile = includeFile.replace(/Vertex/, "Ubo");
  523. includeFile = includeFile.replace(/Fragment/, "Ubo");
  524. }
  525. includeFile = includeFile + "Declaration";
  526. }
  527. if (Effect.IncludesShadersStore[includeFile]) {
  528. // Substitution
  529. var includeContent = Effect.IncludesShadersStore[includeFile];
  530. if (match[2]) {
  531. var splits = match[3].split(",");
  532. for (var index = 0; index < splits.length; index += 2) {
  533. var source = new RegExp(splits[index], "g");
  534. var dest = splits[index + 1];
  535. includeContent = includeContent.replace(source, dest);
  536. }
  537. }
  538. if (match[4]) {
  539. var indexString = match[5];
  540. if (indexString.indexOf("..") !== -1) {
  541. var indexSplits = indexString.split("..");
  542. var minIndex = parseInt(indexSplits[0]);
  543. var maxIndex = parseInt(indexSplits[1]);
  544. var sourceIncludeContent = includeContent.slice(0);
  545. includeContent = "";
  546. if (isNaN(maxIndex)) {
  547. maxIndex = this._indexParameters[indexSplits[1]];
  548. }
  549. for (var i = minIndex; i < maxIndex; i++) {
  550. if (!this._engine.supportsUniformBuffers) {
  551. // Ubo replacement
  552. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  553. return p1 + "{X}";
  554. });
  555. }
  556. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  557. }
  558. }
  559. else {
  560. if (!this._engine.supportsUniformBuffers) {
  561. // Ubo replacement
  562. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  563. return p1 + "{X}";
  564. });
  565. }
  566. includeContent = includeContent.replace(/\{X\}/g, indexString);
  567. }
  568. }
  569. // Replace
  570. returnValue = returnValue.replace(match[0], includeContent);
  571. }
  572. else {
  573. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  574. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  575. Effect.IncludesShadersStore[includeFile] = fileContent;
  576. _this._processIncludes(returnValue, callback);
  577. });
  578. return;
  579. }
  580. match = regex.exec(sourceCode);
  581. }
  582. callback(returnValue);
  583. };
  584. Effect.prototype._processPrecision = function (source) {
  585. if (source.indexOf("precision highp float") === -1) {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  587. source = "precision mediump float;\n" + source;
  588. }
  589. else {
  590. source = "precision highp float;\n" + source;
  591. }
  592. }
  593. else {
  594. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  595. source = source.replace("precision highp float", "precision mediump float");
  596. }
  597. }
  598. return source;
  599. };
  600. /**
  601. * Recompiles the webGL program
  602. * @param vertexSourceCode The source code for the vertex shader.
  603. * @param fragmentSourceCode The source code for the fragment shader.
  604. * @param onCompiled Callback called when completed.
  605. * @param onError Callback called on error.
  606. * @hidden
  607. */
  608. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  609. var _this = this;
  610. this._isReady = false;
  611. this._vertexSourceCodeOverride = vertexSourceCode;
  612. this._fragmentSourceCodeOverride = fragmentSourceCode;
  613. this.onError = function (effect, error) {
  614. if (onError) {
  615. onError(error);
  616. }
  617. };
  618. this.onCompiled = function () {
  619. var scenes = _this.getEngine().scenes;
  620. for (var i = 0; i < scenes.length; i++) {
  621. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  622. }
  623. if (onCompiled) {
  624. onCompiled(_this._program);
  625. }
  626. };
  627. this._fallbacks = null;
  628. this._prepareEffect();
  629. };
  630. /**
  631. * Gets the uniform locations of the the specified variable names
  632. * @param names THe names of the variables to lookup.
  633. * @returns Array of locations in the same order as variable names.
  634. */
  635. Effect.prototype.getSpecificUniformLocations = function (names) {
  636. var engine = this._engine;
  637. return engine.getUniforms(this._program, names);
  638. };
  639. /**
  640. * Prepares the effect
  641. * @hidden
  642. */
  643. Effect.prototype._prepareEffect = function () {
  644. var attributesNames = this._attributesNames;
  645. var defines = this.defines;
  646. var fallbacks = this._fallbacks;
  647. this._valueCache = {};
  648. var previousProgram = this._program;
  649. try {
  650. var engine = this._engine;
  651. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  652. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  653. }
  654. else {
  655. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  656. }
  657. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  658. if (engine.supportsUniformBuffers) {
  659. for (var name in this._uniformBuffersNames) {
  660. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  661. }
  662. }
  663. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  664. this._attributes = engine.getAttributes(this._program, attributesNames);
  665. var index;
  666. for (index = 0; index < this._samplers.length; index++) {
  667. var sampler = this.getUniform(this._samplers[index]);
  668. if (sampler == null) {
  669. this._samplers.splice(index, 1);
  670. index--;
  671. }
  672. }
  673. engine.bindSamplers(this);
  674. this._compilationError = "";
  675. this._isReady = true;
  676. if (this.onCompiled) {
  677. this.onCompiled(this);
  678. }
  679. this.onCompileObservable.notifyObservers(this);
  680. this.onCompileObservable.clear();
  681. // Unbind mesh reference in fallbacks
  682. if (this._fallbacks) {
  683. this._fallbacks.unBindMesh();
  684. }
  685. if (previousProgram) {
  686. this.getEngine()._deleteProgram(previousProgram);
  687. }
  688. }
  689. catch (e) {
  690. this._compilationError = e.message;
  691. // Let's go through fallbacks then
  692. BABYLON.Tools.Error("Unable to compile effect:");
  693. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  694. return " " + uniform;
  695. }));
  696. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  697. return " " + attribute;
  698. }));
  699. BABYLON.Tools.Error("Error: " + this._compilationError);
  700. if (previousProgram) {
  701. this._program = previousProgram;
  702. this._isReady = true;
  703. if (this.onError) {
  704. this.onError(this, this._compilationError);
  705. }
  706. this.onErrorObservable.notifyObservers(this);
  707. }
  708. if (fallbacks && fallbacks.isMoreFallbacks) {
  709. BABYLON.Tools.Error("Trying next fallback.");
  710. this.defines = fallbacks.reduce(this.defines, this);
  711. this._prepareEffect();
  712. }
  713. else { // Sorry we did everything we can
  714. if (this.onError) {
  715. this.onError(this, this._compilationError);
  716. }
  717. this.onErrorObservable.notifyObservers(this);
  718. this.onErrorObservable.clear();
  719. // Unbind mesh reference in fallbacks
  720. if (this._fallbacks) {
  721. this._fallbacks.unBindMesh();
  722. }
  723. }
  724. }
  725. };
  726. Object.defineProperty(Effect.prototype, "isSupported", {
  727. /**
  728. * Checks if the effect is supported. (Must be called after compilation)
  729. */
  730. get: function () {
  731. return this._compilationError === "";
  732. },
  733. enumerable: true,
  734. configurable: true
  735. });
  736. /**
  737. * Binds a texture to the engine to be used as output of the shader.
  738. * @param channel Name of the output variable.
  739. * @param texture Texture to bind.
  740. * @hidden
  741. */
  742. Effect.prototype._bindTexture = function (channel, texture) {
  743. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  744. };
  745. /**
  746. * Sets a texture on the engine to be used in the shader.
  747. * @param channel Name of the sampler variable.
  748. * @param texture Texture to set.
  749. */
  750. Effect.prototype.setTexture = function (channel, texture) {
  751. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  752. };
  753. /**
  754. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  755. * @param channel Name of the sampler variable.
  756. * @param texture Texture to set.
  757. */
  758. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  759. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  760. };
  761. /**
  762. * Sets an array of textures on the engine to be used in the shader.
  763. * @param channel Name of the variable.
  764. * @param textures Textures to set.
  765. */
  766. Effect.prototype.setTextureArray = function (channel, textures) {
  767. if (this._samplers.indexOf(channel + "Ex") === -1) {
  768. var initialPos = this._samplers.indexOf(channel);
  769. for (var index = 1; index < textures.length; index++) {
  770. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  771. }
  772. }
  773. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  774. };
  775. /**
  776. * 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)
  777. * @param channel Name of the sampler variable.
  778. * @param postProcess Post process to get the input texture from.
  779. */
  780. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  781. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  782. };
  783. /**
  784. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  785. * 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)
  786. * @param channel Name of the sampler variable.
  787. * @param postProcess Post process to get the output texture from.
  788. */
  789. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  790. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  791. };
  792. /** @hidden */
  793. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  794. var cache = this._valueCache[uniformName];
  795. var flag = matrix.updateFlag;
  796. if (cache !== undefined && cache === flag) {
  797. return false;
  798. }
  799. this._valueCache[uniformName] = flag;
  800. return true;
  801. };
  802. /** @hidden */
  803. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  804. var cache = this._valueCache[uniformName];
  805. if (!cache) {
  806. cache = [x, y];
  807. this._valueCache[uniformName] = cache;
  808. return true;
  809. }
  810. var changed = false;
  811. if (cache[0] !== x) {
  812. cache[0] = x;
  813. changed = true;
  814. }
  815. if (cache[1] !== y) {
  816. cache[1] = y;
  817. changed = true;
  818. }
  819. return changed;
  820. };
  821. /** @hidden */
  822. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  823. var cache = this._valueCache[uniformName];
  824. if (!cache) {
  825. cache = [x, y, z];
  826. this._valueCache[uniformName] = cache;
  827. return true;
  828. }
  829. var changed = false;
  830. if (cache[0] !== x) {
  831. cache[0] = x;
  832. changed = true;
  833. }
  834. if (cache[1] !== y) {
  835. cache[1] = y;
  836. changed = true;
  837. }
  838. if (cache[2] !== z) {
  839. cache[2] = z;
  840. changed = true;
  841. }
  842. return changed;
  843. };
  844. /** @hidden */
  845. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  846. var cache = this._valueCache[uniformName];
  847. if (!cache) {
  848. cache = [x, y, z, w];
  849. this._valueCache[uniformName] = cache;
  850. return true;
  851. }
  852. var changed = false;
  853. if (cache[0] !== x) {
  854. cache[0] = x;
  855. changed = true;
  856. }
  857. if (cache[1] !== y) {
  858. cache[1] = y;
  859. changed = true;
  860. }
  861. if (cache[2] !== z) {
  862. cache[2] = z;
  863. changed = true;
  864. }
  865. if (cache[3] !== w) {
  866. cache[3] = w;
  867. changed = true;
  868. }
  869. return changed;
  870. };
  871. /**
  872. * Binds a buffer to a uniform.
  873. * @param buffer Buffer to bind.
  874. * @param name Name of the uniform variable to bind to.
  875. */
  876. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  877. var bufferName = this._uniformBuffersNames[name];
  878. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  879. return;
  880. }
  881. Effect._baseCache[bufferName] = buffer;
  882. this._engine.bindUniformBufferBase(buffer, bufferName);
  883. };
  884. /**
  885. * Binds block to a uniform.
  886. * @param blockName Name of the block to bind.
  887. * @param index Index to bind.
  888. */
  889. Effect.prototype.bindUniformBlock = function (blockName, index) {
  890. this._engine.bindUniformBlock(this._program, blockName, index);
  891. };
  892. /**
  893. * Sets an interger value on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param value Value to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setInt = function (uniformName, value) {
  899. var cache = this._valueCache[uniformName];
  900. if (cache !== undefined && cache === value) {
  901. return this;
  902. }
  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. }
  1098. this._valueCache[uniformName] = value;
  1099. this._engine.setFloat(this.getUniform(uniformName), value);
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets a boolean on a uniform variable.
  1104. * @param uniformName Name of the variable.
  1105. * @param bool value to be set.
  1106. * @returns this effect.
  1107. */
  1108. Effect.prototype.setBool = function (uniformName, bool) {
  1109. var cache = this._valueCache[uniformName];
  1110. if (cache !== undefined && cache === bool) {
  1111. return this;
  1112. }
  1113. this._valueCache[uniformName] = bool;
  1114. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1115. return this;
  1116. };
  1117. /**
  1118. * Sets a Vector2 on a uniform variable.
  1119. * @param uniformName Name of the variable.
  1120. * @param vector2 vector2 to be set.
  1121. * @returns this effect.
  1122. */
  1123. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1124. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1125. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1126. }
  1127. return this;
  1128. };
  1129. /**
  1130. * Sets a float2 on a uniform variable.
  1131. * @param uniformName Name of the variable.
  1132. * @param x First float in float2.
  1133. * @param y Second float in float2.
  1134. * @returns this effect.
  1135. */
  1136. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1137. if (this._cacheFloat2(uniformName, x, y)) {
  1138. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1139. }
  1140. return this;
  1141. };
  1142. /**
  1143. * Sets a Vector3 on a uniform variable.
  1144. * @param uniformName Name of the variable.
  1145. * @param vector3 Value to be set.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1149. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param x First float in float3.
  1158. * @param y Second float in float3.
  1159. * @param z Third float in float3.
  1160. * @returns this effect.
  1161. */
  1162. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1163. if (this._cacheFloat3(uniformName, x, y, z)) {
  1164. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1165. }
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a Vector4 on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param vector4 Value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1175. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1176. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1177. }
  1178. return this;
  1179. };
  1180. /**
  1181. * Sets a float4 on a uniform variable.
  1182. * @param uniformName Name of the variable.
  1183. * @param x First float in float4.
  1184. * @param y Second float in float4.
  1185. * @param z Third float in float4.
  1186. * @param w Fourth float in float4.
  1187. * @returns this effect.
  1188. */
  1189. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1190. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1191. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1192. }
  1193. return this;
  1194. };
  1195. /**
  1196. * Sets a Color3 on a uniform variable.
  1197. * @param uniformName Name of the variable.
  1198. * @param color3 Value to be set.
  1199. * @returns this effect.
  1200. */
  1201. Effect.prototype.setColor3 = function (uniformName, color3) {
  1202. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1203. this._engine.setColor3(this.getUniform(uniformName), color3);
  1204. }
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a Color4 on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param color3 Value to be set.
  1211. * @param alpha Alpha value to be set.
  1212. * @returns this effect.
  1213. */
  1214. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1215. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1216. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1217. }
  1218. return this;
  1219. };
  1220. /**
  1221. * Sets a Color4 on a uniform variable
  1222. * @param uniformName defines the name of the variable
  1223. * @param color4 defines the value to be set
  1224. * @returns this effect.
  1225. */
  1226. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1227. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1228. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1229. }
  1230. return this;
  1231. };
  1232. /**
  1233. * This function will add a new shader to the shader store
  1234. * @param name the name of the shader
  1235. * @param pixelShader optional pixel shader content
  1236. * @param vertexShader optional vertex shader content
  1237. */
  1238. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1239. if (pixelShader) {
  1240. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1241. }
  1242. if (vertexShader) {
  1243. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1244. }
  1245. };
  1246. /**
  1247. * Resets the cache of effects.
  1248. */
  1249. Effect.ResetCache = function () {
  1250. Effect._baseCache = {};
  1251. };
  1252. Effect._uniqueIdSeed = 0;
  1253. Effect._baseCache = {};
  1254. /**
  1255. * Store of each shader (The can be looked up using effect.key)
  1256. */
  1257. Effect.ShadersStore = {};
  1258. /**
  1259. * Store of each included file for a shader (The can be looked up using effect.key)
  1260. */
  1261. Effect.IncludesShadersStore = {};
  1262. return Effect;
  1263. }());
  1264. BABYLON.Effect = Effect;
  1265. })(BABYLON || (BABYLON = {}));
  1266. //# sourceMappingURL=babylon.effect.js.map
  1267. //# sourceMappingURL=babylon.types.js.map
  1268. var BABYLON;
  1269. (function (BABYLON) {
  1270. /**
  1271. * Gather the list of keyboard event types as constants.
  1272. */
  1273. var KeyboardEventTypes = /** @class */ (function () {
  1274. function KeyboardEventTypes() {
  1275. }
  1276. /**
  1277. * The keydown event is fired when a key becomes active (pressed).
  1278. */
  1279. KeyboardEventTypes.KEYDOWN = 0x01;
  1280. /**
  1281. * The keyup event is fired when a key has been released.
  1282. */
  1283. KeyboardEventTypes.KEYUP = 0x02;
  1284. return KeyboardEventTypes;
  1285. }());
  1286. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1287. /**
  1288. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1289. */
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. /**
  1292. * Instantiates a new keyboard info.
  1293. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1294. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1295. * @param event Defines the related dom event
  1296. */
  1297. function KeyboardInfo(
  1298. /**
  1299. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1300. */
  1301. type,
  1302. /**
  1303. * Defines the related dom event
  1304. */
  1305. event) {
  1306. this.type = type;
  1307. this.event = event;
  1308. }
  1309. return KeyboardInfo;
  1310. }());
  1311. BABYLON.KeyboardInfo = KeyboardInfo;
  1312. /**
  1313. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1314. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1315. */
  1316. var KeyboardInfoPre = /** @class */ (function (_super) {
  1317. __extends(KeyboardInfoPre, _super);
  1318. /**
  1319. * Instantiates a new keyboard pre info.
  1320. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1321. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1322. * @param event Defines the related dom event
  1323. */
  1324. function KeyboardInfoPre(
  1325. /**
  1326. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1327. */
  1328. type,
  1329. /**
  1330. * Defines the related dom event
  1331. */
  1332. event) {
  1333. var _this = _super.call(this, type, event) || this;
  1334. _this.type = type;
  1335. _this.event = event;
  1336. _this.skipOnPointerObservable = false;
  1337. return _this;
  1338. }
  1339. return KeyboardInfoPre;
  1340. }(KeyboardInfo));
  1341. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1342. })(BABYLON || (BABYLON = {}));
  1343. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1344. var BABYLON;
  1345. (function (BABYLON) {
  1346. /**
  1347. * Gather the list of pointer event types as constants.
  1348. */
  1349. var PointerEventTypes = /** @class */ (function () {
  1350. function PointerEventTypes() {
  1351. }
  1352. /**
  1353. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1354. */
  1355. PointerEventTypes.POINTERDOWN = 0x01;
  1356. /**
  1357. * The pointerup event is fired when a pointer is no longer active.
  1358. */
  1359. PointerEventTypes.POINTERUP = 0x02;
  1360. /**
  1361. * The pointermove event is fired when a pointer changes coordinates.
  1362. */
  1363. PointerEventTypes.POINTERMOVE = 0x04;
  1364. /**
  1365. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1366. */
  1367. PointerEventTypes.POINTERWHEEL = 0x08;
  1368. /**
  1369. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1370. */
  1371. PointerEventTypes.POINTERPICK = 0x10;
  1372. /**
  1373. * The pointertap event is fired when a the object has been touched and released without drag.
  1374. */
  1375. PointerEventTypes.POINTERTAP = 0x20;
  1376. /**
  1377. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1378. */
  1379. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1380. return PointerEventTypes;
  1381. }());
  1382. BABYLON.PointerEventTypes = PointerEventTypes;
  1383. /**
  1384. * Base class of pointer info types.
  1385. */
  1386. var PointerInfoBase = /** @class */ (function () {
  1387. /**
  1388. * Instantiates the base class of pointers info.
  1389. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1390. * @param event Defines the related dom event
  1391. */
  1392. function PointerInfoBase(
  1393. /**
  1394. * Defines the type of event (BABYLON.PointerEventTypes)
  1395. */
  1396. type,
  1397. /**
  1398. * Defines the related dom event
  1399. */
  1400. event) {
  1401. this.type = type;
  1402. this.event = event;
  1403. }
  1404. return PointerInfoBase;
  1405. }());
  1406. BABYLON.PointerInfoBase = PointerInfoBase;
  1407. /**
  1408. * This class is used to store pointer related info for the onPrePointerObservable event.
  1409. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1410. */
  1411. var PointerInfoPre = /** @class */ (function (_super) {
  1412. __extends(PointerInfoPre, _super);
  1413. /**
  1414. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1415. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1416. * @param event Defines the related dom event
  1417. * @param localX Defines the local x coordinates of the pointer when the event occured
  1418. * @param localY Defines the local y coordinates of the pointer when the event occured
  1419. */
  1420. function PointerInfoPre(type, event, localX, localY) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. /**
  1423. * Ray from a pointer if availible (eg. 6dof controller)
  1424. */
  1425. _this.ray = null;
  1426. _this.skipOnPointerObservable = false;
  1427. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1428. return _this;
  1429. }
  1430. return PointerInfoPre;
  1431. }(PointerInfoBase));
  1432. BABYLON.PointerInfoPre = PointerInfoPre;
  1433. /**
  1434. * This type contains all the data related to a pointer event in Babylon.js.
  1435. * 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.
  1436. */
  1437. var PointerInfo = /** @class */ (function (_super) {
  1438. __extends(PointerInfo, _super);
  1439. /**
  1440. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1441. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1442. * @param event Defines the related dom event
  1443. * @param pickInfo Defines the picking info associated to the info (if any)\
  1444. */
  1445. function PointerInfo(type, event,
  1446. /**
  1447. * Defines the picking info associated to the info (if any)\
  1448. */
  1449. pickInfo) {
  1450. var _this = _super.call(this, type, event) || this;
  1451. _this.pickInfo = pickInfo;
  1452. return _this;
  1453. }
  1454. return PointerInfo;
  1455. }(PointerInfoBase));
  1456. BABYLON.PointerInfo = PointerInfo;
  1457. })(BABYLON || (BABYLON = {}));
  1458. //# sourceMappingURL=babylon.pointerEvents.js.map
  1459. var BABYLON;
  1460. (function (BABYLON) {
  1461. /**
  1462. * Constant used to convert a value to gamma space
  1463. * @ignorenaming
  1464. */
  1465. BABYLON.ToGammaSpace = 1 / 2.2;
  1466. /**
  1467. * Constant used to convert a value to linear space
  1468. * @ignorenaming
  1469. */
  1470. BABYLON.ToLinearSpace = 2.2;
  1471. /**
  1472. * Constant used to define the minimal number value in Babylon.js
  1473. * @ignorenaming
  1474. */
  1475. BABYLON.Epsilon = 0.001;
  1476. /**
  1477. * Class used to hold a RBG color
  1478. */
  1479. var Color3 = /** @class */ (function () {
  1480. /**
  1481. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1482. * @param r defines the red component (between 0 and 1, default is 0)
  1483. * @param g defines the green component (between 0 and 1, default is 0)
  1484. * @param b defines the blue component (between 0 and 1, default is 0)
  1485. */
  1486. function Color3(
  1487. /**
  1488. * Defines the red component (between 0 and 1, default is 0)
  1489. */
  1490. r,
  1491. /**
  1492. * Defines the green component (between 0 and 1, default is 0)
  1493. */
  1494. g,
  1495. /**
  1496. * Defines the blue component (between 0 and 1, default is 0)
  1497. */
  1498. b) {
  1499. if (r === void 0) { r = 0; }
  1500. if (g === void 0) { g = 0; }
  1501. if (b === void 0) { b = 0; }
  1502. this.r = r;
  1503. this.g = g;
  1504. this.b = b;
  1505. }
  1506. /**
  1507. * Creates a string with the Color3 current values
  1508. * @returns the string representation of the Color3 object
  1509. */
  1510. Color3.prototype.toString = function () {
  1511. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1512. };
  1513. /**
  1514. * Returns the string "Color3"
  1515. * @returns "Color3"
  1516. */
  1517. Color3.prototype.getClassName = function () {
  1518. return "Color3";
  1519. };
  1520. /**
  1521. * Compute the Color3 hash code
  1522. * @returns an unique number that can be used to hash Color3 objects
  1523. */
  1524. Color3.prototype.getHashCode = function () {
  1525. var hash = this.r || 0;
  1526. hash = (hash * 397) ^ (this.g || 0);
  1527. hash = (hash * 397) ^ (this.b || 0);
  1528. return hash;
  1529. };
  1530. // Operators
  1531. /**
  1532. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1533. * @param array defines the array where to store the r,g,b components
  1534. * @param index defines an optional index in the target array to define where to start storing values
  1535. * @returns the current Color3 object
  1536. */
  1537. Color3.prototype.toArray = function (array, index) {
  1538. if (index === undefined) {
  1539. index = 0;
  1540. }
  1541. array[index] = this.r;
  1542. array[index + 1] = this.g;
  1543. array[index + 2] = this.b;
  1544. return this;
  1545. };
  1546. /**
  1547. * Returns a new Color4 object from the current Color3 and the given alpha
  1548. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  1549. * @returns a new Color4 object
  1550. */
  1551. Color3.prototype.toColor4 = function (alpha) {
  1552. if (alpha === void 0) { alpha = 1; }
  1553. return new Color4(this.r, this.g, this.b, alpha);
  1554. };
  1555. /**
  1556. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1557. * @returns the new array
  1558. */
  1559. Color3.prototype.asArray = function () {
  1560. var result = new Array();
  1561. this.toArray(result, 0);
  1562. return result;
  1563. };
  1564. /**
  1565. * Returns the luminance value
  1566. * @returns a float value
  1567. */
  1568. Color3.prototype.toLuminance = function () {
  1569. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1570. };
  1571. /**
  1572. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3 object
  1575. */
  1576. Color3.prototype.multiply = function (otherColor) {
  1577. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1578. };
  1579. /**
  1580. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines the Color3 object where to store the result
  1583. * @returns the current Color3
  1584. */
  1585. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1586. result.r = this.r * otherColor.r;
  1587. result.g = this.g * otherColor.g;
  1588. result.b = this.b * otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Determines equality between Color3 objects
  1593. * @param otherColor defines the second operand
  1594. * @returns true if the rgb values are equal to the given ones
  1595. */
  1596. Color3.prototype.equals = function (otherColor) {
  1597. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1598. };
  1599. /**
  1600. * Determines equality between the current Color3 object and a set of r,b,g values
  1601. * @param r defines the red component to check
  1602. * @param g defines the green component to check
  1603. * @param b defines the blue component to check
  1604. * @returns true if the rgb values are equal to the given ones
  1605. */
  1606. Color3.prototype.equalsFloats = function (r, g, b) {
  1607. return this.r === r && this.g === g && this.b === b;
  1608. };
  1609. /**
  1610. * Multiplies in place each rgb value by scale
  1611. * @param scale defines the scaling factor
  1612. * @returns the updated Color3
  1613. */
  1614. Color3.prototype.scale = function (scale) {
  1615. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1616. };
  1617. /**
  1618. * Multiplies the rgb values by scale and stores the result into "result"
  1619. * @param scale defines the scaling factor
  1620. * @param result defines the Color3 object where to store the result
  1621. * @returns the unmodified current Color3
  1622. */
  1623. Color3.prototype.scaleToRef = function (scale, result) {
  1624. result.r = this.r * scale;
  1625. result.g = this.g * scale;
  1626. result.b = this.b * scale;
  1627. return this;
  1628. };
  1629. /**
  1630. * Scale the current Color3 values by a factor and add the result to a given Color3
  1631. * @param scale defines the scale factor
  1632. * @param result defines color to store the result into
  1633. * @returns the unmodified current Color3
  1634. */
  1635. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1636. result.r += this.r * scale;
  1637. result.g += this.g * scale;
  1638. result.b += this.b * scale;
  1639. return this;
  1640. };
  1641. /**
  1642. * Clamps the rgb values by the min and max values and stores the result into "result"
  1643. * @param min defines minimum clamping value (default is 0)
  1644. * @param max defines maximum clamping value (default is 1)
  1645. * @param result defines color to store the result into
  1646. * @returns the original Color3
  1647. */
  1648. Color3.prototype.clampToRef = function (min, max, result) {
  1649. if (min === void 0) { min = 0; }
  1650. if (max === void 0) { max = 1; }
  1651. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1652. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1653. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1654. return this;
  1655. };
  1656. /**
  1657. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1658. * @param otherColor defines the second operand
  1659. * @returns the new Color3
  1660. */
  1661. Color3.prototype.add = function (otherColor) {
  1662. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1663. };
  1664. /**
  1665. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1666. * @param otherColor defines the second operand
  1667. * @param result defines Color3 object to store the result into
  1668. * @returns the unmodified current Color3
  1669. */
  1670. Color3.prototype.addToRef = function (otherColor, result) {
  1671. result.r = this.r + otherColor.r;
  1672. result.g = this.g + otherColor.g;
  1673. result.b = this.b + otherColor.b;
  1674. return this;
  1675. };
  1676. /**
  1677. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1678. * @param otherColor defines the second operand
  1679. * @returns the new Color3
  1680. */
  1681. Color3.prototype.subtract = function (otherColor) {
  1682. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1683. };
  1684. /**
  1685. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1686. * @param otherColor defines the second operand
  1687. * @param result defines Color3 object to store the result into
  1688. * @returns the unmodified current Color3
  1689. */
  1690. Color3.prototype.subtractToRef = function (otherColor, result) {
  1691. result.r = this.r - otherColor.r;
  1692. result.g = this.g - otherColor.g;
  1693. result.b = this.b - otherColor.b;
  1694. return this;
  1695. };
  1696. /**
  1697. * Copy the current object
  1698. * @returns a new Color3 copied the current one
  1699. */
  1700. Color3.prototype.clone = function () {
  1701. return new Color3(this.r, this.g, this.b);
  1702. };
  1703. /**
  1704. * Copies the rgb values from the source in the current Color3
  1705. * @param source defines the source Color3 object
  1706. * @returns the updated Color3 object
  1707. */
  1708. Color3.prototype.copyFrom = function (source) {
  1709. this.r = source.r;
  1710. this.g = source.g;
  1711. this.b = source.b;
  1712. return this;
  1713. };
  1714. /**
  1715. * Updates the Color3 rgb values from the given floats
  1716. * @param r defines the red component to read from
  1717. * @param g defines the green component to read from
  1718. * @param b defines the blue component to read from
  1719. * @returns the current Color3 object
  1720. */
  1721. Color3.prototype.copyFromFloats = function (r, g, b) {
  1722. this.r = r;
  1723. this.g = g;
  1724. this.b = b;
  1725. return this;
  1726. };
  1727. /**
  1728. * Updates the Color3 rgb values from the given floats
  1729. * @param r defines the red component to read from
  1730. * @param g defines the green component to read from
  1731. * @param b defines the blue component to read from
  1732. * @returns the current Color3 object
  1733. */
  1734. Color3.prototype.set = function (r, g, b) {
  1735. return this.copyFromFloats(r, g, b);
  1736. };
  1737. /**
  1738. * Compute the Color3 hexadecimal code as a string
  1739. * @returns a string containing the hexadecimal representation of the Color3 object
  1740. */
  1741. Color3.prototype.toHexString = function () {
  1742. var intR = (this.r * 255) | 0;
  1743. var intG = (this.g * 255) | 0;
  1744. var intB = (this.b * 255) | 0;
  1745. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1746. };
  1747. /**
  1748. * Computes a new Color3 converted from the current one to linear space
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.prototype.toLinearSpace = function () {
  1752. var convertedColor = new Color3();
  1753. this.toLinearSpaceToRef(convertedColor);
  1754. return convertedColor;
  1755. };
  1756. /**
  1757. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1758. * @param convertedColor defines the Color3 object where to store the linear space version
  1759. * @returns the unmodified Color3
  1760. */
  1761. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1762. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1763. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1764. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1765. return this;
  1766. };
  1767. /**
  1768. * Computes a new Color3 converted from the current one to gamma space
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.prototype.toGammaSpace = function () {
  1772. var convertedColor = new Color3();
  1773. this.toGammaSpaceToRef(convertedColor);
  1774. return convertedColor;
  1775. };
  1776. /**
  1777. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1778. * @param convertedColor defines the Color3 object where to store the gamma space version
  1779. * @returns the unmodified Color3
  1780. */
  1781. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1782. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1783. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1784. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1785. return this;
  1786. };
  1787. // Statics
  1788. /**
  1789. * Creates a new Color3 from the string containing valid hexadecimal values
  1790. * @param hex defines a string containing valid hexadecimal values
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.FromHexString = function (hex) {
  1794. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1795. return new Color3(0, 0, 0);
  1796. }
  1797. var r = parseInt(hex.substring(1, 3), 16);
  1798. var g = parseInt(hex.substring(3, 5), 16);
  1799. var b = parseInt(hex.substring(5, 7), 16);
  1800. return Color3.FromInts(r, g, b);
  1801. };
  1802. /**
  1803. * Creates a new Vector3 from the starting index of the given array
  1804. * @param array defines the source array
  1805. * @param offset defines an offset in the source array
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.FromArray = function (array, offset) {
  1809. if (offset === void 0) { offset = 0; }
  1810. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1811. };
  1812. /**
  1813. * Creates a new Color3 from integer values (< 256)
  1814. * @param r defines the red component to read from (value between 0 and 255)
  1815. * @param g defines the green component to read from (value between 0 and 255)
  1816. * @param b defines the blue component to read from (value between 0 and 255)
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.FromInts = function (r, g, b) {
  1820. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1821. };
  1822. /**
  1823. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1824. * @param start defines the start Color3 value
  1825. * @param end defines the end Color3 value
  1826. * @param amount defines the gradient value between start and end
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Lerp = function (start, end, amount) {
  1830. var result = new Color3(0.0, 0.0, 0.0);
  1831. Color3.LerpToRef(start, end, amount, result);
  1832. return result;
  1833. };
  1834. /**
  1835. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1836. * @param left defines the start value
  1837. * @param right defines the end value
  1838. * @param amount defines the gradient factor
  1839. * @param result defines the Color3 object where to store the result
  1840. */
  1841. Color3.LerpToRef = function (left, right, amount, result) {
  1842. result.r = left.r + ((right.r - left.r) * amount);
  1843. result.g = left.g + ((right.g - left.g) * amount);
  1844. result.b = left.b + ((right.b - left.b) * amount);
  1845. };
  1846. /**
  1847. * Returns a Color3 value containing a red color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Red = function () { return new Color3(1, 0, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a green color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Green = function () { return new Color3(0, 1, 0); };
  1856. /**
  1857. * Returns a Color3 value containing a blue color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1861. /**
  1862. * Returns a Color3 value containing a black color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.Black = function () { return new Color3(0, 0, 0); };
  1866. /**
  1867. * Returns a Color3 value containing a white color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.White = function () { return new Color3(1, 1, 1); };
  1871. /**
  1872. * Returns a Color3 value containing a purple color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1876. /**
  1877. * Returns a Color3 value containing a magenta color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1881. /**
  1882. * Returns a Color3 value containing a yellow color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1886. /**
  1887. * Returns a Color3 value containing a gray color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1891. /**
  1892. * Returns a Color3 value containing a teal color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1896. /**
  1897. * Returns a Color3 value containing a random color
  1898. * @returns a new Color3 object
  1899. */
  1900. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1901. return Color3;
  1902. }());
  1903. BABYLON.Color3 = Color3;
  1904. /**
  1905. * Class used to hold a RBGA color
  1906. */
  1907. var Color4 = /** @class */ (function () {
  1908. /**
  1909. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1910. * @param r defines the red component (between 0 and 1, default is 0)
  1911. * @param g defines the green component (between 0 and 1, default is 0)
  1912. * @param b defines the blue component (between 0 and 1, default is 0)
  1913. * @param a defines the alpha component (between 0 and 1, default is 1)
  1914. */
  1915. function Color4(
  1916. /**
  1917. * Defines the red component (between 0 and 1, default is 0)
  1918. */
  1919. r,
  1920. /**
  1921. * Defines the green component (between 0 and 1, default is 0)
  1922. */
  1923. g,
  1924. /**
  1925. * Defines the blue component (between 0 and 1, default is 0)
  1926. */
  1927. b,
  1928. /**
  1929. * Defines the alpha component (between 0 and 1, default is 1)
  1930. */
  1931. a) {
  1932. if (r === void 0) { r = 0; }
  1933. if (g === void 0) { g = 0; }
  1934. if (b === void 0) { b = 0; }
  1935. if (a === void 0) { a = 1; }
  1936. this.r = r;
  1937. this.g = g;
  1938. this.b = b;
  1939. this.a = a;
  1940. }
  1941. // Operators
  1942. /**
  1943. * Adds in place the given Color4 values to the current Color4 object
  1944. * @param right defines the second operand
  1945. * @returns the current updated Color4 object
  1946. */
  1947. Color4.prototype.addInPlace = function (right) {
  1948. this.r += right.r;
  1949. this.g += right.g;
  1950. this.b += right.b;
  1951. this.a += right.a;
  1952. return this;
  1953. };
  1954. /**
  1955. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1956. * @returns the new array
  1957. */
  1958. Color4.prototype.asArray = function () {
  1959. var result = new Array();
  1960. this.toArray(result, 0);
  1961. return result;
  1962. };
  1963. /**
  1964. * Stores from the starting index in the given array the Color4 successive values
  1965. * @param array defines the array where to store the r,g,b components
  1966. * @param index defines an optional index in the target array to define where to start storing values
  1967. * @returns the current Color4 object
  1968. */
  1969. Color4.prototype.toArray = function (array, index) {
  1970. if (index === undefined) {
  1971. index = 0;
  1972. }
  1973. array[index] = this.r;
  1974. array[index + 1] = this.g;
  1975. array[index + 2] = this.b;
  1976. array[index + 3] = this.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1981. * @param right defines the second operand
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.add = function (right) {
  1985. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1986. };
  1987. /**
  1988. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1989. * @param right defines the second operand
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.subtract = function (right) {
  1993. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1994. };
  1995. /**
  1996. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1997. * @param right defines the second operand
  1998. * @param result defines the Color4 object where to store the result
  1999. * @returns the current Color4 object
  2000. */
  2001. Color4.prototype.subtractToRef = function (right, result) {
  2002. result.r = this.r - right.r;
  2003. result.g = this.g - right.g;
  2004. result.b = this.b - right.b;
  2005. result.a = this.a - right.a;
  2006. return this;
  2007. };
  2008. /**
  2009. * Creates a new Color4 with the current Color4 values multiplied by scale
  2010. * @param scale defines the scaling factor to apply
  2011. * @returns a new Color4 object
  2012. */
  2013. Color4.prototype.scale = function (scale) {
  2014. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2015. };
  2016. /**
  2017. * Multiplies the current Color4 values by scale and stores the result in "result"
  2018. * @param scale defines the scaling factor to apply
  2019. * @param result defines the Color4 object where to store the result
  2020. * @returns the current unmodified Color4
  2021. */
  2022. Color4.prototype.scaleToRef = function (scale, result) {
  2023. result.r = this.r * scale;
  2024. result.g = this.g * scale;
  2025. result.b = this.b * scale;
  2026. result.a = this.a * scale;
  2027. return this;
  2028. };
  2029. /**
  2030. * Scale the current Color4 values by a factor and add the result to a given Color4
  2031. * @param scale defines the scale factor
  2032. * @param result defines the Color4 object where to store the result
  2033. * @returns the unmodified current Color4
  2034. */
  2035. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2036. result.r += this.r * scale;
  2037. result.g += this.g * scale;
  2038. result.b += this.b * scale;
  2039. result.a += this.a * scale;
  2040. return this;
  2041. };
  2042. /**
  2043. * Clamps the rgb values by the min and max values and stores the result into "result"
  2044. * @param min defines minimum clamping value (default is 0)
  2045. * @param max defines maximum clamping value (default is 1)
  2046. * @param result defines color to store the result into.
  2047. * @returns the cuurent Color4
  2048. */
  2049. Color4.prototype.clampToRef = function (min, max, result) {
  2050. if (min === void 0) { min = 0; }
  2051. if (max === void 0) { max = 1; }
  2052. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2053. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2054. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2055. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2056. return this;
  2057. };
  2058. /**
  2059. * Multipy an Color4 value by another and return a new Color4 object
  2060. * @param color defines the Color4 value to multiply by
  2061. * @returns a new Color4 object
  2062. */
  2063. Color4.prototype.multiply = function (color) {
  2064. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2065. };
  2066. /**
  2067. * Multipy a Color4 value by another and push the result in a reference value
  2068. * @param color defines the Color4 value to multiply by
  2069. * @param result defines the Color4 to fill the result in
  2070. * @returns the result Color4
  2071. */
  2072. Color4.prototype.multiplyToRef = function (color, result) {
  2073. result.r = this.r * color.r;
  2074. result.g = this.g * color.g;
  2075. result.b = this.b * color.b;
  2076. result.a = this.a * color.a;
  2077. return result;
  2078. };
  2079. /**
  2080. * Creates a string with the Color4 current values
  2081. * @returns the string representation of the Color4 object
  2082. */
  2083. Color4.prototype.toString = function () {
  2084. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2085. };
  2086. /**
  2087. * Returns the string "Color4"
  2088. * @returns "Color4"
  2089. */
  2090. Color4.prototype.getClassName = function () {
  2091. return "Color4";
  2092. };
  2093. /**
  2094. * Compute the Color4 hash code
  2095. * @returns an unique number that can be used to hash Color4 objects
  2096. */
  2097. Color4.prototype.getHashCode = function () {
  2098. var hash = this.r || 0;
  2099. hash = (hash * 397) ^ (this.g || 0);
  2100. hash = (hash * 397) ^ (this.b || 0);
  2101. hash = (hash * 397) ^ (this.a || 0);
  2102. return hash;
  2103. };
  2104. /**
  2105. * Creates a new Color4 copied from the current one
  2106. * @returns a new Color4 object
  2107. */
  2108. Color4.prototype.clone = function () {
  2109. return new Color4(this.r, this.g, this.b, this.a);
  2110. };
  2111. /**
  2112. * Copies the given Color4 values into the current one
  2113. * @param source defines the source Color4 object
  2114. * @returns the current updated Color4 object
  2115. */
  2116. Color4.prototype.copyFrom = function (source) {
  2117. this.r = source.r;
  2118. this.g = source.g;
  2119. this.b = source.b;
  2120. this.a = source.a;
  2121. return this;
  2122. };
  2123. /**
  2124. * Copies the given float values into the current one
  2125. * @param r defines the red component to read from
  2126. * @param g defines the green component to read from
  2127. * @param b defines the blue component to read from
  2128. * @param a defines the alpha component to read from
  2129. * @returns the current updated Color4 object
  2130. */
  2131. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2132. this.r = r;
  2133. this.g = g;
  2134. this.b = b;
  2135. this.a = a;
  2136. return this;
  2137. };
  2138. /**
  2139. * Copies the given float values into the current one
  2140. * @param r defines the red component to read from
  2141. * @param g defines the green component to read from
  2142. * @param b defines the blue component to read from
  2143. * @param a defines the alpha component to read from
  2144. * @returns the current updated Color4 object
  2145. */
  2146. Color4.prototype.set = function (r, g, b, a) {
  2147. return this.copyFromFloats(r, g, b, a);
  2148. };
  2149. /**
  2150. * Compute the Color4 hexadecimal code as a string
  2151. * @returns a string containing the hexadecimal representation of the Color4 object
  2152. */
  2153. Color4.prototype.toHexString = function () {
  2154. var intR = (this.r * 255) | 0;
  2155. var intG = (this.g * 255) | 0;
  2156. var intB = (this.b * 255) | 0;
  2157. var intA = (this.a * 255) | 0;
  2158. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2159. };
  2160. /**
  2161. * Computes a new Color4 converted from the current one to linear space
  2162. * @returns a new Color4 object
  2163. */
  2164. Color4.prototype.toLinearSpace = function () {
  2165. var convertedColor = new Color4();
  2166. this.toLinearSpaceToRef(convertedColor);
  2167. return convertedColor;
  2168. };
  2169. /**
  2170. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2171. * @param convertedColor defines the Color4 object where to store the linear space version
  2172. * @returns the unmodified Color4
  2173. */
  2174. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2175. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2176. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2177. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2178. convertedColor.a = this.a;
  2179. return this;
  2180. };
  2181. /**
  2182. * Computes a new Color4 converted from the current one to gamma space
  2183. * @returns a new Color4 object
  2184. */
  2185. Color4.prototype.toGammaSpace = function () {
  2186. var convertedColor = new Color4();
  2187. this.toGammaSpaceToRef(convertedColor);
  2188. return convertedColor;
  2189. };
  2190. /**
  2191. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2192. * @param convertedColor defines the Color4 object where to store the gamma space version
  2193. * @returns the unmodified Color4
  2194. */
  2195. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2196. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2197. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2198. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2199. convertedColor.a = this.a;
  2200. return this;
  2201. };
  2202. // Statics
  2203. /**
  2204. * Creates a new Color4 from the string containing valid hexadecimal values
  2205. * @param hex defines a string containing valid hexadecimal values
  2206. * @returns a new Color4 object
  2207. */
  2208. Color4.FromHexString = function (hex) {
  2209. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2210. return new Color4(0.0, 0.0, 0.0, 0.0);
  2211. }
  2212. var r = parseInt(hex.substring(1, 3), 16);
  2213. var g = parseInt(hex.substring(3, 5), 16);
  2214. var b = parseInt(hex.substring(5, 7), 16);
  2215. var a = parseInt(hex.substring(7, 9), 16);
  2216. return Color4.FromInts(r, g, b, a);
  2217. };
  2218. /**
  2219. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2220. * @param left defines the start value
  2221. * @param right defines the end value
  2222. * @param amount defines the gradient factor
  2223. * @returns a new Color4 object
  2224. */
  2225. Color4.Lerp = function (left, right, amount) {
  2226. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2227. Color4.LerpToRef(left, right, amount, result);
  2228. return result;
  2229. };
  2230. /**
  2231. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2232. * @param left defines the start value
  2233. * @param right defines the end value
  2234. * @param amount defines the gradient factor
  2235. * @param result defines the Color4 object where to store data
  2236. */
  2237. Color4.LerpToRef = function (left, right, amount, result) {
  2238. result.r = left.r + (right.r - left.r) * amount;
  2239. result.g = left.g + (right.g - left.g) * amount;
  2240. result.b = left.b + (right.b - left.b) * amount;
  2241. result.a = left.a + (right.a - left.a) * amount;
  2242. };
  2243. /**
  2244. * Creates a new Color4 from a Color3 and an alpha value
  2245. * @param color3 defines the source Color3 to read from
  2246. * @param alpha defines the alpha component (1.0 by default)
  2247. * @returns a new Color4 object
  2248. */
  2249. Color4.FromColor3 = function (color3, alpha) {
  2250. if (alpha === void 0) { alpha = 1.0; }
  2251. return new Color4(color3.r, color3.g, color3.b, alpha);
  2252. };
  2253. /**
  2254. * Creates a new Color4 from the starting index element of the given array
  2255. * @param array defines the source array to read from
  2256. * @param offset defines the offset in the source array
  2257. * @returns a new Color4 object
  2258. */
  2259. Color4.FromArray = function (array, offset) {
  2260. if (offset === void 0) { offset = 0; }
  2261. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2262. };
  2263. /**
  2264. * Creates a new Color3 from integer values (< 256)
  2265. * @param r defines the red component to read from (value between 0 and 255)
  2266. * @param g defines the green component to read from (value between 0 and 255)
  2267. * @param b defines the blue component to read from (value between 0 and 255)
  2268. * @param a defines the alpha component to read from (value between 0 and 255)
  2269. * @returns a new Color3 object
  2270. */
  2271. Color4.FromInts = function (r, g, b, a) {
  2272. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2273. };
  2274. /**
  2275. * Check the content of a given array and convert it to an array containing RGBA data
  2276. * If the original array was already containing count * 4 values then it is returned directly
  2277. * @param colors defines the array to check
  2278. * @param count defines the number of RGBA data to expect
  2279. * @returns an array containing count * 4 values (RGBA)
  2280. */
  2281. Color4.CheckColors4 = function (colors, count) {
  2282. // Check if color3 was used
  2283. if (colors.length === count * 3) {
  2284. var colors4 = [];
  2285. for (var index = 0; index < colors.length; index += 3) {
  2286. var newIndex = (index / 3) * 4;
  2287. colors4[newIndex] = colors[index];
  2288. colors4[newIndex + 1] = colors[index + 1];
  2289. colors4[newIndex + 2] = colors[index + 2];
  2290. colors4[newIndex + 3] = 1.0;
  2291. }
  2292. return colors4;
  2293. }
  2294. return colors;
  2295. };
  2296. return Color4;
  2297. }());
  2298. BABYLON.Color4 = Color4;
  2299. /**
  2300. * Class representing a vector containing 2 coordinates
  2301. */
  2302. var Vector2 = /** @class */ (function () {
  2303. /**
  2304. * Creates a new Vector2 from the given x and y coordinates
  2305. * @param x defines the first coordinate
  2306. * @param y defines the second coordinate
  2307. */
  2308. function Vector2(
  2309. /** defines the first coordinate */
  2310. x,
  2311. /** defines the second coordinate */
  2312. y) {
  2313. if (x === void 0) { x = 0; }
  2314. if (y === void 0) { y = 0; }
  2315. this.x = x;
  2316. this.y = y;
  2317. }
  2318. /**
  2319. * Gets a string with the Vector2 coordinates
  2320. * @returns a string with the Vector2 coordinates
  2321. */
  2322. Vector2.prototype.toString = function () {
  2323. return "{X: " + this.x + " Y:" + this.y + "}";
  2324. };
  2325. /**
  2326. * Gets class name
  2327. * @returns the string "Vector2"
  2328. */
  2329. Vector2.prototype.getClassName = function () {
  2330. return "Vector2";
  2331. };
  2332. /**
  2333. * Gets current vector hash code
  2334. * @returns the Vector2 hash code as a number
  2335. */
  2336. Vector2.prototype.getHashCode = function () {
  2337. var hash = this.x || 0;
  2338. hash = (hash * 397) ^ (this.y || 0);
  2339. return hash;
  2340. };
  2341. // Operators
  2342. /**
  2343. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2344. * @param array defines the source array
  2345. * @param index defines the offset in source array
  2346. * @returns the current Vector2
  2347. */
  2348. Vector2.prototype.toArray = function (array, index) {
  2349. if (index === void 0) { index = 0; }
  2350. array[index] = this.x;
  2351. array[index + 1] = this.y;
  2352. return this;
  2353. };
  2354. /**
  2355. * Copy the current vector to an array
  2356. * @returns a new array with 2 elements: the Vector2 coordinates.
  2357. */
  2358. Vector2.prototype.asArray = function () {
  2359. var result = new Array();
  2360. this.toArray(result, 0);
  2361. return result;
  2362. };
  2363. /**
  2364. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2365. * @param source defines the source Vector2
  2366. * @returns the current updated Vector2
  2367. */
  2368. Vector2.prototype.copyFrom = function (source) {
  2369. this.x = source.x;
  2370. this.y = source.y;
  2371. return this;
  2372. };
  2373. /**
  2374. * Sets the Vector2 coordinates with the given floats
  2375. * @param x defines the first coordinate
  2376. * @param y defines the second coordinate
  2377. * @returns the current updated Vector2
  2378. */
  2379. Vector2.prototype.copyFromFloats = function (x, y) {
  2380. this.x = x;
  2381. this.y = y;
  2382. return this;
  2383. };
  2384. /**
  2385. * Sets the Vector2 coordinates with the given floats
  2386. * @param x defines the first coordinate
  2387. * @param y defines the second coordinate
  2388. * @returns the current updated Vector2
  2389. */
  2390. Vector2.prototype.set = function (x, y) {
  2391. return this.copyFromFloats(x, y);
  2392. };
  2393. /**
  2394. * Add another vector with the current one
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2397. */
  2398. Vector2.prototype.add = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2403. * @param otherVector defines the other vector
  2404. * @param result defines the target vector
  2405. * @returns the unmodified current Vector2
  2406. */
  2407. Vector2.prototype.addToRef = function (otherVector, result) {
  2408. result.x = this.x + otherVector.x;
  2409. result.y = this.y + otherVector.y;
  2410. return this;
  2411. };
  2412. /**
  2413. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2414. * @param otherVector defines the other vector
  2415. * @returns the current updated Vector2
  2416. */
  2417. Vector2.prototype.addInPlace = function (otherVector) {
  2418. this.x += otherVector.x;
  2419. this.y += otherVector.y;
  2420. return this;
  2421. };
  2422. /**
  2423. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2424. * @param otherVector defines the other vector
  2425. * @returns a new Vector2
  2426. */
  2427. Vector2.prototype.addVector3 = function (otherVector) {
  2428. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2429. };
  2430. /**
  2431. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2432. * @param otherVector defines the other vector
  2433. * @returns a new Vector2
  2434. */
  2435. Vector2.prototype.subtract = function (otherVector) {
  2436. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2437. };
  2438. /**
  2439. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2440. * @param otherVector defines the other vector
  2441. * @param result defines the target vector
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2445. result.x = this.x - otherVector.x;
  2446. result.y = this.y - otherVector.y;
  2447. return this;
  2448. };
  2449. /**
  2450. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2451. * @param otherVector defines the other vector
  2452. * @returns the current updated Vector2
  2453. */
  2454. Vector2.prototype.subtractInPlace = function (otherVector) {
  2455. this.x -= otherVector.x;
  2456. this.y -= otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Multiplies in place the current Vector2 coordinates by the given ones
  2461. * @param otherVector defines the other vector
  2462. * @returns the current updated Vector2
  2463. */
  2464. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2465. this.x *= otherVector.x;
  2466. this.y *= otherVector.y;
  2467. return this;
  2468. };
  2469. /**
  2470. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2471. * @param otherVector defines the other vector
  2472. * @returns a new Vector2
  2473. */
  2474. Vector2.prototype.multiply = function (otherVector) {
  2475. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2476. };
  2477. /**
  2478. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2479. * @param otherVector defines the other vector
  2480. * @param result defines the target vector
  2481. * @returns the unmodified current Vector2
  2482. */
  2483. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2484. result.x = this.x * otherVector.x;
  2485. result.y = this.y * otherVector.y;
  2486. return this;
  2487. };
  2488. /**
  2489. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2490. * @param x defines the first coordinate
  2491. * @param y defines the second coordinate
  2492. * @returns a new Vector2
  2493. */
  2494. Vector2.prototype.multiplyByFloats = function (x, y) {
  2495. return new Vector2(this.x * x, this.y * y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2499. * @param otherVector defines the other vector
  2500. * @returns a new Vector2
  2501. */
  2502. Vector2.prototype.divide = function (otherVector) {
  2503. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2504. };
  2505. /**
  2506. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2507. * @param otherVector defines the other vector
  2508. * @param result defines the target vector
  2509. * @returns the unmodified current Vector2
  2510. */
  2511. Vector2.prototype.divideToRef = function (otherVector, result) {
  2512. result.x = this.x / otherVector.x;
  2513. result.y = this.y / otherVector.y;
  2514. return this;
  2515. };
  2516. /**
  2517. * Divides the current Vector2 coordinates by the given ones
  2518. * @param otherVector defines the other vector
  2519. * @returns the current updated Vector2
  2520. */
  2521. Vector2.prototype.divideInPlace = function (otherVector) {
  2522. return this.divideToRef(otherVector, this);
  2523. };
  2524. /**
  2525. * Gets a new Vector2 with current Vector2 negated coordinates
  2526. * @returns a new Vector2
  2527. */
  2528. Vector2.prototype.negate = function () {
  2529. return new Vector2(-this.x, -this.y);
  2530. };
  2531. /**
  2532. * Multiply the Vector2 coordinates by scale
  2533. * @param scale defines the scaling factor
  2534. * @returns the current updated Vector2
  2535. */
  2536. Vector2.prototype.scaleInPlace = function (scale) {
  2537. this.x *= scale;
  2538. this.y *= scale;
  2539. return this;
  2540. };
  2541. /**
  2542. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2543. * @param scale defines the scaling factor
  2544. * @returns a new Vector2
  2545. */
  2546. Vector2.prototype.scale = function (scale) {
  2547. var result = new Vector2(0, 0);
  2548. this.scaleToRef(scale, result);
  2549. return result;
  2550. };
  2551. /**
  2552. * Scale the current Vector2 values by a factor to a given Vector2
  2553. * @param scale defines the scale factor
  2554. * @param result defines the Vector2 object where to store the result
  2555. * @returns the unmodified current Vector2
  2556. */
  2557. Vector2.prototype.scaleToRef = function (scale, result) {
  2558. result.x = this.x * scale;
  2559. result.y = this.y * scale;
  2560. return this;
  2561. };
  2562. /**
  2563. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2564. * @param scale defines the scale factor
  2565. * @param result defines the Vector2 object where to store the result
  2566. * @returns the unmodified current Vector2
  2567. */
  2568. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2569. result.x += this.x * scale;
  2570. result.y += this.y * scale;
  2571. return this;
  2572. };
  2573. /**
  2574. * Gets a boolean if two vectors are equals
  2575. * @param otherVector defines the other vector
  2576. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2577. */
  2578. Vector2.prototype.equals = function (otherVector) {
  2579. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2580. };
  2581. /**
  2582. * Gets a boolean if two vectors are equals (using an epsilon value)
  2583. * @param otherVector defines the other vector
  2584. * @param epsilon defines the minimal distance to consider equality
  2585. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2586. */
  2587. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2588. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2589. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2590. };
  2591. /**
  2592. * Gets a new Vector2 from current Vector2 floored values
  2593. * @returns a new Vector2
  2594. */
  2595. Vector2.prototype.floor = function () {
  2596. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2597. };
  2598. /**
  2599. * Gets a new Vector2 from current Vector2 floored values
  2600. * @returns a new Vector2
  2601. */
  2602. Vector2.prototype.fract = function () {
  2603. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2604. };
  2605. // Properties
  2606. /**
  2607. * Gets the length of the vector
  2608. * @returns the vector length (float)
  2609. */
  2610. Vector2.prototype.length = function () {
  2611. return Math.sqrt(this.x * this.x + this.y * this.y);
  2612. };
  2613. /**
  2614. * Gets the vector squared length
  2615. * @returns the vector squared length (float)
  2616. */
  2617. Vector2.prototype.lengthSquared = function () {
  2618. return (this.x * this.x + this.y * this.y);
  2619. };
  2620. // Methods
  2621. /**
  2622. * Normalize the vector
  2623. * @returns the current updated Vector2
  2624. */
  2625. Vector2.prototype.normalize = function () {
  2626. var len = this.length();
  2627. if (len === 0) {
  2628. return this;
  2629. }
  2630. var num = 1.0 / len;
  2631. this.x *= num;
  2632. this.y *= num;
  2633. return this;
  2634. };
  2635. /**
  2636. * Gets a new Vector2 copied from the Vector2
  2637. * @returns a new Vector2
  2638. */
  2639. Vector2.prototype.clone = function () {
  2640. return new Vector2(this.x, this.y);
  2641. };
  2642. // Statics
  2643. /**
  2644. * Gets a new Vector2(0, 0)
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.Zero = function () {
  2648. return new Vector2(0, 0);
  2649. };
  2650. /**
  2651. * Gets a new Vector2(1, 1)
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.One = function () {
  2655. return new Vector2(1, 1);
  2656. };
  2657. /**
  2658. * Gets a new Vector2 set from the given index element of the given array
  2659. * @param array defines the data source
  2660. * @param offset defines the offset in the data source
  2661. * @returns a new Vector2
  2662. */
  2663. Vector2.FromArray = function (array, offset) {
  2664. if (offset === void 0) { offset = 0; }
  2665. return new Vector2(array[offset], array[offset + 1]);
  2666. };
  2667. /**
  2668. * Sets "result" from the given index element of the given array
  2669. * @param array defines the data source
  2670. * @param offset defines the offset in the data source
  2671. * @param result defines the target vector
  2672. */
  2673. Vector2.FromArrayToRef = function (array, offset, result) {
  2674. result.x = array[offset];
  2675. result.y = array[offset + 1];
  2676. };
  2677. /**
  2678. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2679. * @param value1 defines 1st point of control
  2680. * @param value2 defines 2nd point of control
  2681. * @param value3 defines 3rd point of control
  2682. * @param value4 defines 4th point of control
  2683. * @param amount defines the interpolation factor
  2684. * @returns a new Vector2
  2685. */
  2686. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2687. var squared = amount * amount;
  2688. var cubed = amount * squared;
  2689. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2690. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2691. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2692. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2693. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2694. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2695. return new Vector2(x, y);
  2696. };
  2697. /**
  2698. * 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".
  2699. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2700. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2701. * @param value defines the value to clamp
  2702. * @param min defines the lower limit
  2703. * @param max defines the upper limit
  2704. * @returns a new Vector2
  2705. */
  2706. Vector2.Clamp = function (value, min, max) {
  2707. var x = value.x;
  2708. x = (x > max.x) ? max.x : x;
  2709. x = (x < min.x) ? min.x : x;
  2710. var y = value.y;
  2711. y = (y > max.y) ? max.y : y;
  2712. y = (y < min.y) ? min.y : y;
  2713. return new Vector2(x, y);
  2714. };
  2715. /**
  2716. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2717. * @param value1 defines the 1st control point
  2718. * @param tangent1 defines the outgoing tangent
  2719. * @param value2 defines the 2nd control point
  2720. * @param tangent2 defines the incoming tangent
  2721. * @param amount defines the interpolation factor
  2722. * @returns a new Vector2
  2723. */
  2724. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2725. var squared = amount * amount;
  2726. var cubed = amount * squared;
  2727. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2728. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2729. var part3 = (cubed - (2.0 * squared)) + amount;
  2730. var part4 = cubed - squared;
  2731. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2732. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2733. return new Vector2(x, y);
  2734. };
  2735. /**
  2736. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2737. * @param start defines the start vector
  2738. * @param end defines the end vector
  2739. * @param amount defines the interpolation factor
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Lerp = function (start, end, amount) {
  2743. var x = start.x + ((end.x - start.x) * amount);
  2744. var y = start.y + ((end.y - start.y) * amount);
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets the dot product of the vector "left" and the vector "right"
  2749. * @param left defines first vector
  2750. * @param right defines second vector
  2751. * @returns the dot product (float)
  2752. */
  2753. Vector2.Dot = function (left, right) {
  2754. return left.x * right.x + left.y * right.y;
  2755. };
  2756. /**
  2757. * Returns a new Vector2 equal to the normalized given vector
  2758. * @param vector defines the vector to normalize
  2759. * @returns a new Vector2
  2760. */
  2761. Vector2.Normalize = function (vector) {
  2762. var newVector = vector.clone();
  2763. newVector.normalize();
  2764. return newVector;
  2765. };
  2766. /**
  2767. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2768. * @param left defines 1st vector
  2769. * @param right defines 2nd vector
  2770. * @returns a new Vector2
  2771. */
  2772. Vector2.Minimize = function (left, right) {
  2773. var x = (left.x < right.x) ? left.x : right.x;
  2774. var y = (left.y < right.y) ? left.y : right.y;
  2775. return new Vector2(x, y);
  2776. };
  2777. /**
  2778. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2779. * @param left defines 1st vector
  2780. * @param right defines 2nd vector
  2781. * @returns a new Vector2
  2782. */
  2783. Vector2.Maximize = function (left, right) {
  2784. var x = (left.x > right.x) ? left.x : right.x;
  2785. var y = (left.y > right.y) ? left.y : right.y;
  2786. return new Vector2(x, y);
  2787. };
  2788. /**
  2789. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2790. * @param vector defines the vector to transform
  2791. * @param transformation defines the matrix to apply
  2792. * @returns a new Vector2
  2793. */
  2794. Vector2.Transform = function (vector, transformation) {
  2795. var r = Vector2.Zero();
  2796. Vector2.TransformToRef(vector, transformation, r);
  2797. return r;
  2798. };
  2799. /**
  2800. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2801. * @param vector defines the vector to transform
  2802. * @param transformation defines the matrix to apply
  2803. * @param result defines the target vector
  2804. */
  2805. Vector2.TransformToRef = function (vector, transformation, result) {
  2806. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2807. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2808. result.x = x;
  2809. result.y = y;
  2810. };
  2811. /**
  2812. * Determines if a given vector is included in a triangle
  2813. * @param p defines the vector to test
  2814. * @param p0 defines 1st triangle point
  2815. * @param p1 defines 2nd triangle point
  2816. * @param p2 defines 3rd triangle point
  2817. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2818. */
  2819. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2820. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2821. var sign = a < 0 ? -1 : 1;
  2822. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2823. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2824. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2825. };
  2826. /**
  2827. * Gets the distance between the vectors "value1" and "value2"
  2828. * @param value1 defines first vector
  2829. * @param value2 defines second vector
  2830. * @returns the distance between vectors
  2831. */
  2832. Vector2.Distance = function (value1, value2) {
  2833. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2834. };
  2835. /**
  2836. * Returns the squared distance between the vectors "value1" and "value2"
  2837. * @param value1 defines first vector
  2838. * @param value2 defines second vector
  2839. * @returns the squared distance between vectors
  2840. */
  2841. Vector2.DistanceSquared = function (value1, value2) {
  2842. var x = value1.x - value2.x;
  2843. var y = value1.y - value2.y;
  2844. return (x * x) + (y * y);
  2845. };
  2846. /**
  2847. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2848. * @param value1 defines first vector
  2849. * @param value2 defines second vector
  2850. * @returns a new Vector2
  2851. */
  2852. Vector2.Center = function (value1, value2) {
  2853. var center = value1.add(value2);
  2854. center.scaleInPlace(0.5);
  2855. return center;
  2856. };
  2857. /**
  2858. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2859. * @param p defines the middle point
  2860. * @param segA defines one point of the segment
  2861. * @param segB defines the other point of the segment
  2862. * @returns the shortest distance
  2863. */
  2864. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2865. var l2 = Vector2.DistanceSquared(segA, segB);
  2866. if (l2 === 0.0) {
  2867. return Vector2.Distance(p, segA);
  2868. }
  2869. var v = segB.subtract(segA);
  2870. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2871. var proj = segA.add(v.multiplyByFloats(t, t));
  2872. return Vector2.Distance(p, proj);
  2873. };
  2874. return Vector2;
  2875. }());
  2876. BABYLON.Vector2 = Vector2;
  2877. /**
  2878. * Classed used to store (x,y,z) vector representation
  2879. * A Vector3 is the main object used in 3D geometry
  2880. * It can represent etiher the coordinates of a point the space, either a direction
  2881. * Reminder: Babylon.js uses a left handed forward facing system
  2882. */
  2883. var Vector3 = /** @class */ (function () {
  2884. /**
  2885. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2886. * @param x defines the first coordinates (on X axis)
  2887. * @param y defines the second coordinates (on Y axis)
  2888. * @param z defines the third coordinates (on Z axis)
  2889. */
  2890. function Vector3(
  2891. /**
  2892. * Defines the first coordinates (on X axis)
  2893. */
  2894. x,
  2895. /**
  2896. * Defines the second coordinates (on Y axis)
  2897. */
  2898. y,
  2899. /**
  2900. * Defines the third coordinates (on Z axis)
  2901. */
  2902. z) {
  2903. if (x === void 0) { x = 0; }
  2904. if (y === void 0) { y = 0; }
  2905. if (z === void 0) { z = 0; }
  2906. this.x = x;
  2907. this.y = y;
  2908. this.z = z;
  2909. }
  2910. /**
  2911. * Creates a string representation of the Vector3
  2912. * @returns a string with the Vector3 coordinates.
  2913. */
  2914. Vector3.prototype.toString = function () {
  2915. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2916. };
  2917. /**
  2918. * Gets the class name
  2919. * @returns the string "Vector3"
  2920. */
  2921. Vector3.prototype.getClassName = function () {
  2922. return "Vector3";
  2923. };
  2924. /**
  2925. * Creates the Vector3 hash code
  2926. * @returns a number which tends to be unique between Vector3 instances
  2927. */
  2928. Vector3.prototype.getHashCode = function () {
  2929. var hash = this.x || 0;
  2930. hash = (hash * 397) ^ (this.y || 0);
  2931. hash = (hash * 397) ^ (this.z || 0);
  2932. return hash;
  2933. };
  2934. // Operators
  2935. /**
  2936. * Creates an array containing three elements : the coordinates of the Vector3
  2937. * @returns a new array of numbers
  2938. */
  2939. Vector3.prototype.asArray = function () {
  2940. var result = [];
  2941. this.toArray(result, 0);
  2942. return result;
  2943. };
  2944. /**
  2945. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2946. * @param array defines the destination array
  2947. * @param index defines the offset in the destination array
  2948. * @returns the current Vector3
  2949. */
  2950. Vector3.prototype.toArray = function (array, index) {
  2951. if (index === void 0) { index = 0; }
  2952. array[index] = this.x;
  2953. array[index + 1] = this.y;
  2954. array[index + 2] = this.z;
  2955. return this;
  2956. };
  2957. /**
  2958. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2959. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2960. */
  2961. Vector3.prototype.toQuaternion = function () {
  2962. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2963. };
  2964. /**
  2965. * Adds the given vector to the current Vector3
  2966. * @param otherVector defines the second operand
  2967. * @returns the current updated Vector3
  2968. */
  2969. Vector3.prototype.addInPlace = function (otherVector) {
  2970. this.x += otherVector.x;
  2971. this.y += otherVector.y;
  2972. this.z += otherVector.z;
  2973. return this;
  2974. };
  2975. /**
  2976. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2977. * @param otherVector defines the second operand
  2978. * @returns the resulting Vector3
  2979. */
  2980. Vector3.prototype.add = function (otherVector) {
  2981. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2982. };
  2983. /**
  2984. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2985. * @param otherVector defines the second operand
  2986. * @param result defines the Vector3 object where to store the result
  2987. * @returns the current Vector3
  2988. */
  2989. Vector3.prototype.addToRef = function (otherVector, result) {
  2990. result.x = this.x + otherVector.x;
  2991. result.y = this.y + otherVector.y;
  2992. result.z = this.z + otherVector.z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Subtract the given vector from the current Vector3
  2997. * @param otherVector defines the second operand
  2998. * @returns the current updated Vector3
  2999. */
  3000. Vector3.prototype.subtractInPlace = function (otherVector) {
  3001. this.x -= otherVector.x;
  3002. this.y -= otherVector.y;
  3003. this.z -= otherVector.z;
  3004. return this;
  3005. };
  3006. /**
  3007. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  3008. * @param otherVector defines the second operand
  3009. * @returns the resulting Vector3
  3010. */
  3011. Vector3.prototype.subtract = function (otherVector) {
  3012. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  3013. };
  3014. /**
  3015. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  3016. * @param otherVector defines the second operand
  3017. * @param result defines the Vector3 object where to store the result
  3018. * @returns the current Vector3
  3019. */
  3020. Vector3.prototype.subtractToRef = function (otherVector, result) {
  3021. result.x = this.x - otherVector.x;
  3022. result.y = this.y - otherVector.y;
  3023. result.z = this.z - otherVector.z;
  3024. return this;
  3025. };
  3026. /**
  3027. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  3028. * @param x defines the x coordinate of the operand
  3029. * @param y defines the y coordinate of the operand
  3030. * @param z defines the z coordinate of the operand
  3031. * @returns the resulting Vector3
  3032. */
  3033. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3034. return new Vector3(this.x - x, this.y - y, this.z - z);
  3035. };
  3036. /**
  3037. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3038. * @param x defines the x coordinate of the operand
  3039. * @param y defines the y coordinate of the operand
  3040. * @param z defines the z coordinate of the operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3045. result.x = this.x - x;
  3046. result.y = this.y - y;
  3047. result.z = this.z - z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3052. * @returns a new Vector3
  3053. */
  3054. Vector3.prototype.negate = function () {
  3055. return new Vector3(-this.x, -this.y, -this.z);
  3056. };
  3057. /**
  3058. * Multiplies the Vector3 coordinates by the float "scale"
  3059. * @param scale defines the multiplier factor
  3060. * @returns the current updated Vector3
  3061. */
  3062. Vector3.prototype.scaleInPlace = function (scale) {
  3063. this.x *= scale;
  3064. this.y *= scale;
  3065. this.z *= scale;
  3066. return this;
  3067. };
  3068. /**
  3069. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3070. * @param scale defines the multiplier factor
  3071. * @returns a new Vector3
  3072. */
  3073. Vector3.prototype.scale = function (scale) {
  3074. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3075. };
  3076. /**
  3077. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3078. * @param scale defines the multiplier factor
  3079. * @param result defines the Vector3 object where to store the result
  3080. * @returns the current Vector3
  3081. */
  3082. Vector3.prototype.scaleToRef = function (scale, result) {
  3083. result.x = this.x * scale;
  3084. result.y = this.y * scale;
  3085. result.z = this.z * scale;
  3086. return this;
  3087. };
  3088. /**
  3089. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3090. * @param scale defines the scale factor
  3091. * @param result defines the Vector3 object where to store the result
  3092. * @returns the unmodified current Vector3
  3093. */
  3094. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3095. result.x += this.x * scale;
  3096. result.y += this.y * scale;
  3097. result.z += this.z * scale;
  3098. return this;
  3099. };
  3100. /**
  3101. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3102. * @param otherVector defines the second operand
  3103. * @returns true if both vectors are equals
  3104. */
  3105. Vector3.prototype.equals = function (otherVector) {
  3106. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3107. };
  3108. /**
  3109. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3110. * @param otherVector defines the second operand
  3111. * @param epsilon defines the minimal distance to define values as equals
  3112. * @returns true if both vectors are distant less than epsilon
  3113. */
  3114. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3115. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3116. 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);
  3117. };
  3118. /**
  3119. * Returns true if the current Vector3 coordinates equals the given floats
  3120. * @param x defines the x coordinate of the operand
  3121. * @param y defines the y coordinate of the operand
  3122. * @param z defines the z coordinate of the operand
  3123. * @returns true if both vectors are equals
  3124. */
  3125. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3126. return this.x === x && this.y === y && this.z === z;
  3127. };
  3128. /**
  3129. * Multiplies the current Vector3 coordinates by the given ones
  3130. * @param otherVector defines the second operand
  3131. * @returns the current updated Vector3
  3132. */
  3133. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3134. this.x *= otherVector.x;
  3135. this.y *= otherVector.y;
  3136. this.z *= otherVector.z;
  3137. return this;
  3138. };
  3139. /**
  3140. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.multiply = function (otherVector) {
  3145. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3146. };
  3147. /**
  3148. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3154. result.x = this.x * otherVector.x;
  3155. result.y = this.y * otherVector.y;
  3156. result.z = this.z * otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3161. * @param x defines the x coordinate of the operand
  3162. * @param y defines the y coordinate of the operand
  3163. * @param z defines the z coordinate of the operand
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3167. return new Vector3(this.x * x, this.y * y, this.z * z);
  3168. };
  3169. /**
  3170. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3171. * @param otherVector defines the second operand
  3172. * @returns the new Vector3
  3173. */
  3174. Vector3.prototype.divide = function (otherVector) {
  3175. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3176. };
  3177. /**
  3178. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3179. * @param otherVector defines the second operand
  3180. * @param result defines the Vector3 object where to store the result
  3181. * @returns the current Vector3
  3182. */
  3183. Vector3.prototype.divideToRef = function (otherVector, result) {
  3184. result.x = this.x / otherVector.x;
  3185. result.y = this.y / otherVector.y;
  3186. result.z = this.z / otherVector.z;
  3187. return this;
  3188. };
  3189. /**
  3190. * Divides the current Vector3 coordinates by the given ones.
  3191. * @param otherVector defines the second operand
  3192. * @returns the current updated Vector3
  3193. */
  3194. Vector3.prototype.divideInPlace = function (otherVector) {
  3195. return this.divideToRef(otherVector, this);
  3196. };
  3197. /**
  3198. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3199. * @param other defines the second operand
  3200. * @returns the current updated Vector3
  3201. */
  3202. Vector3.prototype.minimizeInPlace = function (other) {
  3203. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3204. };
  3205. /**
  3206. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3207. * @param other defines the second operand
  3208. * @returns the current updated Vector3
  3209. */
  3210. Vector3.prototype.maximizeInPlace = function (other) {
  3211. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3212. };
  3213. /**
  3214. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3215. * @param x defines the x coordinate of the operand
  3216. * @param y defines the y coordinate of the operand
  3217. * @param z defines the z coordinate of the operand
  3218. * @returns the current updated Vector3
  3219. */
  3220. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3221. if (x < this.x) {
  3222. this.x = x;
  3223. }
  3224. if (y < this.y) {
  3225. this.y = y;
  3226. }
  3227. if (z < this.z) {
  3228. this.z = z;
  3229. }
  3230. return this;
  3231. };
  3232. /**
  3233. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3234. * @param x defines the x coordinate of the operand
  3235. * @param y defines the y coordinate of the operand
  3236. * @param z defines the z coordinate of the operand
  3237. * @returns the current updated Vector3
  3238. */
  3239. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3240. if (x > this.x) {
  3241. this.x = x;
  3242. }
  3243. if (y > this.y) {
  3244. this.y = y;
  3245. }
  3246. if (z > this.z) {
  3247. this.z = z;
  3248. }
  3249. return this;
  3250. };
  3251. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3252. /**
  3253. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3254. */
  3255. get: function () {
  3256. var absX = Math.abs(this.x);
  3257. var absY = Math.abs(this.y);
  3258. if (absX !== absY) {
  3259. return true;
  3260. }
  3261. var absZ = Math.abs(this.z);
  3262. if (absX !== absZ) {
  3263. return true;
  3264. }
  3265. if (absY !== absZ) {
  3266. return true;
  3267. }
  3268. return false;
  3269. },
  3270. enumerable: true,
  3271. configurable: true
  3272. });
  3273. /**
  3274. * Gets a new Vector3 from current Vector3 floored values
  3275. * @returns a new Vector3
  3276. */
  3277. Vector3.prototype.floor = function () {
  3278. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3279. };
  3280. /**
  3281. * Gets a new Vector3 from current Vector3 floored values
  3282. * @returns a new Vector3
  3283. */
  3284. Vector3.prototype.fract = function () {
  3285. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3286. };
  3287. // Properties
  3288. /**
  3289. * Gets the length of the Vector3
  3290. * @returns the length of the Vecto3
  3291. */
  3292. Vector3.prototype.length = function () {
  3293. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3294. };
  3295. /**
  3296. * Gets the squared length of the Vector3
  3297. * @returns squared length of the Vector3
  3298. */
  3299. Vector3.prototype.lengthSquared = function () {
  3300. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3301. };
  3302. /**
  3303. * Normalize the current Vector3.
  3304. * Please note that this is an in place operation.
  3305. * @returns the current updated Vector3
  3306. */
  3307. Vector3.prototype.normalize = function () {
  3308. var len = this.length();
  3309. if (len === 0 || len === 1.0) {
  3310. return this;
  3311. }
  3312. var num = 1.0 / len;
  3313. this.x *= num;
  3314. this.y *= num;
  3315. this.z *= num;
  3316. return this;
  3317. };
  3318. /**
  3319. * Normalize the current Vector3 to a new vector
  3320. * @returns the new Vector3
  3321. */
  3322. Vector3.prototype.normalizeToNew = function () {
  3323. var normalized = new Vector3(0, 0, 0);
  3324. this.normalizeToRef(normalized);
  3325. return normalized;
  3326. };
  3327. /**
  3328. * Normalize the current Vector3 to the reference
  3329. * @param reference define the Vector3 to update
  3330. * @returns the updated Vector3
  3331. */
  3332. Vector3.prototype.normalizeToRef = function (reference) {
  3333. var len = this.length();
  3334. if (len === 0 || len === 1.0) {
  3335. reference.set(this.x, this.y, this.z);
  3336. return reference;
  3337. }
  3338. var scale = 1.0 / len;
  3339. this.scaleToRef(scale, reference);
  3340. return reference;
  3341. };
  3342. /**
  3343. * Creates a new Vector3 copied from the current Vector3
  3344. * @returns the new Vector3
  3345. */
  3346. Vector3.prototype.clone = function () {
  3347. return new Vector3(this.x, this.y, this.z);
  3348. };
  3349. /**
  3350. * Copies the given vector coordinates to the current Vector3 ones
  3351. * @param source defines the source Vector3
  3352. * @returns the current updated Vector3
  3353. */
  3354. Vector3.prototype.copyFrom = function (source) {
  3355. this.x = source.x;
  3356. this.y = source.y;
  3357. this.z = source.z;
  3358. return this;
  3359. };
  3360. /**
  3361. * Copies the given floats to the current Vector3 coordinates
  3362. * @param x defines the x coordinate of the operand
  3363. * @param y defines the y coordinate of the operand
  3364. * @param z defines the z coordinate of the operand
  3365. * @returns the current updated Vector3
  3366. */
  3367. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3368. this.x = x;
  3369. this.y = y;
  3370. this.z = z;
  3371. return this;
  3372. };
  3373. /**
  3374. * Copies the given floats to the current Vector3 coordinates
  3375. * @param x defines the x coordinate of the operand
  3376. * @param y defines the y coordinate of the operand
  3377. * @param z defines the z coordinate of the operand
  3378. * @returns the current updated Vector3
  3379. */
  3380. Vector3.prototype.set = function (x, y, z) {
  3381. return this.copyFromFloats(x, y, z);
  3382. };
  3383. // Statics
  3384. /**
  3385. * Get the clip factor between two vectors
  3386. * @param vector0 defines the first operand
  3387. * @param vector1 defines the second operand
  3388. * @param axis defines the axis to use
  3389. * @param size defines the size along the axis
  3390. * @returns the clip factor
  3391. */
  3392. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3393. var d0 = Vector3.Dot(vector0, axis) - size;
  3394. var d1 = Vector3.Dot(vector1, axis) - size;
  3395. var s = d0 / (d0 - d1);
  3396. return s;
  3397. };
  3398. /**
  3399. * Get angle between two vectors
  3400. * @param vector0 angle between vector0 and vector1
  3401. * @param vector1 angle between vector0 and vector1
  3402. * @param normal direction of the normal
  3403. * @return the angle between vector0 and vector1
  3404. */
  3405. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3406. var v0 = MathTmp.Vector3[1].copyFrom(vector0).normalize();
  3407. var v1 = MathTmp.Vector3[2].copyFrom(vector1).normalize();
  3408. var dot = Vector3.Dot(v0, v1);
  3409. var n = MathTmp.Vector3[3];
  3410. Vector3.CrossToRef(v0, v1, n);
  3411. if (Vector3.Dot(n, normal) > 0) {
  3412. return Math.acos(dot);
  3413. }
  3414. return -Math.acos(dot);
  3415. };
  3416. /**
  3417. * Returns a new Vector3 set from the index "offset" of the given array
  3418. * @param array defines the source array
  3419. * @param offset defines the offset in the source array
  3420. * @returns the new Vector3
  3421. */
  3422. Vector3.FromArray = function (array, offset) {
  3423. if (!offset) {
  3424. offset = 0;
  3425. }
  3426. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3427. };
  3428. /**
  3429. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3430. * This function is deprecated. Use FromArray instead
  3431. * @param array defines the source array
  3432. * @param offset defines the offset in the source array
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.FromFloatArray = function (array, offset) {
  3436. return Vector3.FromArray(array, offset);
  3437. };
  3438. /**
  3439. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3440. * @param array defines the source array
  3441. * @param offset defines the offset in the source array
  3442. * @param result defines the Vector3 where to store the result
  3443. */
  3444. Vector3.FromArrayToRef = function (array, offset, result) {
  3445. result.x = array[offset];
  3446. result.y = array[offset + 1];
  3447. result.z = array[offset + 2];
  3448. };
  3449. /**
  3450. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3451. * This function is deprecated. Use FromArrayToRef instead.
  3452. * @param array defines the source array
  3453. * @param offset defines the offset in the source array
  3454. * @param result defines the Vector3 where to store the result
  3455. */
  3456. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3457. return Vector3.FromArrayToRef(array, offset, result);
  3458. };
  3459. /**
  3460. * Sets the given vector "result" with the given floats.
  3461. * @param x defines the x coordinate of the source
  3462. * @param y defines the y coordinate of the source
  3463. * @param z defines the z coordinate of the source
  3464. * @param result defines the Vector3 where to store the result
  3465. */
  3466. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3467. result.x = x;
  3468. result.y = y;
  3469. result.z = z;
  3470. };
  3471. /**
  3472. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3473. * @returns a new empty Vector3
  3474. */
  3475. Vector3.Zero = function () {
  3476. return new Vector3(0.0, 0.0, 0.0);
  3477. };
  3478. /**
  3479. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3480. * @returns a new unit Vector3
  3481. */
  3482. Vector3.One = function () {
  3483. return new Vector3(1.0, 1.0, 1.0);
  3484. };
  3485. /**
  3486. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3487. * @returns a new up Vector3
  3488. */
  3489. Vector3.Up = function () {
  3490. return new Vector3(0.0, 1.0, 0.0);
  3491. };
  3492. /**
  3493. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3494. * @returns a new down Vector3
  3495. */
  3496. Vector3.Down = function () {
  3497. return new Vector3(0.0, -1.0, 0.0);
  3498. };
  3499. /**
  3500. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3501. * @returns a new forward Vector3
  3502. */
  3503. Vector3.Forward = function () {
  3504. return new Vector3(0.0, 0.0, 1.0);
  3505. };
  3506. /**
  3507. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3508. * @returns a new forward Vector3
  3509. */
  3510. Vector3.Backward = function () {
  3511. return new Vector3(0.0, 0.0, -1.0);
  3512. };
  3513. /**
  3514. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3515. * @returns a new right Vector3
  3516. */
  3517. Vector3.Right = function () {
  3518. return new Vector3(1.0, 0.0, 0.0);
  3519. };
  3520. /**
  3521. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3522. * @returns a new left Vector3
  3523. */
  3524. Vector3.Left = function () {
  3525. return new Vector3(-1.0, 0.0, 0.0);
  3526. };
  3527. /**
  3528. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3529. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3530. * @param vector defines the Vector3 to transform
  3531. * @param transformation defines the transformation matrix
  3532. * @returns the transformed Vector3
  3533. */
  3534. Vector3.TransformCoordinates = function (vector, transformation) {
  3535. var result = Vector3.Zero();
  3536. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3537. return result;
  3538. };
  3539. /**
  3540. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3541. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3542. * @param vector defines the Vector3 to transform
  3543. * @param transformation defines the transformation matrix
  3544. * @param result defines the Vector3 where to store the result
  3545. */
  3546. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3547. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3548. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3549. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3550. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3551. result.x = x / w;
  3552. result.y = y / w;
  3553. result.z = z / w;
  3554. };
  3555. /**
  3556. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3557. * This method computes tranformed coordinates only, not transformed direction vectors
  3558. * @param x define the x coordinate of the source vector
  3559. * @param y define the y coordinate of the source vector
  3560. * @param z define the z coordinate of the source vector
  3561. * @param transformation defines the transformation matrix
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3565. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3566. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3567. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3568. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3569. result.x = rx / rw;
  3570. result.y = ry / rw;
  3571. result.z = rz / rw;
  3572. };
  3573. /**
  3574. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3575. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3576. * @param vector defines the Vector3 to transform
  3577. * @param transformation defines the transformation matrix
  3578. * @returns the new Vector3
  3579. */
  3580. Vector3.TransformNormal = function (vector, transformation) {
  3581. var result = Vector3.Zero();
  3582. Vector3.TransformNormalToRef(vector, transformation, result);
  3583. return result;
  3584. };
  3585. /**
  3586. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3587. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3588. * @param vector defines the Vector3 to transform
  3589. * @param transformation defines the transformation matrix
  3590. * @param result defines the Vector3 where to store the result
  3591. */
  3592. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3593. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3594. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3595. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3596. result.x = x;
  3597. result.y = y;
  3598. result.z = z;
  3599. };
  3600. /**
  3601. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3602. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3603. * @param x define the x coordinate of the source vector
  3604. * @param y define the y coordinate of the source vector
  3605. * @param z define the z coordinate of the source vector
  3606. * @param transformation defines the transformation matrix
  3607. * @param result defines the Vector3 where to store the result
  3608. */
  3609. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3610. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3611. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3612. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3613. };
  3614. /**
  3615. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3616. * @param value1 defines the first control point
  3617. * @param value2 defines the second control point
  3618. * @param value3 defines the third control point
  3619. * @param value4 defines the fourth control point
  3620. * @param amount defines the amount on the spline to use
  3621. * @returns the new Vector3
  3622. */
  3623. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3624. var squared = amount * amount;
  3625. var cubed = amount * squared;
  3626. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3627. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3628. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3629. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3630. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3631. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3632. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3633. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3634. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3635. return new Vector3(x, y, z);
  3636. };
  3637. /**
  3638. * 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"
  3639. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3640. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3641. * @param value defines the current value
  3642. * @param min defines the lower range value
  3643. * @param max defines the upper range value
  3644. * @returns the new Vector3
  3645. */
  3646. Vector3.Clamp = function (value, min, max) {
  3647. var x = value.x;
  3648. x = (x > max.x) ? max.x : x;
  3649. x = (x < min.x) ? min.x : x;
  3650. var y = value.y;
  3651. y = (y > max.y) ? max.y : y;
  3652. y = (y < min.y) ? min.y : y;
  3653. var z = value.z;
  3654. z = (z > max.z) ? max.z : z;
  3655. z = (z < min.z) ? min.z : z;
  3656. return new Vector3(x, y, z);
  3657. };
  3658. /**
  3659. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3660. * @param value1 defines the first control point
  3661. * @param tangent1 defines the first tangent vector
  3662. * @param value2 defines the second control point
  3663. * @param tangent2 defines the second tangent vector
  3664. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3665. * @returns the new Vector3
  3666. */
  3667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3668. var squared = amount * amount;
  3669. var cubed = amount * squared;
  3670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3672. var part3 = (cubed - (2.0 * squared)) + amount;
  3673. var part4 = cubed - squared;
  3674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3677. return new Vector3(x, y, z);
  3678. };
  3679. /**
  3680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3681. * @param start defines the start value
  3682. * @param end defines the end value
  3683. * @param amount max defines amount between both (between 0 and 1)
  3684. * @returns the new Vector3
  3685. */
  3686. Vector3.Lerp = function (start, end, amount) {
  3687. var result = new Vector3(0, 0, 0);
  3688. Vector3.LerpToRef(start, end, amount, result);
  3689. return result;
  3690. };
  3691. /**
  3692. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3693. * @param start defines the start value
  3694. * @param end defines the end value
  3695. * @param amount max defines amount between both (between 0 and 1)
  3696. * @param result defines the Vector3 where to store the result
  3697. */
  3698. Vector3.LerpToRef = function (start, end, amount, result) {
  3699. result.x = start.x + ((end.x - start.x) * amount);
  3700. result.y = start.y + ((end.y - start.y) * amount);
  3701. result.z = start.z + ((end.z - start.z) * amount);
  3702. };
  3703. /**
  3704. * Returns the dot product (float) between the vectors "left" and "right"
  3705. * @param left defines the left operand
  3706. * @param right defines the right operand
  3707. * @returns the dot product
  3708. */
  3709. Vector3.Dot = function (left, right) {
  3710. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3711. };
  3712. /**
  3713. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3714. * The cross product is then orthogonal to both "left" and "right"
  3715. * @param left defines the left operand
  3716. * @param right defines the right operand
  3717. * @returns the cross product
  3718. */
  3719. Vector3.Cross = function (left, right) {
  3720. var result = Vector3.Zero();
  3721. Vector3.CrossToRef(left, right, result);
  3722. return result;
  3723. };
  3724. /**
  3725. * Sets the given vector "result" with the cross product of "left" and "right"
  3726. * The cross product is then orthogonal to both "left" and "right"
  3727. * @param left defines the left operand
  3728. * @param right defines the right operand
  3729. * @param result defines the Vector3 where to store the result
  3730. */
  3731. Vector3.CrossToRef = function (left, right, result) {
  3732. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3733. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3734. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3735. result.copyFrom(MathTmp.Vector3[0]);
  3736. };
  3737. /**
  3738. * Returns a new Vector3 as the normalization of the given vector
  3739. * @param vector defines the Vector3 to normalize
  3740. * @returns the new Vector3
  3741. */
  3742. Vector3.Normalize = function (vector) {
  3743. var result = Vector3.Zero();
  3744. Vector3.NormalizeToRef(vector, result);
  3745. return result;
  3746. };
  3747. /**
  3748. * Sets the given vector "result" with the normalization of the given first vector
  3749. * @param vector defines the Vector3 to normalize
  3750. * @param result defines the Vector3 where to store the result
  3751. */
  3752. Vector3.NormalizeToRef = function (vector, result) {
  3753. result.copyFrom(vector);
  3754. result.normalize();
  3755. };
  3756. /**
  3757. * Project a Vector3 onto screen space
  3758. * @param vector defines the Vector3 to project
  3759. * @param world defines the world matrix to use
  3760. * @param transform defines the transform (view x projection) matrix to use
  3761. * @param viewport defines the screen viewport to use
  3762. * @returns the new Vector3
  3763. */
  3764. Vector3.Project = function (vector, world, transform, viewport) {
  3765. var cw = viewport.width;
  3766. var ch = viewport.height;
  3767. var cx = viewport.x;
  3768. var cy = viewport.y;
  3769. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3770. 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);
  3771. var matrix = MathTmp.Matrix[0];
  3772. world.multiplyToRef(transform, matrix);
  3773. matrix.multiplyToRef(viewportMatrix, matrix);
  3774. return Vector3.TransformCoordinates(vector, matrix);
  3775. };
  3776. /**
  3777. * Unproject from screen space to object space
  3778. * @param source defines the screen space Vector3 to use
  3779. * @param viewportWidth defines the current width of the viewport
  3780. * @param viewportHeight defines the current height of the viewport
  3781. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3782. * @param transform defines the transform (view x projection) matrix to use
  3783. * @returns the new Vector3
  3784. */
  3785. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3786. var matrix = MathTmp.Matrix[0];
  3787. world.multiplyToRef(transform, matrix);
  3788. matrix.invert();
  3789. source.x = source.x / viewportWidth * 2 - 1;
  3790. source.y = -(source.y / viewportHeight * 2 - 1);
  3791. var vector = Vector3.TransformCoordinates(source, matrix);
  3792. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3793. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3794. vector = vector.scale(1.0 / num);
  3795. }
  3796. return vector;
  3797. };
  3798. /**
  3799. * Unproject from screen space to object space
  3800. * @param source defines the screen space Vector3 to use
  3801. * @param viewportWidth defines the current width of the viewport
  3802. * @param viewportHeight defines the current height of the viewport
  3803. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3804. * @param view defines the view matrix to use
  3805. * @param projection defines the projection matrix to use
  3806. * @returns the new Vector3
  3807. */
  3808. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3809. var result = Vector3.Zero();
  3810. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3811. return result;
  3812. };
  3813. /**
  3814. * Unproject from screen space to object space
  3815. * @param source defines the screen space Vector3 to use
  3816. * @param viewportWidth defines the current width of the viewport
  3817. * @param viewportHeight defines the current height of the viewport
  3818. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3819. * @param view defines the view matrix to use
  3820. * @param projection defines the projection matrix to use
  3821. * @param result defines the Vector3 where to store the result
  3822. */
  3823. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3824. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3825. };
  3826. /**
  3827. * Unproject from screen space to object space
  3828. * @param sourceX defines the screen space x coordinate to use
  3829. * @param sourceY defines the screen space y coordinate to use
  3830. * @param sourceZ defines the screen space z coordinate to use
  3831. * @param viewportWidth defines the current width of the viewport
  3832. * @param viewportHeight defines the current height of the viewport
  3833. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3834. * @param view defines the view matrix to use
  3835. * @param projection defines the projection matrix to use
  3836. * @param result defines the Vector3 where to store the result
  3837. */
  3838. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3839. var matrix = MathTmp.Matrix[0];
  3840. world.multiplyToRef(view, matrix);
  3841. matrix.multiplyToRef(projection, matrix);
  3842. matrix.invert();
  3843. var screenSource = MathTmp.Vector3[0];
  3844. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3845. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3846. screenSource.z = 2 * sourceZ - 1.0;
  3847. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3848. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3849. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3850. result.scaleInPlace(1.0 / num);
  3851. }
  3852. };
  3853. /**
  3854. * Gets the minimal coordinate values between two Vector3
  3855. * @param left defines the first operand
  3856. * @param right defines the second operand
  3857. * @returns the new Vector3
  3858. */
  3859. Vector3.Minimize = function (left, right) {
  3860. var min = left.clone();
  3861. min.minimizeInPlace(right);
  3862. return min;
  3863. };
  3864. /**
  3865. * Gets the maximal coordinate values between two Vector3
  3866. * @param left defines the first operand
  3867. * @param right defines the second operand
  3868. * @returns the new Vector3
  3869. */
  3870. Vector3.Maximize = function (left, right) {
  3871. var max = left.clone();
  3872. max.maximizeInPlace(right);
  3873. return max;
  3874. };
  3875. /**
  3876. * Returns the distance between the vectors "value1" and "value2"
  3877. * @param value1 defines the first operand
  3878. * @param value2 defines the second operand
  3879. * @returns the distance
  3880. */
  3881. Vector3.Distance = function (value1, value2) {
  3882. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3883. };
  3884. /**
  3885. * Returns the squared distance between the vectors "value1" and "value2"
  3886. * @param value1 defines the first operand
  3887. * @param value2 defines the second operand
  3888. * @returns the squared distance
  3889. */
  3890. Vector3.DistanceSquared = function (value1, value2) {
  3891. var x = value1.x - value2.x;
  3892. var y = value1.y - value2.y;
  3893. var z = value1.z - value2.z;
  3894. return (x * x) + (y * y) + (z * z);
  3895. };
  3896. /**
  3897. * Returns a new Vector3 located at the center between "value1" and "value2"
  3898. * @param value1 defines the first operand
  3899. * @param value2 defines the second operand
  3900. * @returns the new Vector3
  3901. */
  3902. Vector3.Center = function (value1, value2) {
  3903. var center = value1.add(value2);
  3904. center.scaleInPlace(0.5);
  3905. return center;
  3906. };
  3907. /**
  3908. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3909. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3910. * to something in order to rotate it from its local system to the given target system
  3911. * Note: axis1, axis2 and axis3 are normalized during this operation
  3912. * @param axis1 defines the first axis
  3913. * @param axis2 defines the second axis
  3914. * @param axis3 defines the third axis
  3915. * @returns a new Vector3
  3916. */
  3917. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3918. var rotation = Vector3.Zero();
  3919. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3920. return rotation;
  3921. };
  3922. /**
  3923. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3924. * @param axis1 defines the first axis
  3925. * @param axis2 defines the second axis
  3926. * @param axis3 defines the third axis
  3927. * @param ref defines the Vector3 where to store the result
  3928. */
  3929. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3930. var quat = MathTmp.Quaternion[0];
  3931. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3932. quat.toEulerAnglesToRef(ref);
  3933. };
  3934. return Vector3;
  3935. }());
  3936. BABYLON.Vector3 = Vector3;
  3937. /**
  3938. * Vector4 class created for EulerAngle class conversion to Quaternion
  3939. */
  3940. var Vector4 = /** @class */ (function () {
  3941. /**
  3942. * Creates a Vector4 object from the given floats.
  3943. * @param x x value of the vector
  3944. * @param y y value of the vector
  3945. * @param z z value of the vector
  3946. * @param w w value of the vector
  3947. */
  3948. function Vector4(
  3949. /** x value of the vector */
  3950. x,
  3951. /** y value of the vector */
  3952. y,
  3953. /** z value of the vector */
  3954. z,
  3955. /** w value of the vector */
  3956. w) {
  3957. this.x = x;
  3958. this.y = y;
  3959. this.z = z;
  3960. this.w = w;
  3961. }
  3962. /**
  3963. * Returns the string with the Vector4 coordinates.
  3964. * @returns a string containing all the vector values
  3965. */
  3966. Vector4.prototype.toString = function () {
  3967. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3968. };
  3969. /**
  3970. * Returns the string "Vector4".
  3971. * @returns "Vector4"
  3972. */
  3973. Vector4.prototype.getClassName = function () {
  3974. return "Vector4";
  3975. };
  3976. /**
  3977. * Returns the Vector4 hash code.
  3978. * @returns a unique hash code
  3979. */
  3980. Vector4.prototype.getHashCode = function () {
  3981. var hash = this.x || 0;
  3982. hash = (hash * 397) ^ (this.y || 0);
  3983. hash = (hash * 397) ^ (this.z || 0);
  3984. hash = (hash * 397) ^ (this.w || 0);
  3985. return hash;
  3986. };
  3987. // Operators
  3988. /**
  3989. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3990. * @returns the resulting array
  3991. */
  3992. Vector4.prototype.asArray = function () {
  3993. var result = new Array();
  3994. this.toArray(result, 0);
  3995. return result;
  3996. };
  3997. /**
  3998. * Populates the given array from the given index with the Vector4 coordinates.
  3999. * @param array array to populate
  4000. * @param index index of the array to start at (default: 0)
  4001. * @returns the Vector4.
  4002. */
  4003. Vector4.prototype.toArray = function (array, index) {
  4004. if (index === undefined) {
  4005. index = 0;
  4006. }
  4007. array[index] = this.x;
  4008. array[index + 1] = this.y;
  4009. array[index + 2] = this.z;
  4010. array[index + 3] = this.w;
  4011. return this;
  4012. };
  4013. /**
  4014. * Adds the given vector to the current Vector4.
  4015. * @param otherVector the vector to add
  4016. * @returns the updated Vector4.
  4017. */
  4018. Vector4.prototype.addInPlace = function (otherVector) {
  4019. this.x += otherVector.x;
  4020. this.y += otherVector.y;
  4021. this.z += otherVector.z;
  4022. this.w += otherVector.w;
  4023. return this;
  4024. };
  4025. /**
  4026. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  4027. * @param otherVector the vector to add
  4028. * @returns the resulting vector
  4029. */
  4030. Vector4.prototype.add = function (otherVector) {
  4031. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  4032. };
  4033. /**
  4034. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  4035. * @param otherVector the vector to add
  4036. * @param result the vector to store the result
  4037. * @returns the current Vector4.
  4038. */
  4039. Vector4.prototype.addToRef = function (otherVector, result) {
  4040. result.x = this.x + otherVector.x;
  4041. result.y = this.y + otherVector.y;
  4042. result.z = this.z + otherVector.z;
  4043. result.w = this.w + otherVector.w;
  4044. return this;
  4045. };
  4046. /**
  4047. * Subtract in place the given vector from the current Vector4.
  4048. * @param otherVector the vector to subtract
  4049. * @returns the updated Vector4.
  4050. */
  4051. Vector4.prototype.subtractInPlace = function (otherVector) {
  4052. this.x -= otherVector.x;
  4053. this.y -= otherVector.y;
  4054. this.z -= otherVector.z;
  4055. this.w -= otherVector.w;
  4056. return this;
  4057. };
  4058. /**
  4059. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4060. * @param otherVector the vector to add
  4061. * @returns the new vector with the result
  4062. */
  4063. Vector4.prototype.subtract = function (otherVector) {
  4064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4065. };
  4066. /**
  4067. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4068. * @param otherVector the vector to subtract
  4069. * @param result the vector to store the result
  4070. * @returns the current Vector4.
  4071. */
  4072. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4073. result.x = this.x - otherVector.x;
  4074. result.y = this.y - otherVector.y;
  4075. result.z = this.z - otherVector.z;
  4076. result.w = this.w - otherVector.w;
  4077. return this;
  4078. };
  4079. /**
  4080. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4081. */
  4082. /**
  4083. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4084. * @param x value to subtract
  4085. * @param y value to subtract
  4086. * @param z value to subtract
  4087. * @param w value to subtract
  4088. * @returns new vector containing the result
  4089. */
  4090. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4091. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4092. };
  4093. /**
  4094. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4095. * @param x value to subtract
  4096. * @param y value to subtract
  4097. * @param z value to subtract
  4098. * @param w value to subtract
  4099. * @param result the vector to store the result in
  4100. * @returns the current Vector4.
  4101. */
  4102. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4103. result.x = this.x - x;
  4104. result.y = this.y - y;
  4105. result.z = this.z - z;
  4106. result.w = this.w - w;
  4107. return this;
  4108. };
  4109. /**
  4110. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4111. * @returns a new vector with the negated values
  4112. */
  4113. Vector4.prototype.negate = function () {
  4114. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4115. };
  4116. /**
  4117. * Multiplies the current Vector4 coordinates by scale (float).
  4118. * @param scale the number to scale with
  4119. * @returns the updated Vector4.
  4120. */
  4121. Vector4.prototype.scaleInPlace = function (scale) {
  4122. this.x *= scale;
  4123. this.y *= scale;
  4124. this.z *= scale;
  4125. this.w *= scale;
  4126. return this;
  4127. };
  4128. /**
  4129. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4130. * @param scale the number to scale with
  4131. * @returns a new vector with the result
  4132. */
  4133. Vector4.prototype.scale = function (scale) {
  4134. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4135. };
  4136. /**
  4137. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4138. * @param scale the number to scale with
  4139. * @param result a vector to store the result in
  4140. * @returns the current Vector4.
  4141. */
  4142. Vector4.prototype.scaleToRef = function (scale, result) {
  4143. result.x = this.x * scale;
  4144. result.y = this.y * scale;
  4145. result.z = this.z * scale;
  4146. result.w = this.w * scale;
  4147. return this;
  4148. };
  4149. /**
  4150. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4151. * @param scale defines the scale factor
  4152. * @param result defines the Vector4 object where to store the result
  4153. * @returns the unmodified current Vector4
  4154. */
  4155. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4156. result.x += this.x * scale;
  4157. result.y += this.y * scale;
  4158. result.z += this.z * scale;
  4159. result.w += this.w * scale;
  4160. return this;
  4161. };
  4162. /**
  4163. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4164. * @param otherVector the vector to compare against
  4165. * @returns true if they are equal
  4166. */
  4167. Vector4.prototype.equals = function (otherVector) {
  4168. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4169. };
  4170. /**
  4171. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4172. * @param otherVector vector to compare against
  4173. * @param epsilon (Default: very small number)
  4174. * @returns true if they are equal
  4175. */
  4176. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4177. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4178. return otherVector
  4179. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4180. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4181. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4182. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4183. };
  4184. /**
  4185. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4186. * @param x x value to compare against
  4187. * @param y y value to compare against
  4188. * @param z z value to compare against
  4189. * @param w w value to compare against
  4190. * @returns true if equal
  4191. */
  4192. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4193. return this.x === x && this.y === y && this.z === z && this.w === w;
  4194. };
  4195. /**
  4196. * Multiplies in place the current Vector4 by the given one.
  4197. * @param otherVector vector to multiple with
  4198. * @returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4201. this.x *= otherVector.x;
  4202. this.y *= otherVector.y;
  4203. this.z *= otherVector.z;
  4204. this.w *= otherVector.w;
  4205. return this;
  4206. };
  4207. /**
  4208. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4209. * @param otherVector vector to multiple with
  4210. * @returns resulting new vector
  4211. */
  4212. Vector4.prototype.multiply = function (otherVector) {
  4213. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4214. };
  4215. /**
  4216. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4217. * @param otherVector vector to multiple with
  4218. * @param result vector to store the result
  4219. * @returns the current Vector4.
  4220. */
  4221. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4222. result.x = this.x * otherVector.x;
  4223. result.y = this.y * otherVector.y;
  4224. result.z = this.z * otherVector.z;
  4225. result.w = this.w * otherVector.w;
  4226. return this;
  4227. };
  4228. /**
  4229. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4230. * @param x x value multiply with
  4231. * @param y y value multiply with
  4232. * @param z z value multiply with
  4233. * @param w w value multiply with
  4234. * @returns resulting new vector
  4235. */
  4236. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4237. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4238. };
  4239. /**
  4240. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4241. * @param otherVector vector to devide with
  4242. * @returns resulting new vector
  4243. */
  4244. Vector4.prototype.divide = function (otherVector) {
  4245. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4246. };
  4247. /**
  4248. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4249. * @param otherVector vector to devide with
  4250. * @param result vector to store the result
  4251. * @returns the current Vector4.
  4252. */
  4253. Vector4.prototype.divideToRef = function (otherVector, result) {
  4254. result.x = this.x / otherVector.x;
  4255. result.y = this.y / otherVector.y;
  4256. result.z = this.z / otherVector.z;
  4257. result.w = this.w / otherVector.w;
  4258. return this;
  4259. };
  4260. /**
  4261. * Divides the current Vector3 coordinates by the given ones.
  4262. * @param otherVector vector to devide with
  4263. * @returns the updated Vector3.
  4264. */
  4265. Vector4.prototype.divideInPlace = function (otherVector) {
  4266. return this.divideToRef(otherVector, this);
  4267. };
  4268. /**
  4269. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4270. * @param other defines the second operand
  4271. * @returns the current updated Vector4
  4272. */
  4273. Vector4.prototype.minimizeInPlace = function (other) {
  4274. if (other.x < this.x) {
  4275. this.x = other.x;
  4276. }
  4277. if (other.y < this.y) {
  4278. this.y = other.y;
  4279. }
  4280. if (other.z < this.z) {
  4281. this.z = other.z;
  4282. }
  4283. if (other.w < this.w) {
  4284. this.w = other.w;
  4285. }
  4286. return this;
  4287. };
  4288. /**
  4289. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4290. * @param other defines the second operand
  4291. * @returns the current updated Vector4
  4292. */
  4293. Vector4.prototype.maximizeInPlace = function (other) {
  4294. if (other.x > this.x) {
  4295. this.x = other.x;
  4296. }
  4297. if (other.y > this.y) {
  4298. this.y = other.y;
  4299. }
  4300. if (other.z > this.z) {
  4301. this.z = other.z;
  4302. }
  4303. if (other.w > this.w) {
  4304. this.w = other.w;
  4305. }
  4306. return this;
  4307. };
  4308. /**
  4309. * Gets a new Vector4 from current Vector4 floored values
  4310. * @returns a new Vector4
  4311. */
  4312. Vector4.prototype.floor = function () {
  4313. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4314. };
  4315. /**
  4316. * Gets a new Vector4 from current Vector3 floored values
  4317. * @returns a new Vector4
  4318. */
  4319. Vector4.prototype.fract = function () {
  4320. 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));
  4321. };
  4322. // Properties
  4323. /**
  4324. * Returns the Vector4 length (float).
  4325. * @returns the length
  4326. */
  4327. Vector4.prototype.length = function () {
  4328. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4329. };
  4330. /**
  4331. * Returns the Vector4 squared length (float).
  4332. * @returns the length squared
  4333. */
  4334. Vector4.prototype.lengthSquared = function () {
  4335. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4336. };
  4337. // Methods
  4338. /**
  4339. * Normalizes in place the Vector4.
  4340. * @returns the updated Vector4.
  4341. */
  4342. Vector4.prototype.normalize = function () {
  4343. var len = this.length();
  4344. if (len === 0) {
  4345. return this;
  4346. }
  4347. var num = 1.0 / len;
  4348. this.x *= num;
  4349. this.y *= num;
  4350. this.z *= num;
  4351. this.w *= num;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4356. * @returns this converted to a new vector3
  4357. */
  4358. Vector4.prototype.toVector3 = function () {
  4359. return new Vector3(this.x, this.y, this.z);
  4360. };
  4361. /**
  4362. * Returns a new Vector4 copied from the current one.
  4363. * @returns the new cloned vector
  4364. */
  4365. Vector4.prototype.clone = function () {
  4366. return new Vector4(this.x, this.y, this.z, this.w);
  4367. };
  4368. /**
  4369. * Updates the current Vector4 with the given one coordinates.
  4370. * @param source the source vector to copy from
  4371. * @returns the updated Vector4.
  4372. */
  4373. Vector4.prototype.copyFrom = function (source) {
  4374. this.x = source.x;
  4375. this.y = source.y;
  4376. this.z = source.z;
  4377. this.w = source.w;
  4378. return this;
  4379. };
  4380. /**
  4381. * Updates the current Vector4 coordinates with the given floats.
  4382. * @param x float to copy from
  4383. * @param y float to copy from
  4384. * @param z float to copy from
  4385. * @param w float to copy from
  4386. * @returns the updated Vector4.
  4387. */
  4388. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4389. this.x = x;
  4390. this.y = y;
  4391. this.z = z;
  4392. this.w = w;
  4393. return this;
  4394. };
  4395. /**
  4396. * Updates the current Vector4 coordinates with the given floats.
  4397. * @param x float to set from
  4398. * @param y float to set from
  4399. * @param z float to set from
  4400. * @param w float to set from
  4401. * @returns the updated Vector4.
  4402. */
  4403. Vector4.prototype.set = function (x, y, z, w) {
  4404. return this.copyFromFloats(x, y, z, w);
  4405. };
  4406. // Statics
  4407. /**
  4408. * Returns a new Vector4 set from the starting index of the given array.
  4409. * @param array the array to pull values from
  4410. * @param offset the offset into the array to start at
  4411. * @returns the new vector
  4412. */
  4413. Vector4.FromArray = function (array, offset) {
  4414. if (!offset) {
  4415. offset = 0;
  4416. }
  4417. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4418. };
  4419. /**
  4420. * Updates the given vector "result" from the starting index of the given array.
  4421. * @param array the array to pull values from
  4422. * @param offset the offset into the array to start at
  4423. * @param result the vector to store the result in
  4424. */
  4425. Vector4.FromArrayToRef = function (array, offset, result) {
  4426. result.x = array[offset];
  4427. result.y = array[offset + 1];
  4428. result.z = array[offset + 2];
  4429. result.w = array[offset + 3];
  4430. };
  4431. /**
  4432. * Updates the given vector "result" from the starting index of the given Float32Array.
  4433. * @param array the array to pull values from
  4434. * @param offset the offset into the array to start at
  4435. * @param result the vector to store the result in
  4436. */
  4437. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4438. Vector4.FromArrayToRef(array, offset, result);
  4439. };
  4440. /**
  4441. * Updates the given vector "result" coordinates from the given floats.
  4442. * @param x float to set from
  4443. * @param y float to set from
  4444. * @param z float to set from
  4445. * @param w float to set from
  4446. * @param result the vector to the floats in
  4447. */
  4448. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4449. result.x = x;
  4450. result.y = y;
  4451. result.z = z;
  4452. result.w = w;
  4453. };
  4454. /**
  4455. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4456. * @returns the new vector
  4457. */
  4458. Vector4.Zero = function () {
  4459. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4460. };
  4461. /**
  4462. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4463. * @returns the new vector
  4464. */
  4465. Vector4.One = function () {
  4466. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4467. };
  4468. /**
  4469. * Returns a new normalized Vector4 from the given one.
  4470. * @param vector the vector to normalize
  4471. * @returns the vector
  4472. */
  4473. Vector4.Normalize = function (vector) {
  4474. var result = Vector4.Zero();
  4475. Vector4.NormalizeToRef(vector, result);
  4476. return result;
  4477. };
  4478. /**
  4479. * Updates the given vector "result" from the normalization of the given one.
  4480. * @param vector the vector to normalize
  4481. * @param result the vector to store the result in
  4482. */
  4483. Vector4.NormalizeToRef = function (vector, result) {
  4484. result.copyFrom(vector);
  4485. result.normalize();
  4486. };
  4487. /**
  4488. * Returns a vector with the minimum values from the left and right vectors
  4489. * @param left left vector to minimize
  4490. * @param right right vector to minimize
  4491. * @returns a new vector with the minimum of the left and right vector values
  4492. */
  4493. Vector4.Minimize = function (left, right) {
  4494. var min = left.clone();
  4495. min.minimizeInPlace(right);
  4496. return min;
  4497. };
  4498. /**
  4499. * Returns a vector with the maximum values from the left and right vectors
  4500. * @param left left vector to maximize
  4501. * @param right right vector to maximize
  4502. * @returns a new vector with the maximum of the left and right vector values
  4503. */
  4504. Vector4.Maximize = function (left, right) {
  4505. var max = left.clone();
  4506. max.maximizeInPlace(right);
  4507. return max;
  4508. };
  4509. /**
  4510. * Returns the distance (float) between the vectors "value1" and "value2".
  4511. * @param value1 value to calulate the distance between
  4512. * @param value2 value to calulate the distance between
  4513. * @return the distance between the two vectors
  4514. */
  4515. Vector4.Distance = function (value1, value2) {
  4516. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4517. };
  4518. /**
  4519. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4520. * @param value1 value to calulate the distance between
  4521. * @param value2 value to calulate the distance between
  4522. * @return the distance between the two vectors squared
  4523. */
  4524. Vector4.DistanceSquared = function (value1, value2) {
  4525. var x = value1.x - value2.x;
  4526. var y = value1.y - value2.y;
  4527. var z = value1.z - value2.z;
  4528. var w = value1.w - value2.w;
  4529. return (x * x) + (y * y) + (z * z) + (w * w);
  4530. };
  4531. /**
  4532. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4533. * @param value1 value to calulate the center between
  4534. * @param value2 value to calulate the center between
  4535. * @return the center between the two vectors
  4536. */
  4537. Vector4.Center = function (value1, value2) {
  4538. var center = value1.add(value2);
  4539. center.scaleInPlace(0.5);
  4540. return center;
  4541. };
  4542. /**
  4543. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4544. * This methods computes transformed normalized direction vectors only.
  4545. * @param vector the vector to transform
  4546. * @param transformation the transformation matrix to apply
  4547. * @returns the new vector
  4548. */
  4549. Vector4.TransformNormal = function (vector, transformation) {
  4550. var result = Vector4.Zero();
  4551. Vector4.TransformNormalToRef(vector, transformation, result);
  4552. return result;
  4553. };
  4554. /**
  4555. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4556. * This methods computes transformed normalized direction vectors only.
  4557. * @param vector the vector to transform
  4558. * @param transformation the transformation matrix to apply
  4559. * @param result the vector to store the result in
  4560. */
  4561. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4562. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4563. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4564. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4565. result.x = x;
  4566. result.y = y;
  4567. result.z = z;
  4568. result.w = vector.w;
  4569. };
  4570. /**
  4571. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4572. * This methods computes transformed normalized direction vectors only.
  4573. * @param x value to transform
  4574. * @param y value to transform
  4575. * @param z value to transform
  4576. * @param w value to transform
  4577. * @param transformation the transformation matrix to apply
  4578. * @param result the vector to store the results in
  4579. */
  4580. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4581. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4582. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4583. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4584. result.w = w;
  4585. };
  4586. return Vector4;
  4587. }());
  4588. BABYLON.Vector4 = Vector4;
  4589. /**
  4590. * Size containing widht and height
  4591. */
  4592. var Size = /** @class */ (function () {
  4593. /**
  4594. * Creates a Size object from the given width and height (floats).
  4595. * @param width width of the new size
  4596. * @param height height of the new size
  4597. */
  4598. function Size(width, height) {
  4599. this.width = width;
  4600. this.height = height;
  4601. }
  4602. /**
  4603. * Returns a string with the Size width and height
  4604. * @returns a string with the Size width and height
  4605. */
  4606. Size.prototype.toString = function () {
  4607. return "{W: " + this.width + ", H: " + this.height + "}";
  4608. };
  4609. /**
  4610. * "Size"
  4611. * @returns the string "Size"
  4612. */
  4613. Size.prototype.getClassName = function () {
  4614. return "Size";
  4615. };
  4616. /**
  4617. * Returns the Size hash code.
  4618. * @returns a hash code for a unique width and height
  4619. */
  4620. Size.prototype.getHashCode = function () {
  4621. var hash = this.width || 0;
  4622. hash = (hash * 397) ^ (this.height || 0);
  4623. return hash;
  4624. };
  4625. /**
  4626. * Updates the current size from the given one.
  4627. * @param src the given size
  4628. */
  4629. Size.prototype.copyFrom = function (src) {
  4630. this.width = src.width;
  4631. this.height = src.height;
  4632. };
  4633. /**
  4634. * Updates in place the current Size from the given floats.
  4635. * @param width width of the new size
  4636. * @param height height of the new size
  4637. * @returns the updated Size.
  4638. */
  4639. Size.prototype.copyFromFloats = function (width, height) {
  4640. this.width = width;
  4641. this.height = height;
  4642. return this;
  4643. };
  4644. /**
  4645. * Updates in place the current Size from the given floats.
  4646. * @param width width to set
  4647. * @param height height to set
  4648. * @returns the updated Size.
  4649. */
  4650. Size.prototype.set = function (width, height) {
  4651. return this.copyFromFloats(width, height);
  4652. };
  4653. /**
  4654. * Multiplies the width and height by numbers
  4655. * @param w factor to multiple the width by
  4656. * @param h factor to multiple the height by
  4657. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4658. */
  4659. Size.prototype.multiplyByFloats = function (w, h) {
  4660. return new Size(this.width * w, this.height * h);
  4661. };
  4662. /**
  4663. * Clones the size
  4664. * @returns a new Size copied from the given one.
  4665. */
  4666. Size.prototype.clone = function () {
  4667. return new Size(this.width, this.height);
  4668. };
  4669. /**
  4670. * True if the current Size and the given one width and height are strictly equal.
  4671. * @param other the other size to compare against
  4672. * @returns True if the current Size and the given one width and height are strictly equal.
  4673. */
  4674. Size.prototype.equals = function (other) {
  4675. if (!other) {
  4676. return false;
  4677. }
  4678. return (this.width === other.width) && (this.height === other.height);
  4679. };
  4680. Object.defineProperty(Size.prototype, "surface", {
  4681. /**
  4682. * The surface of the Size : width * height (float).
  4683. */
  4684. get: function () {
  4685. return this.width * this.height;
  4686. },
  4687. enumerable: true,
  4688. configurable: true
  4689. });
  4690. /**
  4691. * Create a new size of zero
  4692. * @returns a new Size set to (0.0, 0.0)
  4693. */
  4694. Size.Zero = function () {
  4695. return new Size(0.0, 0.0);
  4696. };
  4697. /**
  4698. * Sums the width and height of two sizes
  4699. * @param otherSize size to add to this size
  4700. * @returns a new Size set as the addition result of the current Size and the given one.
  4701. */
  4702. Size.prototype.add = function (otherSize) {
  4703. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4704. return r;
  4705. };
  4706. /**
  4707. * Subtracts the width and height of two
  4708. * @param otherSize size to subtract to this size
  4709. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4710. */
  4711. Size.prototype.subtract = function (otherSize) {
  4712. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4713. return r;
  4714. };
  4715. /**
  4716. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4717. * @param start starting size to lerp between
  4718. * @param end end size to lerp between
  4719. * @param amount amount to lerp between the start and end values
  4720. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4721. */
  4722. Size.Lerp = function (start, end, amount) {
  4723. var w = start.width + ((end.width - start.width) * amount);
  4724. var h = start.height + ((end.height - start.height) * amount);
  4725. return new Size(w, h);
  4726. };
  4727. return Size;
  4728. }());
  4729. BABYLON.Size = Size;
  4730. /**
  4731. * Class used to store quaternion data
  4732. * @see https://en.wikipedia.org/wiki/Quaternion
  4733. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4734. */
  4735. var Quaternion = /** @class */ (function () {
  4736. /**
  4737. * Creates a new Quaternion from the given floats
  4738. * @param x defines the first component (0 by default)
  4739. * @param y defines the second component (0 by default)
  4740. * @param z defines the third component (0 by default)
  4741. * @param w defines the fourth component (1.0 by default)
  4742. */
  4743. function Quaternion(
  4744. /** defines the first component (0 by default) */
  4745. x,
  4746. /** defines the second component (0 by default) */
  4747. y,
  4748. /** defines the third component (0 by default) */
  4749. z,
  4750. /** defines the fourth component (1.0 by default) */
  4751. w) {
  4752. if (x === void 0) { x = 0.0; }
  4753. if (y === void 0) { y = 0.0; }
  4754. if (z === void 0) { z = 0.0; }
  4755. if (w === void 0) { w = 1.0; }
  4756. this.x = x;
  4757. this.y = y;
  4758. this.z = z;
  4759. this.w = w;
  4760. }
  4761. /**
  4762. * Gets a string representation for the current quaternion
  4763. * @returns a string with the Quaternion coordinates
  4764. */
  4765. Quaternion.prototype.toString = function () {
  4766. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4767. };
  4768. /**
  4769. * Gets the class name of the quaternion
  4770. * @returns the string "Quaternion"
  4771. */
  4772. Quaternion.prototype.getClassName = function () {
  4773. return "Quaternion";
  4774. };
  4775. /**
  4776. * Gets a hash code for this quaternion
  4777. * @returns the quaternion hash code
  4778. */
  4779. Quaternion.prototype.getHashCode = function () {
  4780. var hash = this.x || 0;
  4781. hash = (hash * 397) ^ (this.y || 0);
  4782. hash = (hash * 397) ^ (this.z || 0);
  4783. hash = (hash * 397) ^ (this.w || 0);
  4784. return hash;
  4785. };
  4786. /**
  4787. * Copy the quaternion to an array
  4788. * @returns a new array populated with 4 elements from the quaternion coordinates
  4789. */
  4790. Quaternion.prototype.asArray = function () {
  4791. return [this.x, this.y, this.z, this.w];
  4792. };
  4793. /**
  4794. * Check if two quaternions are equals
  4795. * @param otherQuaternion defines the second operand
  4796. * @return true if the current quaternion and the given one coordinates are strictly equals
  4797. */
  4798. Quaternion.prototype.equals = function (otherQuaternion) {
  4799. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4800. };
  4801. /**
  4802. * Clone the current quaternion
  4803. * @returns a new quaternion copied from the current one
  4804. */
  4805. Quaternion.prototype.clone = function () {
  4806. return new Quaternion(this.x, this.y, this.z, this.w);
  4807. };
  4808. /**
  4809. * Copy a quaternion to the current one
  4810. * @param other defines the other quaternion
  4811. * @returns the updated current quaternion
  4812. */
  4813. Quaternion.prototype.copyFrom = function (other) {
  4814. this.x = other.x;
  4815. this.y = other.y;
  4816. this.z = other.z;
  4817. this.w = other.w;
  4818. return this;
  4819. };
  4820. /**
  4821. * Updates the current quaternion with the given float coordinates
  4822. * @param x defines the x coordinate
  4823. * @param y defines the y coordinate
  4824. * @param z defines the z coordinate
  4825. * @param w defines the w coordinate
  4826. * @returns the updated current quaternion
  4827. */
  4828. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4829. this.x = x;
  4830. this.y = y;
  4831. this.z = z;
  4832. this.w = w;
  4833. return this;
  4834. };
  4835. /**
  4836. * Updates the current quaternion from the given float coordinates
  4837. * @param x defines the x coordinate
  4838. * @param y defines the y coordinate
  4839. * @param z defines the z coordinate
  4840. * @param w defines the w coordinate
  4841. * @returns the updated current quaternion
  4842. */
  4843. Quaternion.prototype.set = function (x, y, z, w) {
  4844. return this.copyFromFloats(x, y, z, w);
  4845. };
  4846. /**
  4847. * Adds two quaternions
  4848. * @param other defines the second operand
  4849. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4850. */
  4851. Quaternion.prototype.add = function (other) {
  4852. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4853. };
  4854. /**
  4855. * Add a quaternion to the current one
  4856. * @param other defines the quaternion to add
  4857. * @returns the current quaternion
  4858. */
  4859. Quaternion.prototype.addInPlace = function (other) {
  4860. this.x += other.x;
  4861. this.y += other.y;
  4862. this.z += other.z;
  4863. this.w += other.w;
  4864. return this;
  4865. };
  4866. /**
  4867. * Subtract two quaternions
  4868. * @param other defines the second operand
  4869. * @returns a new quaternion as the subtraction result of the given one from the current one
  4870. */
  4871. Quaternion.prototype.subtract = function (other) {
  4872. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4873. };
  4874. /**
  4875. * Multiplies the current quaternion by a scale factor
  4876. * @param value defines the scale factor
  4877. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4878. */
  4879. Quaternion.prototype.scale = function (value) {
  4880. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4881. };
  4882. /**
  4883. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4884. * @param scale defines the scale factor
  4885. * @param result defines the Quaternion object where to store the result
  4886. * @returns the unmodified current quaternion
  4887. */
  4888. Quaternion.prototype.scaleToRef = function (scale, result) {
  4889. result.x = this.x * scale;
  4890. result.y = this.y * scale;
  4891. result.z = this.z * scale;
  4892. result.w = this.w * scale;
  4893. return this;
  4894. };
  4895. /**
  4896. * Multiplies in place the current quaternion by a scale factor
  4897. * @param value defines the scale factor
  4898. * @returns the current modified quaternion
  4899. */
  4900. Quaternion.prototype.scaleInPlace = function (value) {
  4901. this.x *= value;
  4902. this.y *= value;
  4903. this.z *= value;
  4904. this.w *= value;
  4905. return this;
  4906. };
  4907. /**
  4908. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4909. * @param scale defines the scale factor
  4910. * @param result defines the Quaternion object where to store the result
  4911. * @returns the unmodified current quaternion
  4912. */
  4913. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4914. result.x += this.x * scale;
  4915. result.y += this.y * scale;
  4916. result.z += this.z * scale;
  4917. result.w += this.w * scale;
  4918. return this;
  4919. };
  4920. /**
  4921. * Multiplies two quaternions
  4922. * @param q1 defines the second operand
  4923. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4924. */
  4925. Quaternion.prototype.multiply = function (q1) {
  4926. var result = new Quaternion(0, 0, 0, 1.0);
  4927. this.multiplyToRef(q1, result);
  4928. return result;
  4929. };
  4930. /**
  4931. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4932. * @param q1 defines the second operand
  4933. * @param result defines the target quaternion
  4934. * @returns the current quaternion
  4935. */
  4936. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4937. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4938. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4939. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4940. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4941. result.copyFromFloats(x, y, z, w);
  4942. return this;
  4943. };
  4944. /**
  4945. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4946. * @param q1 defines the second operand
  4947. * @returns the currentupdated quaternion
  4948. */
  4949. Quaternion.prototype.multiplyInPlace = function (q1) {
  4950. this.multiplyToRef(q1, this);
  4951. return this;
  4952. };
  4953. /**
  4954. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4955. * @param ref defines the target quaternion
  4956. * @returns the current quaternion
  4957. */
  4958. Quaternion.prototype.conjugateToRef = function (ref) {
  4959. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4960. return this;
  4961. };
  4962. /**
  4963. * Conjugates in place (1-q) the current quaternion
  4964. * @returns the current updated quaternion
  4965. */
  4966. Quaternion.prototype.conjugateInPlace = function () {
  4967. this.x *= -1;
  4968. this.y *= -1;
  4969. this.z *= -1;
  4970. return this;
  4971. };
  4972. /**
  4973. * Conjugates in place (1-q) the current quaternion
  4974. * @returns a new quaternion
  4975. */
  4976. Quaternion.prototype.conjugate = function () {
  4977. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4978. return result;
  4979. };
  4980. /**
  4981. * Gets length of current quaternion
  4982. * @returns the quaternion length (float)
  4983. */
  4984. Quaternion.prototype.length = function () {
  4985. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4986. };
  4987. /**
  4988. * Normalize in place the current quaternion
  4989. * @returns the current updated quaternion
  4990. */
  4991. Quaternion.prototype.normalize = function () {
  4992. var length = 1.0 / this.length();
  4993. this.x *= length;
  4994. this.y *= length;
  4995. this.z *= length;
  4996. this.w *= length;
  4997. return this;
  4998. };
  4999. /**
  5000. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  5001. * @param order is a reserved parameter and is ignore for now
  5002. * @returns a new Vector3 containing the Euler angles
  5003. */
  5004. Quaternion.prototype.toEulerAngles = function (order) {
  5005. if (order === void 0) { order = "YZX"; }
  5006. var result = Vector3.Zero();
  5007. this.toEulerAnglesToRef(result, order);
  5008. return result;
  5009. };
  5010. /**
  5011. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  5012. * @param result defines the vector which will be filled with the Euler angles
  5013. * @param order is a reserved parameter and is ignore for now
  5014. * @returns the current unchanged quaternion
  5015. */
  5016. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  5017. if (order === void 0) { order = "YZX"; }
  5018. var qz = this.z;
  5019. var qx = this.x;
  5020. var qy = this.y;
  5021. var qw = this.w;
  5022. var sqw = qw * qw;
  5023. var sqz = qz * qz;
  5024. var sqx = qx * qx;
  5025. var sqy = qy * qy;
  5026. var zAxisY = qy * qz - qx * qw;
  5027. var limit = .4999999;
  5028. if (zAxisY < -limit) {
  5029. result.y = 2 * Math.atan2(qy, qw);
  5030. result.x = Math.PI / 2;
  5031. result.z = 0;
  5032. }
  5033. else if (zAxisY > limit) {
  5034. result.y = 2 * Math.atan2(qy, qw);
  5035. result.x = -Math.PI / 2;
  5036. result.z = 0;
  5037. }
  5038. else {
  5039. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  5040. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  5041. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  5042. }
  5043. return this;
  5044. };
  5045. /**
  5046. * Updates the given rotation matrix with the current quaternion values
  5047. * @param result defines the target matrix
  5048. * @returns the current unchanged quaternion
  5049. */
  5050. Quaternion.prototype.toRotationMatrix = function (result) {
  5051. var xx = this.x * this.x;
  5052. var yy = this.y * this.y;
  5053. var zz = this.z * this.z;
  5054. var xy = this.x * this.y;
  5055. var zw = this.z * this.w;
  5056. var zx = this.z * this.x;
  5057. var yw = this.y * this.w;
  5058. var yz = this.y * this.z;
  5059. var xw = this.x * this.w;
  5060. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5061. result.m[1] = 2.0 * (xy + zw);
  5062. result.m[2] = 2.0 * (zx - yw);
  5063. result.m[3] = 0;
  5064. result.m[4] = 2.0 * (xy - zw);
  5065. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5066. result.m[6] = 2.0 * (yz + xw);
  5067. result.m[7] = 0;
  5068. result.m[8] = 2.0 * (zx + yw);
  5069. result.m[9] = 2.0 * (yz - xw);
  5070. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5071. result.m[11] = 0;
  5072. result.m[12] = 0;
  5073. result.m[13] = 0;
  5074. result.m[14] = 0;
  5075. result.m[15] = 1.0;
  5076. result._markAsUpdated();
  5077. return this;
  5078. };
  5079. /**
  5080. * Updates the current quaternion from the given rotation matrix values
  5081. * @param matrix defines the source matrix
  5082. * @returns the current updated quaternion
  5083. */
  5084. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5085. Quaternion.FromRotationMatrixToRef(matrix, this);
  5086. return this;
  5087. };
  5088. // Statics
  5089. /**
  5090. * Creates a new quaternion from a rotation matrix
  5091. * @param matrix defines the source matrix
  5092. * @returns a new quaternion created from the given rotation matrix values
  5093. */
  5094. Quaternion.FromRotationMatrix = function (matrix) {
  5095. var result = new Quaternion();
  5096. Quaternion.FromRotationMatrixToRef(matrix, result);
  5097. return result;
  5098. };
  5099. /**
  5100. * Updates the given quaternion with the given rotation matrix values
  5101. * @param matrix defines the source matrix
  5102. * @param result defines the target quaternion
  5103. */
  5104. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5105. var data = matrix.m;
  5106. var m11 = data[0], m12 = data[4], m13 = data[8];
  5107. var m21 = data[1], m22 = data[5], m23 = data[9];
  5108. var m31 = data[2], m32 = data[6], m33 = data[10];
  5109. var trace = m11 + m22 + m33;
  5110. var s;
  5111. if (trace > 0) {
  5112. s = 0.5 / Math.sqrt(trace + 1.0);
  5113. result.w = 0.25 / s;
  5114. result.x = (m32 - m23) * s;
  5115. result.y = (m13 - m31) * s;
  5116. result.z = (m21 - m12) * s;
  5117. }
  5118. else if (m11 > m22 && m11 > m33) {
  5119. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5120. result.w = (m32 - m23) / s;
  5121. result.x = 0.25 * s;
  5122. result.y = (m12 + m21) / s;
  5123. result.z = (m13 + m31) / s;
  5124. }
  5125. else if (m22 > m33) {
  5126. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5127. result.w = (m13 - m31) / s;
  5128. result.x = (m12 + m21) / s;
  5129. result.y = 0.25 * s;
  5130. result.z = (m23 + m32) / s;
  5131. }
  5132. else {
  5133. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5134. result.w = (m21 - m12) / s;
  5135. result.x = (m13 + m31) / s;
  5136. result.y = (m23 + m32) / s;
  5137. result.z = 0.25 * s;
  5138. }
  5139. };
  5140. /**
  5141. * Returns the dot product (float) between the quaternions "left" and "right"
  5142. * @param left defines the left operand
  5143. * @param right defines the right operand
  5144. * @returns the dot product
  5145. */
  5146. Quaternion.Dot = function (left, right) {
  5147. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5148. };
  5149. /**
  5150. * Checks if the two quaternions are close to each other
  5151. * @param quat0 defines the first quaternion to check
  5152. * @param quat1 defines the second quaternion to check
  5153. * @returns true if the two quaternions are close to each other
  5154. */
  5155. Quaternion.AreClose = function (quat0, quat1) {
  5156. var dot = Quaternion.Dot(quat0, quat1);
  5157. return dot >= 0;
  5158. };
  5159. /**
  5160. * Creates an empty quaternion
  5161. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5162. */
  5163. Quaternion.Zero = function () {
  5164. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5165. };
  5166. /**
  5167. * Inverse a given quaternion
  5168. * @param q defines the source quaternion
  5169. * @returns a new quaternion as the inverted current quaternion
  5170. */
  5171. Quaternion.Inverse = function (q) {
  5172. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5173. };
  5174. /**
  5175. * Creates an identity quaternion
  5176. * @returns the identity quaternion
  5177. */
  5178. Quaternion.Identity = function () {
  5179. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5180. };
  5181. /**
  5182. * Gets a boolean indicating if the given quaternion is identity
  5183. * @param quaternion defines the quaternion to check
  5184. * @returns true if the quaternion is identity
  5185. */
  5186. Quaternion.IsIdentity = function (quaternion) {
  5187. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5188. };
  5189. /**
  5190. * Creates a quaternion from a rotation around an axis
  5191. * @param axis defines the axis to use
  5192. * @param angle defines the angle to use
  5193. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5194. */
  5195. Quaternion.RotationAxis = function (axis, angle) {
  5196. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5197. };
  5198. /**
  5199. * Creates a rotation around an axis and stores it into the given quaternion
  5200. * @param axis defines the axis to use
  5201. * @param angle defines the angle to use
  5202. * @param result defines the target quaternion
  5203. * @returns the target quaternion
  5204. */
  5205. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5206. var sin = Math.sin(angle / 2);
  5207. axis.normalize();
  5208. result.w = Math.cos(angle / 2);
  5209. result.x = axis.x * sin;
  5210. result.y = axis.y * sin;
  5211. result.z = axis.z * sin;
  5212. return result;
  5213. };
  5214. /**
  5215. * Creates a new quaternion from data stored into an array
  5216. * @param array defines the data source
  5217. * @param offset defines the offset in the source array where the data starts
  5218. * @returns a new quaternion
  5219. */
  5220. Quaternion.FromArray = function (array, offset) {
  5221. if (!offset) {
  5222. offset = 0;
  5223. }
  5224. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5225. };
  5226. /**
  5227. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5228. * @param yaw defines the rotation around Y axis
  5229. * @param pitch defines the rotation around X axis
  5230. * @param roll defines the rotation around Z axis
  5231. * @returns the new quaternion
  5232. */
  5233. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5234. var q = new Quaternion();
  5235. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5236. return q;
  5237. };
  5238. /**
  5239. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5240. * @param yaw defines the rotation around Y axis
  5241. * @param pitch defines the rotation around X axis
  5242. * @param roll defines the rotation around Z axis
  5243. * @param result defines the target quaternion
  5244. */
  5245. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5246. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5247. var halfRoll = roll * 0.5;
  5248. var halfPitch = pitch * 0.5;
  5249. var halfYaw = yaw * 0.5;
  5250. var sinRoll = Math.sin(halfRoll);
  5251. var cosRoll = Math.cos(halfRoll);
  5252. var sinPitch = Math.sin(halfPitch);
  5253. var cosPitch = Math.cos(halfPitch);
  5254. var sinYaw = Math.sin(halfYaw);
  5255. var cosYaw = Math.cos(halfYaw);
  5256. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5257. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5258. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5259. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5260. };
  5261. /**
  5262. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5263. * @param alpha defines the rotation around first axis
  5264. * @param beta defines the rotation around second axis
  5265. * @param gamma defines the rotation around third axis
  5266. * @returns the new quaternion
  5267. */
  5268. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5269. var result = new Quaternion();
  5270. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5271. return result;
  5272. };
  5273. /**
  5274. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5275. * @param alpha defines the rotation around first axis
  5276. * @param beta defines the rotation around second axis
  5277. * @param gamma defines the rotation around third axis
  5278. * @param result defines the target quaternion
  5279. */
  5280. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5281. // Produces a quaternion from Euler angles in the z-x-z orientation
  5282. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5283. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5284. var halfBeta = beta * 0.5;
  5285. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5286. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5287. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5288. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5289. };
  5290. /**
  5291. * 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)
  5292. * @param axis1 defines the first axis
  5293. * @param axis2 defines the second axis
  5294. * @param axis3 defines the third axis
  5295. * @returns the new quaternion
  5296. */
  5297. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5298. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5299. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5300. return quat;
  5301. };
  5302. /**
  5303. * 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
  5304. * @param axis1 defines the first axis
  5305. * @param axis2 defines the second axis
  5306. * @param axis3 defines the third axis
  5307. * @param ref defines the target quaternion
  5308. */
  5309. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5310. var rotMat = MathTmp.Matrix[0];
  5311. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5312. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5313. };
  5314. /**
  5315. * Interpolates between two quaternions
  5316. * @param left defines first quaternion
  5317. * @param right defines second quaternion
  5318. * @param amount defines the gradient to use
  5319. * @returns the new interpolated quaternion
  5320. */
  5321. Quaternion.Slerp = function (left, right, amount) {
  5322. var result = Quaternion.Identity();
  5323. Quaternion.SlerpToRef(left, right, amount, result);
  5324. return result;
  5325. };
  5326. /**
  5327. * Interpolates between two quaternions and stores it into a target quaternion
  5328. * @param left defines first quaternion
  5329. * @param right defines second quaternion
  5330. * @param amount defines the gradient to use
  5331. * @param result defines the target quaternion
  5332. */
  5333. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5334. var num2;
  5335. var num3;
  5336. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5337. var flag = false;
  5338. if (num4 < 0) {
  5339. flag = true;
  5340. num4 = -num4;
  5341. }
  5342. if (num4 > 0.999999) {
  5343. num3 = 1 - amount;
  5344. num2 = flag ? -amount : amount;
  5345. }
  5346. else {
  5347. var num5 = Math.acos(num4);
  5348. var num6 = (1.0 / Math.sin(num5));
  5349. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5350. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5351. }
  5352. result.x = (num3 * left.x) + (num2 * right.x);
  5353. result.y = (num3 * left.y) + (num2 * right.y);
  5354. result.z = (num3 * left.z) + (num2 * right.z);
  5355. result.w = (num3 * left.w) + (num2 * right.w);
  5356. };
  5357. /**
  5358. * Interpolate between two quaternions using Hermite interpolation
  5359. * @param value1 defines first quaternion
  5360. * @param tangent1 defines the incoming tangent
  5361. * @param value2 defines second quaternion
  5362. * @param tangent2 defines the outgoing tangent
  5363. * @param amount defines the target quaternion
  5364. * @returns the new interpolated quaternion
  5365. */
  5366. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5367. var squared = amount * amount;
  5368. var cubed = amount * squared;
  5369. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5370. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5371. var part3 = (cubed - (2.0 * squared)) + amount;
  5372. var part4 = cubed - squared;
  5373. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5374. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5375. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5376. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5377. return new Quaternion(x, y, z, w);
  5378. };
  5379. return Quaternion;
  5380. }());
  5381. BABYLON.Quaternion = Quaternion;
  5382. /**
  5383. * Class used to store matrix data (4x4)
  5384. */
  5385. var Matrix = /** @class */ (function () {
  5386. /**
  5387. * Creates an empty matrix (filled with zeros)
  5388. */
  5389. function Matrix() {
  5390. this._isIdentity = false;
  5391. this._isIdentityDirty = true;
  5392. /**
  5393. * Gets or sets the internal data of the matrix
  5394. */
  5395. this.m = new Float32Array(16);
  5396. this._markAsUpdated();
  5397. }
  5398. /** @hidden */
  5399. Matrix.prototype._markAsUpdated = function () {
  5400. this.updateFlag = Matrix._updateFlagSeed++;
  5401. this._isIdentityDirty = true;
  5402. };
  5403. // Properties
  5404. /**
  5405. * Check if the current matrix is indentity
  5406. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5407. * @returns true is the matrix is the identity matrix
  5408. */
  5409. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5410. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5411. if (this._isIdentityDirty) {
  5412. this._isIdentityDirty = false;
  5413. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5414. this._isIdentity = false;
  5415. }
  5416. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5417. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5418. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5419. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5420. this._isIdentity = false;
  5421. }
  5422. else {
  5423. this._isIdentity = true;
  5424. }
  5425. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5426. this._isIdentity = false;
  5427. }
  5428. }
  5429. return this._isIdentity;
  5430. };
  5431. /**
  5432. * Gets the determinant of the matrix
  5433. * @returns the matrix determinant
  5434. */
  5435. Matrix.prototype.determinant = function () {
  5436. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5437. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5438. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5439. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5440. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5441. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5442. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5443. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5444. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5445. };
  5446. // Methods
  5447. /**
  5448. * Returns the matrix as a Float32Array
  5449. * @returns the matrix underlying array
  5450. */
  5451. Matrix.prototype.toArray = function () {
  5452. return this.m;
  5453. };
  5454. /**
  5455. * Returns the matrix as a Float32Array
  5456. * @returns the matrix underlying array.
  5457. */
  5458. Matrix.prototype.asArray = function () {
  5459. return this.toArray();
  5460. };
  5461. /**
  5462. * Inverts the current matrix in place
  5463. * @returns the current inverted matrix
  5464. */
  5465. Matrix.prototype.invert = function () {
  5466. this.invertToRef(this);
  5467. return this;
  5468. };
  5469. /**
  5470. * Sets all the matrix elements to zero
  5471. * @returns the current matrix
  5472. */
  5473. Matrix.prototype.reset = function () {
  5474. for (var index = 0; index < 16; index++) {
  5475. this.m[index] = 0.0;
  5476. }
  5477. this._markAsUpdated();
  5478. return this;
  5479. };
  5480. /**
  5481. * Adds the current matrix with a second one
  5482. * @param other defines the matrix to add
  5483. * @returns a new matrix as the addition of the current matrix and the given one
  5484. */
  5485. Matrix.prototype.add = function (other) {
  5486. var result = new Matrix();
  5487. this.addToRef(other, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5492. * @param other defines the matrix to add
  5493. * @param result defines the target matrix
  5494. * @returns the current matrix
  5495. */
  5496. Matrix.prototype.addToRef = function (other, result) {
  5497. for (var index = 0; index < 16; index++) {
  5498. result.m[index] = this.m[index] + other.m[index];
  5499. }
  5500. result._markAsUpdated();
  5501. return this;
  5502. };
  5503. /**
  5504. * Adds in place the given matrix to the current matrix
  5505. * @param other defines the second operand
  5506. * @returns the current updated matrix
  5507. */
  5508. Matrix.prototype.addToSelf = function (other) {
  5509. for (var index = 0; index < 16; index++) {
  5510. this.m[index] += other.m[index];
  5511. }
  5512. this._markAsUpdated();
  5513. return this;
  5514. };
  5515. /**
  5516. * Sets the given matrix to the current inverted Matrix
  5517. * @param other defines the target matrix
  5518. * @returns the unmodified current matrix
  5519. */
  5520. Matrix.prototype.invertToRef = function (other) {
  5521. var l1 = this.m[0];
  5522. var l2 = this.m[1];
  5523. var l3 = this.m[2];
  5524. var l4 = this.m[3];
  5525. var l5 = this.m[4];
  5526. var l6 = this.m[5];
  5527. var l7 = this.m[6];
  5528. var l8 = this.m[7];
  5529. var l9 = this.m[8];
  5530. var l10 = this.m[9];
  5531. var l11 = this.m[10];
  5532. var l12 = this.m[11];
  5533. var l13 = this.m[12];
  5534. var l14 = this.m[13];
  5535. var l15 = this.m[14];
  5536. var l16 = this.m[15];
  5537. var l17 = (l11 * l16) - (l12 * l15);
  5538. var l18 = (l10 * l16) - (l12 * l14);
  5539. var l19 = (l10 * l15) - (l11 * l14);
  5540. var l20 = (l9 * l16) - (l12 * l13);
  5541. var l21 = (l9 * l15) - (l11 * l13);
  5542. var l22 = (l9 * l14) - (l10 * l13);
  5543. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5544. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5545. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5546. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5547. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5548. var l28 = (l7 * l16) - (l8 * l15);
  5549. var l29 = (l6 * l16) - (l8 * l14);
  5550. var l30 = (l6 * l15) - (l7 * l14);
  5551. var l31 = (l5 * l16) - (l8 * l13);
  5552. var l32 = (l5 * l15) - (l7 * l13);
  5553. var l33 = (l5 * l14) - (l6 * l13);
  5554. var l34 = (l7 * l12) - (l8 * l11);
  5555. var l35 = (l6 * l12) - (l8 * l10);
  5556. var l36 = (l6 * l11) - (l7 * l10);
  5557. var l37 = (l5 * l12) - (l8 * l9);
  5558. var l38 = (l5 * l11) - (l7 * l9);
  5559. var l39 = (l5 * l10) - (l6 * l9);
  5560. other.m[0] = l23 * l27;
  5561. other.m[4] = l24 * l27;
  5562. other.m[8] = l25 * l27;
  5563. other.m[12] = l26 * l27;
  5564. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5565. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5566. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5567. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5568. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5569. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5570. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5571. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5572. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5573. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5574. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5575. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5576. other._markAsUpdated();
  5577. return this;
  5578. };
  5579. /**
  5580. * Inserts the translation vector (using 3 floats) in the current matrix
  5581. * @param x defines the 1st component of the translation
  5582. * @param y defines the 2nd component of the translation
  5583. * @param z defines the 3rd component of the translation
  5584. * @returns the current updated matrix
  5585. */
  5586. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5587. this.m[12] = x;
  5588. this.m[13] = y;
  5589. this.m[14] = z;
  5590. this._markAsUpdated();
  5591. return this;
  5592. };
  5593. /**
  5594. * Inserts the translation vector in the current matrix
  5595. * @param vector3 defines the translation to insert
  5596. * @returns the current updated matrix
  5597. */
  5598. Matrix.prototype.setTranslation = function (vector3) {
  5599. this.m[12] = vector3.x;
  5600. this.m[13] = vector3.y;
  5601. this.m[14] = vector3.z;
  5602. this._markAsUpdated();
  5603. return this;
  5604. };
  5605. /**
  5606. * Gets the translation value of the current matrix
  5607. * @returns a new Vector3 as the extracted translation from the matrix
  5608. */
  5609. Matrix.prototype.getTranslation = function () {
  5610. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5611. };
  5612. /**
  5613. * Fill a Vector3 with the extracted translation from the matrix
  5614. * @param result defines the Vector3 where to store the translation
  5615. * @returns the current matrix
  5616. */
  5617. Matrix.prototype.getTranslationToRef = function (result) {
  5618. result.x = this.m[12];
  5619. result.y = this.m[13];
  5620. result.z = this.m[14];
  5621. return this;
  5622. };
  5623. /**
  5624. * Remove rotation and scaling part from the matrix
  5625. * @returns the updated matrix
  5626. */
  5627. Matrix.prototype.removeRotationAndScaling = function () {
  5628. this.setRowFromFloats(0, 1, 0, 0, 0);
  5629. this.setRowFromFloats(1, 0, 1, 0, 0);
  5630. this.setRowFromFloats(2, 0, 0, 1, 0);
  5631. return this;
  5632. };
  5633. /**
  5634. * Multiply two matrices
  5635. * @param other defines the second operand
  5636. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5637. */
  5638. Matrix.prototype.multiply = function (other) {
  5639. var result = new Matrix();
  5640. this.multiplyToRef(other, result);
  5641. return result;
  5642. };
  5643. /**
  5644. * Copy the current matrix from the given one
  5645. * @param other defines the source matrix
  5646. * @returns the current updated matrix
  5647. */
  5648. Matrix.prototype.copyFrom = function (other) {
  5649. for (var index = 0; index < 16; index++) {
  5650. this.m[index] = other.m[index];
  5651. }
  5652. this._markAsUpdated();
  5653. return this;
  5654. };
  5655. /**
  5656. * Populates the given array from the starting index with the current matrix values
  5657. * @param array defines the target array
  5658. * @param offset defines the offset in the target array where to start storing values
  5659. * @returns the current matrix
  5660. */
  5661. Matrix.prototype.copyToArray = function (array, offset) {
  5662. if (offset === void 0) { offset = 0; }
  5663. for (var index = 0; index < 16; index++) {
  5664. array[offset + index] = this.m[index];
  5665. }
  5666. return this;
  5667. };
  5668. /**
  5669. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5670. * @param other defines the second operand
  5671. * @param result defines the matrix where to store the multiplication
  5672. * @returns the current matrix
  5673. */
  5674. Matrix.prototype.multiplyToRef = function (other, result) {
  5675. this.multiplyToArray(other, result.m, 0);
  5676. result._markAsUpdated();
  5677. return this;
  5678. };
  5679. /**
  5680. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5681. * @param other defines the second operand
  5682. * @param result defines the array where to store the multiplication
  5683. * @param offset defines the offset in the target array where to start storing values
  5684. * @returns the current matrix
  5685. */
  5686. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5687. var tm0 = this.m[0];
  5688. var tm1 = this.m[1];
  5689. var tm2 = this.m[2];
  5690. var tm3 = this.m[3];
  5691. var tm4 = this.m[4];
  5692. var tm5 = this.m[5];
  5693. var tm6 = this.m[6];
  5694. var tm7 = this.m[7];
  5695. var tm8 = this.m[8];
  5696. var tm9 = this.m[9];
  5697. var tm10 = this.m[10];
  5698. var tm11 = this.m[11];
  5699. var tm12 = this.m[12];
  5700. var tm13 = this.m[13];
  5701. var tm14 = this.m[14];
  5702. var tm15 = this.m[15];
  5703. var om0 = other.m[0];
  5704. var om1 = other.m[1];
  5705. var om2 = other.m[2];
  5706. var om3 = other.m[3];
  5707. var om4 = other.m[4];
  5708. var om5 = other.m[5];
  5709. var om6 = other.m[6];
  5710. var om7 = other.m[7];
  5711. var om8 = other.m[8];
  5712. var om9 = other.m[9];
  5713. var om10 = other.m[10];
  5714. var om11 = other.m[11];
  5715. var om12 = other.m[12];
  5716. var om13 = other.m[13];
  5717. var om14 = other.m[14];
  5718. var om15 = other.m[15];
  5719. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5720. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5721. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5722. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5723. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5724. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5725. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5726. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5727. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5728. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5729. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5730. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5731. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5732. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5733. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5734. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5735. return this;
  5736. };
  5737. /**
  5738. * Check equality between this matrix and a second one
  5739. * @param value defines the second matrix to compare
  5740. * @returns true is the current matrix and the given one values are strictly equal
  5741. */
  5742. Matrix.prototype.equals = function (value) {
  5743. return value &&
  5744. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5745. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5746. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5747. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5748. };
  5749. /**
  5750. * Clone the current matrix
  5751. * @returns a new matrix from the current matrix
  5752. */
  5753. Matrix.prototype.clone = function () {
  5754. 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]);
  5755. };
  5756. /**
  5757. * Returns the name of the current matrix class
  5758. * @returns the string "Matrix"
  5759. */
  5760. Matrix.prototype.getClassName = function () {
  5761. return "Matrix";
  5762. };
  5763. /**
  5764. * Gets the hash code of the current matrix
  5765. * @returns the hash code
  5766. */
  5767. Matrix.prototype.getHashCode = function () {
  5768. var hash = this.m[0] || 0;
  5769. for (var i = 1; i < 16; i++) {
  5770. hash = (hash * 397) ^ (this.m[i] || 0);
  5771. }
  5772. return hash;
  5773. };
  5774. /**
  5775. * Decomposes the current Matrix into a translation, rotation and scaling components
  5776. * @param scale defines the scale vector3 given as a reference to update
  5777. * @param rotation defines the rotation quaternion given as a reference to update
  5778. * @param translation defines the translation vector3 given as a reference to update
  5779. * @returns true if operation was successful
  5780. */
  5781. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5782. if (translation) {
  5783. translation.x = this.m[12];
  5784. translation.y = this.m[13];
  5785. translation.z = this.m[14];
  5786. }
  5787. scale = scale || MathTmp.Vector3[0];
  5788. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5789. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5790. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5791. if (this.determinant() <= 0) {
  5792. scale.y *= -1;
  5793. }
  5794. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5795. if (rotation) {
  5796. rotation.x = 0;
  5797. rotation.y = 0;
  5798. rotation.z = 0;
  5799. rotation.w = 1;
  5800. }
  5801. return false;
  5802. }
  5803. if (rotation) {
  5804. 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]);
  5805. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5806. }
  5807. return true;
  5808. };
  5809. /**
  5810. * Gets specific row of the matrix
  5811. * @param index defines the number of the row to get
  5812. * @returns the index-th row of the current matrix as a new Vector4
  5813. */
  5814. Matrix.prototype.getRow = function (index) {
  5815. if (index < 0 || index > 3) {
  5816. return null;
  5817. }
  5818. var i = index * 4;
  5819. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5820. };
  5821. /**
  5822. * Sets the index-th row of the current matrix to the vector4 values
  5823. * @param index defines the number of the row to set
  5824. * @param row defines the target vector4
  5825. * @returns the updated current matrix
  5826. */
  5827. Matrix.prototype.setRow = function (index, row) {
  5828. if (index < 0 || index > 3) {
  5829. return this;
  5830. }
  5831. var i = index * 4;
  5832. this.m[i + 0] = row.x;
  5833. this.m[i + 1] = row.y;
  5834. this.m[i + 2] = row.z;
  5835. this.m[i + 3] = row.w;
  5836. this._markAsUpdated();
  5837. return this;
  5838. };
  5839. /**
  5840. * Compute the transpose of the matrix
  5841. * @returns the new transposed matrix
  5842. */
  5843. Matrix.prototype.transpose = function () {
  5844. return Matrix.Transpose(this);
  5845. };
  5846. /**
  5847. * Compute the transpose of the matrix and store it in a given matrix
  5848. * @param result defines the target matrix
  5849. * @returns the current matrix
  5850. */
  5851. Matrix.prototype.transposeToRef = function (result) {
  5852. Matrix.TransposeToRef(this, result);
  5853. return this;
  5854. };
  5855. /**
  5856. * Sets the index-th row of the current matrix with the given 4 x float values
  5857. * @param index defines the row index
  5858. * @param x defines the x component to set
  5859. * @param y defines the y component to set
  5860. * @param z defines the z component to set
  5861. * @param w defines the w component to set
  5862. * @returns the updated current matrix
  5863. */
  5864. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5865. if (index < 0 || index > 3) {
  5866. return this;
  5867. }
  5868. var i = index * 4;
  5869. this.m[i + 0] = x;
  5870. this.m[i + 1] = y;
  5871. this.m[i + 2] = z;
  5872. this.m[i + 3] = w;
  5873. this._markAsUpdated();
  5874. return this;
  5875. };
  5876. /**
  5877. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5878. * @param scale defines the scale factor
  5879. * @returns a new matrix
  5880. */
  5881. Matrix.prototype.scale = function (scale) {
  5882. var result = new Matrix();
  5883. this.scaleToRef(scale, result);
  5884. return result;
  5885. };
  5886. /**
  5887. * Scale the current matrix values by a factor to a given result matrix
  5888. * @param scale defines the scale factor
  5889. * @param result defines the matrix to store the result
  5890. * @returns the current matrix
  5891. */
  5892. Matrix.prototype.scaleToRef = function (scale, result) {
  5893. for (var index = 0; index < 16; index++) {
  5894. result.m[index] = this.m[index] * scale;
  5895. }
  5896. result._markAsUpdated();
  5897. return this;
  5898. };
  5899. /**
  5900. * Scale the current matrix values by a factor and add the result to a given matrix
  5901. * @param scale defines the scale factor
  5902. * @param result defines the Matrix to store the result
  5903. * @returns the current matrix
  5904. */
  5905. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5906. for (var index = 0; index < 16; index++) {
  5907. result.m[index] += this.m[index] * scale;
  5908. }
  5909. result._markAsUpdated();
  5910. return this;
  5911. };
  5912. /**
  5913. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5914. * @param ref matrix to store the result
  5915. */
  5916. Matrix.prototype.toNormalMatrix = function (ref) {
  5917. this.invertToRef(ref);
  5918. ref.transpose();
  5919. var m = ref.m;
  5920. 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);
  5921. };
  5922. /**
  5923. * Gets only rotation part of the current matrix
  5924. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5925. */
  5926. Matrix.prototype.getRotationMatrix = function () {
  5927. var result = Matrix.Identity();
  5928. this.getRotationMatrixToRef(result);
  5929. return result;
  5930. };
  5931. /**
  5932. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5933. * @param result defines the target matrix to store data to
  5934. * @returns the current matrix
  5935. */
  5936. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5937. var m = this.m;
  5938. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5939. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5940. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5941. if (this.determinant() <= 0) {
  5942. sy *= -1;
  5943. }
  5944. if (sx === 0 || sy === 0 || sz === 0) {
  5945. Matrix.IdentityToRef(result);
  5946. }
  5947. else {
  5948. 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);
  5949. }
  5950. return this;
  5951. };
  5952. // Statics
  5953. /**
  5954. * Creates a matrix from an array
  5955. * @param array defines the source array
  5956. * @param offset defines an offset in the source array
  5957. * @returns a new Matrix set from the starting index of the given array
  5958. */
  5959. Matrix.FromArray = function (array, offset) {
  5960. var result = new Matrix();
  5961. if (!offset) {
  5962. offset = 0;
  5963. }
  5964. Matrix.FromArrayToRef(array, offset, result);
  5965. return result;
  5966. };
  5967. /**
  5968. * Copy the content of an array into a given matrix
  5969. * @param array defines the source array
  5970. * @param offset defines an offset in the source array
  5971. * @param result defines the target matrix
  5972. */
  5973. Matrix.FromArrayToRef = function (array, offset, result) {
  5974. for (var index = 0; index < 16; index++) {
  5975. result.m[index] = array[index + offset];
  5976. }
  5977. result._markAsUpdated();
  5978. };
  5979. /**
  5980. * Stores an array into a matrix after having multiplied each component by a given factor
  5981. * @param array defines the source array
  5982. * @param offset defines the offset in the source array
  5983. * @param scale defines the scaling factor
  5984. * @param result defines the target matrix
  5985. */
  5986. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5987. for (var index = 0; index < 16; index++) {
  5988. result.m[index] = array[index + offset] * scale;
  5989. }
  5990. result._markAsUpdated();
  5991. };
  5992. /**
  5993. * Stores a list of values (16) inside a given matrix
  5994. * @param initialM11 defines 1st value of 1st row
  5995. * @param initialM12 defines 2nd value of 1st row
  5996. * @param initialM13 defines 3rd value of 1st row
  5997. * @param initialM14 defines 4th value of 1st row
  5998. * @param initialM21 defines 1st value of 2nd row
  5999. * @param initialM22 defines 2nd value of 2nd row
  6000. * @param initialM23 defines 3rd value of 2nd row
  6001. * @param initialM24 defines 4th value of 2nd row
  6002. * @param initialM31 defines 1st value of 3rd row
  6003. * @param initialM32 defines 2nd value of 3rd row
  6004. * @param initialM33 defines 3rd value of 3rd row
  6005. * @param initialM34 defines 4th value of 3rd row
  6006. * @param initialM41 defines 1st value of 4th row
  6007. * @param initialM42 defines 2nd value of 4th row
  6008. * @param initialM43 defines 3rd value of 4th row
  6009. * @param initialM44 defines 4th value of 4th row
  6010. * @param result defines the target matrix
  6011. */
  6012. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  6013. result.m[0] = initialM11;
  6014. result.m[1] = initialM12;
  6015. result.m[2] = initialM13;
  6016. result.m[3] = initialM14;
  6017. result.m[4] = initialM21;
  6018. result.m[5] = initialM22;
  6019. result.m[6] = initialM23;
  6020. result.m[7] = initialM24;
  6021. result.m[8] = initialM31;
  6022. result.m[9] = initialM32;
  6023. result.m[10] = initialM33;
  6024. result.m[11] = initialM34;
  6025. result.m[12] = initialM41;
  6026. result.m[13] = initialM42;
  6027. result.m[14] = initialM43;
  6028. result.m[15] = initialM44;
  6029. result._markAsUpdated();
  6030. };
  6031. Object.defineProperty(Matrix, "IdentityReadOnly", {
  6032. /**
  6033. * Gets an identity matrix that must not be updated
  6034. */
  6035. get: function () {
  6036. return Matrix._identityReadOnly;
  6037. },
  6038. enumerable: true,
  6039. configurable: true
  6040. });
  6041. /**
  6042. * Creates new matrix from a list of values (16)
  6043. * @param initialM11 defines 1st value of 1st row
  6044. * @param initialM12 defines 2nd value of 1st row
  6045. * @param initialM13 defines 3rd value of 1st row
  6046. * @param initialM14 defines 4th value of 1st row
  6047. * @param initialM21 defines 1st value of 2nd row
  6048. * @param initialM22 defines 2nd value of 2nd row
  6049. * @param initialM23 defines 3rd value of 2nd row
  6050. * @param initialM24 defines 4th value of 2nd row
  6051. * @param initialM31 defines 1st value of 3rd row
  6052. * @param initialM32 defines 2nd value of 3rd row
  6053. * @param initialM33 defines 3rd value of 3rd row
  6054. * @param initialM34 defines 4th value of 3rd row
  6055. * @param initialM41 defines 1st value of 4th row
  6056. * @param initialM42 defines 2nd value of 4th row
  6057. * @param initialM43 defines 3rd value of 4th row
  6058. * @param initialM44 defines 4th value of 4th row
  6059. * @returns the new matrix
  6060. */
  6061. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6062. var result = new Matrix();
  6063. result.m[0] = initialM11;
  6064. result.m[1] = initialM12;
  6065. result.m[2] = initialM13;
  6066. result.m[3] = initialM14;
  6067. result.m[4] = initialM21;
  6068. result.m[5] = initialM22;
  6069. result.m[6] = initialM23;
  6070. result.m[7] = initialM24;
  6071. result.m[8] = initialM31;
  6072. result.m[9] = initialM32;
  6073. result.m[10] = initialM33;
  6074. result.m[11] = initialM34;
  6075. result.m[12] = initialM41;
  6076. result.m[13] = initialM42;
  6077. result.m[14] = initialM43;
  6078. result.m[15] = initialM44;
  6079. return result;
  6080. };
  6081. /**
  6082. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6083. * @param scale defines the scale vector3
  6084. * @param rotation defines the rotation quaternion
  6085. * @param translation defines the translation vector3
  6086. * @returns a new matrix
  6087. */
  6088. Matrix.Compose = function (scale, rotation, translation) {
  6089. var result = Matrix.Identity();
  6090. Matrix.ComposeToRef(scale, rotation, translation, result);
  6091. return result;
  6092. };
  6093. /**
  6094. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6095. * @param scale defines the scale vector3
  6096. * @param rotation defines the rotation quaternion
  6097. * @param translation defines the translation vector3
  6098. * @param result defines the target matrix
  6099. */
  6100. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6101. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6102. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6103. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6104. result.setTranslation(translation);
  6105. };
  6106. /**
  6107. * Creates a new identity matrix
  6108. * @returns a new identity matrix
  6109. */
  6110. Matrix.Identity = function () {
  6111. 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);
  6112. };
  6113. /**
  6114. * Creates a new identity matrix and stores the result in a given matrix
  6115. * @param result defines the target matrix
  6116. */
  6117. Matrix.IdentityToRef = function (result) {
  6118. 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);
  6119. };
  6120. /**
  6121. * Creates a new zero matrix
  6122. * @returns a new zero matrix
  6123. */
  6124. Matrix.Zero = function () {
  6125. 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);
  6126. };
  6127. /**
  6128. * Creates a new rotation matrix for "angle" radians around the X axis
  6129. * @param angle defines the angle (in radians) to use
  6130. * @return the new matrix
  6131. */
  6132. Matrix.RotationX = function (angle) {
  6133. var result = new Matrix();
  6134. Matrix.RotationXToRef(angle, result);
  6135. return result;
  6136. };
  6137. /**
  6138. * Creates a new matrix as the invert of a given matrix
  6139. * @param source defines the source matrix
  6140. * @returns the new matrix
  6141. */
  6142. Matrix.Invert = function (source) {
  6143. var result = new Matrix();
  6144. source.invertToRef(result);
  6145. return result;
  6146. };
  6147. /**
  6148. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6149. * @param angle defines the angle (in radians) to use
  6150. * @param result defines the target matrix
  6151. */
  6152. Matrix.RotationXToRef = function (angle, result) {
  6153. var s = Math.sin(angle);
  6154. var c = Math.cos(angle);
  6155. result.m[0] = 1.0;
  6156. result.m[15] = 1.0;
  6157. result.m[5] = c;
  6158. result.m[10] = c;
  6159. result.m[9] = -s;
  6160. result.m[6] = s;
  6161. result.m[1] = 0.0;
  6162. result.m[2] = 0.0;
  6163. result.m[3] = 0.0;
  6164. result.m[4] = 0.0;
  6165. result.m[7] = 0.0;
  6166. result.m[8] = 0.0;
  6167. result.m[11] = 0.0;
  6168. result.m[12] = 0.0;
  6169. result.m[13] = 0.0;
  6170. result.m[14] = 0.0;
  6171. result._markAsUpdated();
  6172. };
  6173. /**
  6174. * Creates a new rotation matrix for "angle" radians around the Y axis
  6175. * @param angle defines the angle (in radians) to use
  6176. * @return the new matrix
  6177. */
  6178. Matrix.RotationY = function (angle) {
  6179. var result = new Matrix();
  6180. Matrix.RotationYToRef(angle, result);
  6181. return result;
  6182. };
  6183. /**
  6184. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6185. * @param angle defines the angle (in radians) to use
  6186. * @param result defines the target matrix
  6187. */
  6188. Matrix.RotationYToRef = function (angle, result) {
  6189. var s = Math.sin(angle);
  6190. var c = Math.cos(angle);
  6191. result.m[5] = 1.0;
  6192. result.m[15] = 1.0;
  6193. result.m[0] = c;
  6194. result.m[2] = -s;
  6195. result.m[8] = s;
  6196. result.m[10] = c;
  6197. result.m[1] = 0.0;
  6198. result.m[3] = 0.0;
  6199. result.m[4] = 0.0;
  6200. result.m[6] = 0.0;
  6201. result.m[7] = 0.0;
  6202. result.m[9] = 0.0;
  6203. result.m[11] = 0.0;
  6204. result.m[12] = 0.0;
  6205. result.m[13] = 0.0;
  6206. result.m[14] = 0.0;
  6207. result._markAsUpdated();
  6208. };
  6209. /**
  6210. * Creates a new rotation matrix for "angle" radians around the Z axis
  6211. * @param angle defines the angle (in radians) to use
  6212. * @return the new matrix
  6213. */
  6214. Matrix.RotationZ = function (angle) {
  6215. var result = new Matrix();
  6216. Matrix.RotationZToRef(angle, result);
  6217. return result;
  6218. };
  6219. /**
  6220. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6221. * @param angle defines the angle (in radians) to use
  6222. * @param result defines the target matrix
  6223. */
  6224. Matrix.RotationZToRef = function (angle, result) {
  6225. var s = Math.sin(angle);
  6226. var c = Math.cos(angle);
  6227. result.m[10] = 1.0;
  6228. result.m[15] = 1.0;
  6229. result.m[0] = c;
  6230. result.m[1] = s;
  6231. result.m[4] = -s;
  6232. result.m[5] = c;
  6233. result.m[2] = 0.0;
  6234. result.m[3] = 0.0;
  6235. result.m[6] = 0.0;
  6236. result.m[7] = 0.0;
  6237. result.m[8] = 0.0;
  6238. result.m[9] = 0.0;
  6239. result.m[11] = 0.0;
  6240. result.m[12] = 0.0;
  6241. result.m[13] = 0.0;
  6242. result.m[14] = 0.0;
  6243. result._markAsUpdated();
  6244. };
  6245. /**
  6246. * Creates a new rotation matrix for "angle" radians around the given axis
  6247. * @param axis defines the axis to use
  6248. * @param angle defines the angle (in radians) to use
  6249. * @return the new matrix
  6250. */
  6251. Matrix.RotationAxis = function (axis, angle) {
  6252. var result = Matrix.Zero();
  6253. Matrix.RotationAxisToRef(axis, angle, result);
  6254. return result;
  6255. };
  6256. /**
  6257. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6258. * @param axis defines the axis to use
  6259. * @param angle defines the angle (in radians) to use
  6260. * @param result defines the target matrix
  6261. */
  6262. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6263. var s = Math.sin(-angle);
  6264. var c = Math.cos(-angle);
  6265. var c1 = 1 - c;
  6266. axis.normalize();
  6267. result.m[0] = (axis.x * axis.x) * c1 + c;
  6268. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6269. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6270. result.m[3] = 0.0;
  6271. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6272. result.m[5] = (axis.y * axis.y) * c1 + c;
  6273. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6274. result.m[7] = 0.0;
  6275. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6276. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6277. result.m[10] = (axis.z * axis.z) * c1 + c;
  6278. result.m[11] = 0.0;
  6279. result.m[15] = 1.0;
  6280. result._markAsUpdated();
  6281. };
  6282. /**
  6283. * Creates a rotation matrix
  6284. * @param yaw defines the yaw angle in radians (Y axis)
  6285. * @param pitch defines the pitch angle in radians (X axis)
  6286. * @param roll defines the roll angle in radians (X axis)
  6287. * @returns the new rotation matrix
  6288. */
  6289. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6290. var result = new Matrix();
  6291. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6292. return result;
  6293. };
  6294. /**
  6295. * Creates a rotation matrix and stores it in a given matrix
  6296. * @param yaw defines the yaw angle in radians (Y axis)
  6297. * @param pitch defines the pitch angle in radians (X axis)
  6298. * @param roll defines the roll angle in radians (X axis)
  6299. * @param result defines the target matrix
  6300. */
  6301. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6302. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6303. this._tempQuaternion.toRotationMatrix(result);
  6304. };
  6305. /**
  6306. * Creates a scaling matrix
  6307. * @param x defines the scale factor on X axis
  6308. * @param y defines the scale factor on Y axis
  6309. * @param z defines the scale factor on Z axis
  6310. * @returns the new matrix
  6311. */
  6312. Matrix.Scaling = function (x, y, z) {
  6313. var result = Matrix.Zero();
  6314. Matrix.ScalingToRef(x, y, z, result);
  6315. return result;
  6316. };
  6317. /**
  6318. * Creates a scaling matrix and stores it in a given matrix
  6319. * @param x defines the scale factor on X axis
  6320. * @param y defines the scale factor on Y axis
  6321. * @param z defines the scale factor on Z axis
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.ScalingToRef = function (x, y, z, result) {
  6325. result.m[0] = x;
  6326. result.m[1] = 0.0;
  6327. result.m[2] = 0.0;
  6328. result.m[3] = 0.0;
  6329. result.m[4] = 0.0;
  6330. result.m[5] = y;
  6331. result.m[6] = 0.0;
  6332. result.m[7] = 0.0;
  6333. result.m[8] = 0.0;
  6334. result.m[9] = 0.0;
  6335. result.m[10] = z;
  6336. result.m[11] = 0.0;
  6337. result.m[12] = 0.0;
  6338. result.m[13] = 0.0;
  6339. result.m[14] = 0.0;
  6340. result.m[15] = 1.0;
  6341. result._markAsUpdated();
  6342. };
  6343. /**
  6344. * Creates a translation matrix
  6345. * @param x defines the translation on X axis
  6346. * @param y defines the translation on Y axis
  6347. * @param z defines the translationon Z axis
  6348. * @returns the new matrix
  6349. */
  6350. Matrix.Translation = function (x, y, z) {
  6351. var result = Matrix.Identity();
  6352. Matrix.TranslationToRef(x, y, z, result);
  6353. return result;
  6354. };
  6355. /**
  6356. * Creates a translation matrix and stores it in a given matrix
  6357. * @param x defines the translation on X axis
  6358. * @param y defines the translation on Y axis
  6359. * @param z defines the translationon Z axis
  6360. * @param result defines the target matrix
  6361. */
  6362. Matrix.TranslationToRef = function (x, y, z, result) {
  6363. 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);
  6364. };
  6365. /**
  6366. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6367. * @param startValue defines the start value
  6368. * @param endValue defines the end value
  6369. * @param gradient defines the gradient factor
  6370. * @returns the new matrix
  6371. */
  6372. Matrix.Lerp = function (startValue, endValue, gradient) {
  6373. var result = Matrix.Zero();
  6374. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6375. return result;
  6376. };
  6377. /**
  6378. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6379. * @param startValue defines the start value
  6380. * @param endValue defines the end value
  6381. * @param gradient defines the gradient factor
  6382. * @param result defines the Matrix object where to store data
  6383. */
  6384. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6385. for (var index = 0; index < 16; index++) {
  6386. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6387. }
  6388. result._markAsUpdated();
  6389. };
  6390. /**
  6391. * Builds a new matrix whose values are computed by:
  6392. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6393. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6394. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6395. * @param startValue defines the first matrix
  6396. * @param endValue defines the second matrix
  6397. * @param gradient defines the gradient between the two matrices
  6398. * @returns the new matrix
  6399. */
  6400. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6401. var result = Matrix.Zero();
  6402. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6403. return result;
  6404. };
  6405. /**
  6406. * Update a matrix to values which are computed by:
  6407. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6408. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6409. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6410. * @param startValue defines the first matrix
  6411. * @param endValue defines the second matrix
  6412. * @param gradient defines the gradient between the two matrices
  6413. * @param result defines the target matrix
  6414. */
  6415. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6416. var startScale = MathTmp.Vector3[0];
  6417. var startRotation = MathTmp.Quaternion[0];
  6418. var startTranslation = MathTmp.Vector3[1];
  6419. startValue.decompose(startScale, startRotation, startTranslation);
  6420. var endScale = MathTmp.Vector3[2];
  6421. var endRotation = MathTmp.Quaternion[1];
  6422. var endTranslation = MathTmp.Vector3[3];
  6423. endValue.decompose(endScale, endRotation, endTranslation);
  6424. var resultScale = MathTmp.Vector3[4];
  6425. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6426. var resultRotation = MathTmp.Quaternion[2];
  6427. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6428. var resultTranslation = MathTmp.Vector3[5];
  6429. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6430. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6431. };
  6432. /**
  6433. * 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"
  6434. * This function works in left handed mode
  6435. * @param eye defines the final position of the entity
  6436. * @param target defines where the entity should look at
  6437. * @param up defines the up vector for the entity
  6438. * @returns the new matrix
  6439. */
  6440. Matrix.LookAtLH = function (eye, target, up) {
  6441. var result = Matrix.Zero();
  6442. Matrix.LookAtLHToRef(eye, target, up, result);
  6443. return result;
  6444. };
  6445. /**
  6446. * 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".
  6447. * This function works in left handed mode
  6448. * @param eye defines the final position of the entity
  6449. * @param target defines where the entity should look at
  6450. * @param up defines the up vector for the entity
  6451. * @param result defines the target matrix
  6452. */
  6453. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6454. // Z axis
  6455. target.subtractToRef(eye, this._zAxis);
  6456. this._zAxis.normalize();
  6457. // X axis
  6458. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6459. if (this._xAxis.lengthSquared() === 0) {
  6460. this._xAxis.x = 1.0;
  6461. }
  6462. else {
  6463. this._xAxis.normalize();
  6464. }
  6465. // Y axis
  6466. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6467. this._yAxis.normalize();
  6468. // Eye angles
  6469. var ex = -Vector3.Dot(this._xAxis, eye);
  6470. var ey = -Vector3.Dot(this._yAxis, eye);
  6471. var ez = -Vector3.Dot(this._zAxis, eye);
  6472. 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);
  6473. };
  6474. /**
  6475. * 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"
  6476. * This function works in right handed mode
  6477. * @param eye defines the final position of the entity
  6478. * @param target defines where the entity should look at
  6479. * @param up defines the up vector for the entity
  6480. * @returns the new matrix
  6481. */
  6482. Matrix.LookAtRH = function (eye, target, up) {
  6483. var result = Matrix.Zero();
  6484. Matrix.LookAtRHToRef(eye, target, up, result);
  6485. return result;
  6486. };
  6487. /**
  6488. * 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".
  6489. * This function works in right handed mode
  6490. * @param eye defines the final position of the entity
  6491. * @param target defines where the entity should look at
  6492. * @param up defines the up vector for the entity
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6496. // Z axis
  6497. eye.subtractToRef(target, this._zAxis);
  6498. this._zAxis.normalize();
  6499. // X axis
  6500. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6501. if (this._xAxis.lengthSquared() === 0) {
  6502. this._xAxis.x = 1.0;
  6503. }
  6504. else {
  6505. this._xAxis.normalize();
  6506. }
  6507. // Y axis
  6508. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6509. this._yAxis.normalize();
  6510. // Eye angles
  6511. var ex = -Vector3.Dot(this._xAxis, eye);
  6512. var ey = -Vector3.Dot(this._yAxis, eye);
  6513. var ez = -Vector3.Dot(this._zAxis, eye);
  6514. 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);
  6515. };
  6516. /**
  6517. * Create a left-handed orthographic projection matrix
  6518. * @param width defines the viewport width
  6519. * @param height defines the viewport height
  6520. * @param znear defines the near clip plane
  6521. * @param zfar defines the far clip plane
  6522. * @returns a new matrix as a left-handed orthographic projection matrix
  6523. */
  6524. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6525. var matrix = Matrix.Zero();
  6526. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6527. return matrix;
  6528. };
  6529. /**
  6530. * Store a left-handed orthographic projection to a given matrix
  6531. * @param width defines the viewport width
  6532. * @param height defines the viewport height
  6533. * @param znear defines the near clip plane
  6534. * @param zfar defines the far clip plane
  6535. * @param result defines the target matrix
  6536. */
  6537. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6538. var n = znear;
  6539. var f = zfar;
  6540. var a = 2.0 / width;
  6541. var b = 2.0 / height;
  6542. var c = 2.0 / (f - n);
  6543. var d = -(f + n) / (f - n);
  6544. 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);
  6545. };
  6546. /**
  6547. * Create a left-handed orthographic projection matrix
  6548. * @param left defines the viewport left coordinate
  6549. * @param right defines the viewport right coordinate
  6550. * @param bottom defines the viewport bottom coordinate
  6551. * @param top defines the viewport top coordinate
  6552. * @param znear defines the near clip plane
  6553. * @param zfar defines the far clip plane
  6554. * @returns a new matrix as a left-handed orthographic projection matrix
  6555. */
  6556. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6557. var matrix = Matrix.Zero();
  6558. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6559. return matrix;
  6560. };
  6561. /**
  6562. * Stores a left-handed orthographic projection into a given matrix
  6563. * @param left defines the viewport left coordinate
  6564. * @param right defines the viewport right coordinate
  6565. * @param bottom defines the viewport bottom coordinate
  6566. * @param top defines the viewport top coordinate
  6567. * @param znear defines the near clip plane
  6568. * @param zfar defines the far clip plane
  6569. * @param result defines the target matrix
  6570. */
  6571. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6572. var n = znear;
  6573. var f = zfar;
  6574. var a = 2.0 / (right - left);
  6575. var b = 2.0 / (top - bottom);
  6576. var c = 2.0 / (f - n);
  6577. var d = -(f + n) / (f - n);
  6578. var i0 = (left + right) / (left - right);
  6579. var i1 = (top + bottom) / (bottom - top);
  6580. 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);
  6581. };
  6582. /**
  6583. * Creates a right-handed orthographic projection matrix
  6584. * @param left defines the viewport left coordinate
  6585. * @param right defines the viewport right coordinate
  6586. * @param bottom defines the viewport bottom coordinate
  6587. * @param top defines the viewport top coordinate
  6588. * @param znear defines the near clip plane
  6589. * @param zfar defines the far clip plane
  6590. * @returns a new matrix as a right-handed orthographic projection matrix
  6591. */
  6592. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6593. var matrix = Matrix.Zero();
  6594. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6595. return matrix;
  6596. };
  6597. /**
  6598. * Stores a right-handed orthographic projection into a given matrix
  6599. * @param left defines the viewport left coordinate
  6600. * @param right defines the viewport right coordinate
  6601. * @param bottom defines the viewport bottom coordinate
  6602. * @param top defines the viewport top coordinate
  6603. * @param znear defines the near clip plane
  6604. * @param zfar defines the far clip plane
  6605. * @param result defines the target matrix
  6606. */
  6607. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6608. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6609. result.m[10] *= -1.0;
  6610. };
  6611. /**
  6612. * Creates a left-handed perspective projection matrix
  6613. * @param width defines the viewport width
  6614. * @param height defines the viewport height
  6615. * @param znear defines the near clip plane
  6616. * @param zfar defines the far clip plane
  6617. * @returns a new matrix as a left-handed perspective projection matrix
  6618. */
  6619. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6620. var matrix = Matrix.Zero();
  6621. var n = znear;
  6622. var f = zfar;
  6623. var a = 2.0 * n / width;
  6624. var b = 2.0 * n / height;
  6625. var c = (f + n) / (f - n);
  6626. var d = -2.0 * f * n / (f - n);
  6627. 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);
  6628. return matrix;
  6629. };
  6630. /**
  6631. * Creates a left-handed perspective projection matrix
  6632. * @param fov defines the horizontal field of view
  6633. * @param aspect defines the aspect ratio
  6634. * @param znear defines the near clip plane
  6635. * @param zfar defines the far clip plane
  6636. * @returns a new matrix as a left-handed perspective projection matrix
  6637. */
  6638. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6639. var matrix = Matrix.Zero();
  6640. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6641. return matrix;
  6642. };
  6643. /**
  6644. * Stores a left-handed perspective projection into a given matrix
  6645. * @param fov defines the horizontal field of view
  6646. * @param aspect defines the aspect ratio
  6647. * @param znear defines the near clip plane
  6648. * @param zfar defines the far clip plane
  6649. * @param result defines the target matrix
  6650. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6651. */
  6652. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6653. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6654. var n = znear;
  6655. var f = zfar;
  6656. var t = 1.0 / (Math.tan(fov * 0.5));
  6657. var a = isVerticalFovFixed ? (t / aspect) : t;
  6658. var b = isVerticalFovFixed ? t : (t * aspect);
  6659. var c = (f + n) / (f - n);
  6660. var d = -2.0 * f * n / (f - n);
  6661. 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);
  6662. };
  6663. /**
  6664. * Creates a right-handed perspective projection matrix
  6665. * @param fov defines the horizontal field of view
  6666. * @param aspect defines the aspect ratio
  6667. * @param znear defines the near clip plane
  6668. * @param zfar defines the far clip plane
  6669. * @returns a new matrix as a right-handed perspective projection matrix
  6670. */
  6671. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6672. var matrix = Matrix.Zero();
  6673. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6674. return matrix;
  6675. };
  6676. /**
  6677. * Stores a right-handed perspective projection into a given matrix
  6678. * @param fov defines the horizontal field of view
  6679. * @param aspect defines the aspect ratio
  6680. * @param znear defines the near clip plane
  6681. * @param zfar defines the far clip plane
  6682. * @param result defines the target matrix
  6683. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6684. */
  6685. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6686. //alternatively this could be expressed as:
  6687. // m = PerspectiveFovLHToRef
  6688. // m[10] *= -1.0;
  6689. // m[11] *= -1.0;
  6690. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6691. var n = znear;
  6692. var f = zfar;
  6693. var t = 1.0 / (Math.tan(fov * 0.5));
  6694. var a = isVerticalFovFixed ? (t / aspect) : t;
  6695. var b = isVerticalFovFixed ? t : (t * aspect);
  6696. var c = -(f + n) / (f - n);
  6697. var d = -2 * f * n / (f - n);
  6698. 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);
  6699. };
  6700. /**
  6701. * Stores a perspective projection for WebVR info a given matrix
  6702. * @param fov defines the field of view
  6703. * @param znear defines the near clip plane
  6704. * @param zfar defines the far clip plane
  6705. * @param result defines the target matrix
  6706. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6707. */
  6708. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6709. if (rightHanded === void 0) { rightHanded = false; }
  6710. var rightHandedFactor = rightHanded ? -1 : 1;
  6711. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6712. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6713. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6714. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6715. var xScale = 2.0 / (leftTan + rightTan);
  6716. var yScale = 2.0 / (upTan + downTan);
  6717. result.m[0] = xScale;
  6718. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6719. result.m[5] = yScale;
  6720. result.m[6] = result.m[7] = 0.0;
  6721. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6722. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6723. result.m[10] = -zfar / (znear - zfar);
  6724. result.m[11] = 1.0 * rightHandedFactor;
  6725. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6726. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6727. result._markAsUpdated();
  6728. };
  6729. /**
  6730. * Computes a complete transformation matrix
  6731. * @param viewport defines the viewport to use
  6732. * @param world defines the world matrix
  6733. * @param view defines the view matrix
  6734. * @param projection defines the projection matrix
  6735. * @param zmin defines the near clip plane
  6736. * @param zmax defines the far clip plane
  6737. * @returns the transformation matrix
  6738. */
  6739. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6740. var cw = viewport.width;
  6741. var ch = viewport.height;
  6742. var cx = viewport.x;
  6743. var cy = viewport.y;
  6744. 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);
  6745. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6746. };
  6747. /**
  6748. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6749. * @param matrix defines the matrix to use
  6750. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6751. */
  6752. Matrix.GetAsMatrix2x2 = function (matrix) {
  6753. return new Float32Array([
  6754. matrix.m[0], matrix.m[1],
  6755. matrix.m[4], matrix.m[5]
  6756. ]);
  6757. };
  6758. /**
  6759. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6760. * @param matrix defines the matrix to use
  6761. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6762. */
  6763. Matrix.GetAsMatrix3x3 = function (matrix) {
  6764. return new Float32Array([
  6765. matrix.m[0], matrix.m[1], matrix.m[2],
  6766. matrix.m[4], matrix.m[5], matrix.m[6],
  6767. matrix.m[8], matrix.m[9], matrix.m[10]
  6768. ]);
  6769. };
  6770. /**
  6771. * Compute the transpose of a given matrix
  6772. * @param matrix defines the matrix to transpose
  6773. * @returns the new matrix
  6774. */
  6775. Matrix.Transpose = function (matrix) {
  6776. var result = new Matrix();
  6777. Matrix.TransposeToRef(matrix, result);
  6778. return result;
  6779. };
  6780. /**
  6781. * Compute the transpose of a matrix and store it in a target matrix
  6782. * @param matrix defines the matrix to transpose
  6783. * @param result defines the target matrix
  6784. */
  6785. Matrix.TransposeToRef = function (matrix, result) {
  6786. result.m[0] = matrix.m[0];
  6787. result.m[1] = matrix.m[4];
  6788. result.m[2] = matrix.m[8];
  6789. result.m[3] = matrix.m[12];
  6790. result.m[4] = matrix.m[1];
  6791. result.m[5] = matrix.m[5];
  6792. result.m[6] = matrix.m[9];
  6793. result.m[7] = matrix.m[13];
  6794. result.m[8] = matrix.m[2];
  6795. result.m[9] = matrix.m[6];
  6796. result.m[10] = matrix.m[10];
  6797. result.m[11] = matrix.m[14];
  6798. result.m[12] = matrix.m[3];
  6799. result.m[13] = matrix.m[7];
  6800. result.m[14] = matrix.m[11];
  6801. result.m[15] = matrix.m[15];
  6802. };
  6803. /**
  6804. * Computes a reflection matrix from a plane
  6805. * @param plane defines the reflection plane
  6806. * @returns a new matrix
  6807. */
  6808. Matrix.Reflection = function (plane) {
  6809. var matrix = new Matrix();
  6810. Matrix.ReflectionToRef(plane, matrix);
  6811. return matrix;
  6812. };
  6813. /**
  6814. * Computes a reflection matrix from a plane
  6815. * @param plane defines the reflection plane
  6816. * @param result defines the target matrix
  6817. */
  6818. Matrix.ReflectionToRef = function (plane, result) {
  6819. plane.normalize();
  6820. var x = plane.normal.x;
  6821. var y = plane.normal.y;
  6822. var z = plane.normal.z;
  6823. var temp = -2 * x;
  6824. var temp2 = -2 * y;
  6825. var temp3 = -2 * z;
  6826. result.m[0] = (temp * x) + 1;
  6827. result.m[1] = temp2 * x;
  6828. result.m[2] = temp3 * x;
  6829. result.m[3] = 0.0;
  6830. result.m[4] = temp * y;
  6831. result.m[5] = (temp2 * y) + 1;
  6832. result.m[6] = temp3 * y;
  6833. result.m[7] = 0.0;
  6834. result.m[8] = temp * z;
  6835. result.m[9] = temp2 * z;
  6836. result.m[10] = (temp3 * z) + 1;
  6837. result.m[11] = 0.0;
  6838. result.m[12] = temp * plane.d;
  6839. result.m[13] = temp2 * plane.d;
  6840. result.m[14] = temp3 * plane.d;
  6841. result.m[15] = 1.0;
  6842. result._markAsUpdated();
  6843. };
  6844. /**
  6845. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6846. * @param xaxis defines the value of the 1st axis
  6847. * @param yaxis defines the value of the 2nd axis
  6848. * @param zaxis defines the value of the 3rd axis
  6849. * @param result defines the target matrix
  6850. */
  6851. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6852. result.m[0] = xaxis.x;
  6853. result.m[1] = xaxis.y;
  6854. result.m[2] = xaxis.z;
  6855. result.m[3] = 0.0;
  6856. result.m[4] = yaxis.x;
  6857. result.m[5] = yaxis.y;
  6858. result.m[6] = yaxis.z;
  6859. result.m[7] = 0.0;
  6860. result.m[8] = zaxis.x;
  6861. result.m[9] = zaxis.y;
  6862. result.m[10] = zaxis.z;
  6863. result.m[11] = 0.0;
  6864. result.m[12] = 0.0;
  6865. result.m[13] = 0.0;
  6866. result.m[14] = 0.0;
  6867. result.m[15] = 1.0;
  6868. result._markAsUpdated();
  6869. };
  6870. /**
  6871. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6872. * @param quat defines the quaternion to use
  6873. * @param result defines the target matrix
  6874. */
  6875. Matrix.FromQuaternionToRef = function (quat, result) {
  6876. var xx = quat.x * quat.x;
  6877. var yy = quat.y * quat.y;
  6878. var zz = quat.z * quat.z;
  6879. var xy = quat.x * quat.y;
  6880. var zw = quat.z * quat.w;
  6881. var zx = quat.z * quat.x;
  6882. var yw = quat.y * quat.w;
  6883. var yz = quat.y * quat.z;
  6884. var xw = quat.x * quat.w;
  6885. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6886. result.m[1] = 2.0 * (xy + zw);
  6887. result.m[2] = 2.0 * (zx - yw);
  6888. result.m[3] = 0.0;
  6889. result.m[4] = 2.0 * (xy - zw);
  6890. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6891. result.m[6] = 2.0 * (yz + xw);
  6892. result.m[7] = 0.0;
  6893. result.m[8] = 2.0 * (zx + yw);
  6894. result.m[9] = 2.0 * (yz - xw);
  6895. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6896. result.m[11] = 0.0;
  6897. result.m[12] = 0.0;
  6898. result.m[13] = 0.0;
  6899. result.m[14] = 0.0;
  6900. result.m[15] = 1.0;
  6901. result._markAsUpdated();
  6902. };
  6903. Matrix._tempQuaternion = new Quaternion();
  6904. Matrix._xAxis = Vector3.Zero();
  6905. Matrix._yAxis = Vector3.Zero();
  6906. Matrix._zAxis = Vector3.Zero();
  6907. Matrix._updateFlagSeed = 0;
  6908. Matrix._identityReadOnly = Matrix.Identity();
  6909. return Matrix;
  6910. }());
  6911. BABYLON.Matrix = Matrix;
  6912. /**
  6913. * Represens a plane by the equation ax + by + cz + d = 0
  6914. */
  6915. var Plane = /** @class */ (function () {
  6916. /**
  6917. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6918. * @param a a component of the plane
  6919. * @param b b component of the plane
  6920. * @param c c component of the plane
  6921. * @param d d component of the plane
  6922. */
  6923. function Plane(a, b, c, d) {
  6924. this.normal = new Vector3(a, b, c);
  6925. this.d = d;
  6926. }
  6927. /**
  6928. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6929. */
  6930. Plane.prototype.asArray = function () {
  6931. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6932. };
  6933. // Methods
  6934. /**
  6935. * @returns a new plane copied from the current Plane.
  6936. */
  6937. Plane.prototype.clone = function () {
  6938. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6939. };
  6940. /**
  6941. * @returns the string "Plane".
  6942. */
  6943. Plane.prototype.getClassName = function () {
  6944. return "Plane";
  6945. };
  6946. /**
  6947. * @returns the Plane hash code.
  6948. */
  6949. Plane.prototype.getHashCode = function () {
  6950. var hash = this.normal.getHashCode();
  6951. hash = (hash * 397) ^ (this.d || 0);
  6952. return hash;
  6953. };
  6954. /**
  6955. * Normalize the current Plane in place.
  6956. * @returns the updated Plane.
  6957. */
  6958. Plane.prototype.normalize = function () {
  6959. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6960. var magnitude = 0.0;
  6961. if (norm !== 0) {
  6962. magnitude = 1.0 / norm;
  6963. }
  6964. this.normal.x *= magnitude;
  6965. this.normal.y *= magnitude;
  6966. this.normal.z *= magnitude;
  6967. this.d *= magnitude;
  6968. return this;
  6969. };
  6970. /**
  6971. * Applies a transformation the plane and returns the result
  6972. * @param transformation the transformation matrix to be applied to the plane
  6973. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6974. */
  6975. Plane.prototype.transform = function (transformation) {
  6976. var transposedMatrix = Matrix.Transpose(transformation);
  6977. var x = this.normal.x;
  6978. var y = this.normal.y;
  6979. var z = this.normal.z;
  6980. var d = this.d;
  6981. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6982. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6983. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6984. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6985. return new Plane(normalX, normalY, normalZ, finalD);
  6986. };
  6987. /**
  6988. * Calcualtte the dot product between the point and the plane normal
  6989. * @param point point to calculate the dot product with
  6990. * @returns the dot product (float) of the point coordinates and the plane normal.
  6991. */
  6992. Plane.prototype.dotCoordinate = function (point) {
  6993. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6994. };
  6995. /**
  6996. * Updates the current Plane from the plane defined by the three given points.
  6997. * @param point1 one of the points used to contruct the plane
  6998. * @param point2 one of the points used to contruct the plane
  6999. * @param point3 one of the points used to contruct the plane
  7000. * @returns the updated Plane.
  7001. */
  7002. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  7003. var x1 = point2.x - point1.x;
  7004. var y1 = point2.y - point1.y;
  7005. var z1 = point2.z - point1.z;
  7006. var x2 = point3.x - point1.x;
  7007. var y2 = point3.y - point1.y;
  7008. var z2 = point3.z - point1.z;
  7009. var yz = (y1 * z2) - (z1 * y2);
  7010. var xz = (z1 * x2) - (x1 * z2);
  7011. var xy = (x1 * y2) - (y1 * x2);
  7012. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  7013. var invPyth;
  7014. if (pyth !== 0) {
  7015. invPyth = 1.0 / pyth;
  7016. }
  7017. else {
  7018. invPyth = 0.0;
  7019. }
  7020. this.normal.x = yz * invPyth;
  7021. this.normal.y = xz * invPyth;
  7022. this.normal.z = xy * invPyth;
  7023. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  7024. return this;
  7025. };
  7026. /**
  7027. * Checks if the plane is facing a given direction
  7028. * @param direction the direction to check if the plane is facing
  7029. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  7030. * @returns True is the vector "direction" is the same side than the plane normal.
  7031. */
  7032. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  7033. var dot = Vector3.Dot(this.normal, direction);
  7034. return (dot <= epsilon);
  7035. };
  7036. /**
  7037. * Calculates the distance to a point
  7038. * @param point point to calculate distance to
  7039. * @returns the signed distance (float) from the given point to the Plane.
  7040. */
  7041. Plane.prototype.signedDistanceTo = function (point) {
  7042. return Vector3.Dot(point, this.normal) + this.d;
  7043. };
  7044. // Statics
  7045. /**
  7046. * Creates a plane from an array
  7047. * @param array the array to create a plane from
  7048. * @returns a new Plane from the given array.
  7049. */
  7050. Plane.FromArray = function (array) {
  7051. return new Plane(array[0], array[1], array[2], array[3]);
  7052. };
  7053. /**
  7054. * Creates a plane from three points
  7055. * @param point1 point used to create the plane
  7056. * @param point2 point used to create the plane
  7057. * @param point3 point used to create the plane
  7058. * @returns a new Plane defined by the three given points.
  7059. */
  7060. Plane.FromPoints = function (point1, point2, point3) {
  7061. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7062. result.copyFromPoints(point1, point2, point3);
  7063. return result;
  7064. };
  7065. /**
  7066. * Creates a plane from an origin point and a normal
  7067. * @param origin origin of the plane to be constructed
  7068. * @param normal normal of the plane to be constructed
  7069. * @returns a new Plane the normal vector to this plane at the given origin point.
  7070. * Note : the vector "normal" is updated because normalized.
  7071. */
  7072. Plane.FromPositionAndNormal = function (origin, normal) {
  7073. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7074. normal.normalize();
  7075. result.normal = normal;
  7076. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7077. return result;
  7078. };
  7079. /**
  7080. * Calculates the distance from a plane and a point
  7081. * @param origin origin of the plane to be constructed
  7082. * @param normal normal of the plane to be constructed
  7083. * @param point point to calculate distance to
  7084. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7085. */
  7086. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7087. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7088. return Vector3.Dot(point, normal) + d;
  7089. };
  7090. return Plane;
  7091. }());
  7092. BABYLON.Plane = Plane;
  7093. /**
  7094. * Class used to represent a viewport on screen
  7095. */
  7096. var Viewport = /** @class */ (function () {
  7097. /**
  7098. * Creates a Viewport object located at (x, y) and sized (width, height)
  7099. * @param x defines viewport left coordinate
  7100. * @param y defines viewport top coordinate
  7101. * @param width defines the viewport width
  7102. * @param height defines the viewport height
  7103. */
  7104. function Viewport(
  7105. /** viewport left coordinate */
  7106. x,
  7107. /** viewport top coordinate */
  7108. y,
  7109. /**viewport width */
  7110. width,
  7111. /** viewport height */
  7112. height) {
  7113. this.x = x;
  7114. this.y = y;
  7115. this.width = width;
  7116. this.height = height;
  7117. }
  7118. /**
  7119. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7120. * @param renderWidthOrEngine defines either an engine or the rendering width
  7121. * @param renderHeight defines the rendering height
  7122. * @returns a new Viewport
  7123. */
  7124. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7125. if (renderWidthOrEngine.getRenderWidth) {
  7126. var engine = renderWidthOrEngine;
  7127. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7128. }
  7129. var renderWidth = renderWidthOrEngine;
  7130. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7131. };
  7132. /**
  7133. * Returns a new Viewport copied from the current one
  7134. * @returns a new Viewport
  7135. */
  7136. Viewport.prototype.clone = function () {
  7137. return new Viewport(this.x, this.y, this.width, this.height);
  7138. };
  7139. return Viewport;
  7140. }());
  7141. BABYLON.Viewport = Viewport;
  7142. /**
  7143. * Reprasents a camera frustum
  7144. */
  7145. var Frustum = /** @class */ (function () {
  7146. function Frustum() {
  7147. }
  7148. /**
  7149. * Gets the planes representing the frustum
  7150. * @param transform matrix to be applied to the returned planes
  7151. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7152. */
  7153. Frustum.GetPlanes = function (transform) {
  7154. var frustumPlanes = [];
  7155. for (var index = 0; index < 6; index++) {
  7156. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7157. }
  7158. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7159. return frustumPlanes;
  7160. };
  7161. /**
  7162. * Gets the near frustum plane transformed by the transform matrix
  7163. * @param transform transformation matrix to be applied to the resulting frustum plane
  7164. * @param frustumPlane the resuling frustum plane
  7165. */
  7166. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7167. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7168. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7169. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7170. frustumPlane.d = transform.m[15] + transform.m[14];
  7171. frustumPlane.normalize();
  7172. };
  7173. /**
  7174. * Gets the far frustum plane transformed by the transform matrix
  7175. * @param transform transformation matrix to be applied to the resulting frustum plane
  7176. * @param frustumPlane the resuling frustum plane
  7177. */
  7178. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7179. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7180. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7181. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7182. frustumPlane.d = transform.m[15] - transform.m[14];
  7183. frustumPlane.normalize();
  7184. };
  7185. /**
  7186. * Gets the left frustum plane transformed by the transform matrix
  7187. * @param transform transformation matrix to be applied to the resulting frustum plane
  7188. * @param frustumPlane the resuling frustum plane
  7189. */
  7190. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7191. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7192. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7193. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7194. frustumPlane.d = transform.m[15] + transform.m[12];
  7195. frustumPlane.normalize();
  7196. };
  7197. /**
  7198. * Gets the right frustum plane transformed by the transform matrix
  7199. * @param transform transformation matrix to be applied to the resulting frustum plane
  7200. * @param frustumPlane the resuling frustum plane
  7201. */
  7202. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7203. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7204. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7205. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7206. frustumPlane.d = transform.m[15] - transform.m[12];
  7207. frustumPlane.normalize();
  7208. };
  7209. /**
  7210. * Gets the top frustum plane transformed by the transform matrix
  7211. * @param transform transformation matrix to be applied to the resulting frustum plane
  7212. * @param frustumPlane the resuling frustum plane
  7213. */
  7214. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7215. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7216. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7217. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7218. frustumPlane.d = transform.m[15] - transform.m[13];
  7219. frustumPlane.normalize();
  7220. };
  7221. /**
  7222. * Gets the bottom frustum plane transformed by the transform matrix
  7223. * @param transform transformation matrix to be applied to the resulting frustum plane
  7224. * @param frustumPlane the resuling frustum plane
  7225. */
  7226. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7227. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7228. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7229. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7230. frustumPlane.d = transform.m[15] + transform.m[13];
  7231. frustumPlane.normalize();
  7232. };
  7233. /**
  7234. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7235. * @param transform transformation matrix to be applied to the resulting frustum planes
  7236. * @param frustumPlanes the resuling frustum planes
  7237. */
  7238. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7239. // Near
  7240. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7241. // Far
  7242. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7243. // Left
  7244. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7245. // Right
  7246. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7247. // Top
  7248. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7249. // Bottom
  7250. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7251. };
  7252. return Frustum;
  7253. }());
  7254. BABYLON.Frustum = Frustum;
  7255. /** Defines supported spaces */
  7256. var Space;
  7257. (function (Space) {
  7258. /** Local (object) space */
  7259. Space[Space["LOCAL"] = 0] = "LOCAL";
  7260. /** World space */
  7261. Space[Space["WORLD"] = 1] = "WORLD";
  7262. /** Bone space */
  7263. Space[Space["BONE"] = 2] = "BONE";
  7264. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7265. /** Defines the 3 main axes */
  7266. var Axis = /** @class */ (function () {
  7267. function Axis() {
  7268. }
  7269. /** X axis */
  7270. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7271. /** Y axis */
  7272. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7273. /** Z axis */
  7274. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7275. return Axis;
  7276. }());
  7277. BABYLON.Axis = Axis;
  7278. /** Class used to represent a Bezier curve */
  7279. var BezierCurve = /** @class */ (function () {
  7280. function BezierCurve() {
  7281. }
  7282. /**
  7283. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7284. * @param t defines the time
  7285. * @param x1 defines the left coordinate on X axis
  7286. * @param y1 defines the left coordinate on Y axis
  7287. * @param x2 defines the right coordinate on X axis
  7288. * @param y2 defines the right coordinate on Y axis
  7289. * @returns the interpolated value
  7290. */
  7291. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7292. // Extract X (which is equal to time here)
  7293. var f0 = 1 - 3 * x2 + 3 * x1;
  7294. var f1 = 3 * x2 - 6 * x1;
  7295. var f2 = 3 * x1;
  7296. var refinedT = t;
  7297. for (var i = 0; i < 5; i++) {
  7298. var refinedT2 = refinedT * refinedT;
  7299. var refinedT3 = refinedT2 * refinedT;
  7300. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7301. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7302. refinedT -= (x - t) * slope;
  7303. refinedT = Math.min(1, Math.max(0, refinedT));
  7304. }
  7305. // Resolve cubic bezier for the given x
  7306. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7307. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7308. Math.pow(refinedT, 3);
  7309. };
  7310. return BezierCurve;
  7311. }());
  7312. BABYLON.BezierCurve = BezierCurve;
  7313. /**
  7314. * Defines potential orientation for back face culling
  7315. */
  7316. var Orientation;
  7317. (function (Orientation) {
  7318. /**
  7319. * Clockwise
  7320. */
  7321. Orientation[Orientation["CW"] = 0] = "CW";
  7322. /** Counter clockwise */
  7323. Orientation[Orientation["CCW"] = 1] = "CCW";
  7324. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7325. /**
  7326. * Defines angle representation
  7327. */
  7328. var Angle = /** @class */ (function () {
  7329. /**
  7330. * Creates an Angle object of "radians" radians (float).
  7331. */
  7332. function Angle(radians) {
  7333. this._radians = radians;
  7334. if (this._radians < 0.0) {
  7335. this._radians += (2.0 * Math.PI);
  7336. }
  7337. }
  7338. /**
  7339. * Get value in degrees
  7340. * @returns the Angle value in degrees (float)
  7341. */
  7342. Angle.prototype.degrees = function () {
  7343. return this._radians * 180.0 / Math.PI;
  7344. };
  7345. /**
  7346. * Get value in radians
  7347. * @returns the Angle value in radians (float)
  7348. */
  7349. Angle.prototype.radians = function () {
  7350. return this._radians;
  7351. };
  7352. /**
  7353. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7354. * @param a defines first vector
  7355. * @param b defines second vector
  7356. * @returns a new Angle
  7357. */
  7358. Angle.BetweenTwoPoints = function (a, b) {
  7359. var delta = b.subtract(a);
  7360. var theta = Math.atan2(delta.y, delta.x);
  7361. return new Angle(theta);
  7362. };
  7363. /**
  7364. * Gets a new Angle object from the given float in radians
  7365. * @param radians defines the angle value in radians
  7366. * @returns a new Angle
  7367. */
  7368. Angle.FromRadians = function (radians) {
  7369. return new Angle(radians);
  7370. };
  7371. /**
  7372. * Gets a new Angle object from the given float in degrees
  7373. * @param degrees defines the angle value in degrees
  7374. * @returns a new Angle
  7375. */
  7376. Angle.FromDegrees = function (degrees) {
  7377. return new Angle(degrees * Math.PI / 180.0);
  7378. };
  7379. return Angle;
  7380. }());
  7381. BABYLON.Angle = Angle;
  7382. /**
  7383. * This represents an arc in a 2d space.
  7384. */
  7385. var Arc2 = /** @class */ (function () {
  7386. /**
  7387. * Creates an Arc object from the three given points : start, middle and end.
  7388. * @param startPoint Defines the start point of the arc
  7389. * @param midPoint Defines the midlle point of the arc
  7390. * @param endPoint Defines the end point of the arc
  7391. */
  7392. function Arc2(
  7393. /** Defines the start point of the arc */
  7394. startPoint,
  7395. /** Defines the mid point of the arc */
  7396. midPoint,
  7397. /** Defines the end point of the arc */
  7398. endPoint) {
  7399. this.startPoint = startPoint;
  7400. this.midPoint = midPoint;
  7401. this.endPoint = endPoint;
  7402. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7403. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7404. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7405. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7406. 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);
  7407. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7408. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7409. var a1 = this.startAngle.degrees();
  7410. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7411. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7412. // angles correction
  7413. if (a2 - a1 > +180.0) {
  7414. a2 -= 360.0;
  7415. }
  7416. if (a2 - a1 < -180.0) {
  7417. a2 += 360.0;
  7418. }
  7419. if (a3 - a2 > +180.0) {
  7420. a3 -= 360.0;
  7421. }
  7422. if (a3 - a2 < -180.0) {
  7423. a3 += 360.0;
  7424. }
  7425. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7426. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7427. }
  7428. return Arc2;
  7429. }());
  7430. BABYLON.Arc2 = Arc2;
  7431. /**
  7432. * Represents a 2D path made up of multiple 2D points
  7433. */
  7434. var Path2 = /** @class */ (function () {
  7435. /**
  7436. * Creates a Path2 object from the starting 2D coordinates x and y.
  7437. * @param x the starting points x value
  7438. * @param y the starting points y value
  7439. */
  7440. function Path2(x, y) {
  7441. this._points = new Array();
  7442. this._length = 0.0;
  7443. /**
  7444. * If the path start and end point are the same
  7445. */
  7446. this.closed = false;
  7447. this._points.push(new Vector2(x, y));
  7448. }
  7449. /**
  7450. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7451. * @param x the added points x value
  7452. * @param y the added points y value
  7453. * @returns the updated Path2.
  7454. */
  7455. Path2.prototype.addLineTo = function (x, y) {
  7456. if (this.closed) {
  7457. return this;
  7458. }
  7459. var newPoint = new Vector2(x, y);
  7460. var previousPoint = this._points[this._points.length - 1];
  7461. this._points.push(newPoint);
  7462. this._length += newPoint.subtract(previousPoint).length();
  7463. return this;
  7464. };
  7465. /**
  7466. * 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.
  7467. * @param midX middle point x value
  7468. * @param midY middle point y value
  7469. * @param endX end point x value
  7470. * @param endY end point y value
  7471. * @param numberOfSegments (default: 36)
  7472. * @returns the updated Path2.
  7473. */
  7474. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7475. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7476. if (this.closed) {
  7477. return this;
  7478. }
  7479. var startPoint = this._points[this._points.length - 1];
  7480. var midPoint = new Vector2(midX, midY);
  7481. var endPoint = new Vector2(endX, endY);
  7482. var arc = new Arc2(startPoint, midPoint, endPoint);
  7483. var increment = arc.angle.radians() / numberOfSegments;
  7484. if (arc.orientation === Orientation.CW) {
  7485. increment *= -1;
  7486. }
  7487. var currentAngle = arc.startAngle.radians() + increment;
  7488. for (var i = 0; i < numberOfSegments; i++) {
  7489. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7490. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7491. this.addLineTo(x, y);
  7492. currentAngle += increment;
  7493. }
  7494. return this;
  7495. };
  7496. /**
  7497. * Closes the Path2.
  7498. * @returns the Path2.
  7499. */
  7500. Path2.prototype.close = function () {
  7501. this.closed = true;
  7502. return this;
  7503. };
  7504. /**
  7505. * Gets the sum of the distance between each sequential point in the path
  7506. * @returns the Path2 total length (float).
  7507. */
  7508. Path2.prototype.length = function () {
  7509. var result = this._length;
  7510. if (!this.closed) {
  7511. var lastPoint = this._points[this._points.length - 1];
  7512. var firstPoint = this._points[0];
  7513. result += (firstPoint.subtract(lastPoint).length());
  7514. }
  7515. return result;
  7516. };
  7517. /**
  7518. * Gets the points which construct the path
  7519. * @returns the Path2 internal array of points.
  7520. */
  7521. Path2.prototype.getPoints = function () {
  7522. return this._points;
  7523. };
  7524. /**
  7525. * Retreives the point at the distance aways from the starting point
  7526. * @param normalizedLengthPosition the length along the path to retreive the point from
  7527. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7528. */
  7529. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7530. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7531. return Vector2.Zero();
  7532. }
  7533. var lengthPosition = normalizedLengthPosition * this.length();
  7534. var previousOffset = 0;
  7535. for (var i = 0; i < this._points.length; i++) {
  7536. var j = (i + 1) % this._points.length;
  7537. var a = this._points[i];
  7538. var b = this._points[j];
  7539. var bToA = b.subtract(a);
  7540. var nextOffset = (bToA.length() + previousOffset);
  7541. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7542. var dir = bToA.normalize();
  7543. var localOffset = lengthPosition - previousOffset;
  7544. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7545. }
  7546. previousOffset = nextOffset;
  7547. }
  7548. return Vector2.Zero();
  7549. };
  7550. /**
  7551. * Creates a new path starting from an x and y position
  7552. * @param x starting x value
  7553. * @param y starting y value
  7554. * @returns a new Path2 starting at the coordinates (x, y).
  7555. */
  7556. Path2.StartingAt = function (x, y) {
  7557. return new Path2(x, y);
  7558. };
  7559. return Path2;
  7560. }());
  7561. BABYLON.Path2 = Path2;
  7562. /**
  7563. * Represents a 3D path made up of multiple 3D points
  7564. */
  7565. var Path3D = /** @class */ (function () {
  7566. /**
  7567. * new Path3D(path, normal, raw)
  7568. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7569. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7570. * @param path an array of Vector3, the curve axis of the Path3D
  7571. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7572. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7573. */
  7574. function Path3D(
  7575. /**
  7576. * an array of Vector3, the curve axis of the Path3D
  7577. */
  7578. path, firstNormal, raw) {
  7579. if (firstNormal === void 0) { firstNormal = null; }
  7580. this.path = path;
  7581. this._curve = new Array();
  7582. this._distances = new Array();
  7583. this._tangents = new Array();
  7584. this._normals = new Array();
  7585. this._binormals = new Array();
  7586. for (var p = 0; p < path.length; p++) {
  7587. this._curve[p] = path[p].clone(); // hard copy
  7588. }
  7589. this._raw = raw || false;
  7590. this._compute(firstNormal);
  7591. }
  7592. /**
  7593. * Returns the Path3D array of successive Vector3 designing its curve.
  7594. * @returns the Path3D array of successive Vector3 designing its curve.
  7595. */
  7596. Path3D.prototype.getCurve = function () {
  7597. return this._curve;
  7598. };
  7599. /**
  7600. * Returns an array populated with tangent vectors on each Path3D curve point.
  7601. * @returns an array populated with tangent vectors on each Path3D curve point.
  7602. */
  7603. Path3D.prototype.getTangents = function () {
  7604. return this._tangents;
  7605. };
  7606. /**
  7607. * Returns an array populated with normal vectors on each Path3D curve point.
  7608. * @returns an array populated with normal vectors on each Path3D curve point.
  7609. */
  7610. Path3D.prototype.getNormals = function () {
  7611. return this._normals;
  7612. };
  7613. /**
  7614. * Returns an array populated with binormal vectors on each Path3D curve point.
  7615. * @returns an array populated with binormal vectors on each Path3D curve point.
  7616. */
  7617. Path3D.prototype.getBinormals = function () {
  7618. return this._binormals;
  7619. };
  7620. /**
  7621. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7622. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7623. */
  7624. Path3D.prototype.getDistances = function () {
  7625. return this._distances;
  7626. };
  7627. /**
  7628. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7629. * @param path path which all values are copied into the curves points
  7630. * @param firstNormal which should be projected onto the curve
  7631. * @returns the same object updated.
  7632. */
  7633. Path3D.prototype.update = function (path, firstNormal) {
  7634. if (firstNormal === void 0) { firstNormal = null; }
  7635. for (var p = 0; p < path.length; p++) {
  7636. this._curve[p].x = path[p].x;
  7637. this._curve[p].y = path[p].y;
  7638. this._curve[p].z = path[p].z;
  7639. }
  7640. this._compute(firstNormal);
  7641. return this;
  7642. };
  7643. // private function compute() : computes tangents, normals and binormals
  7644. Path3D.prototype._compute = function (firstNormal) {
  7645. var l = this._curve.length;
  7646. // first and last tangents
  7647. this._tangents[0] = this._getFirstNonNullVector(0);
  7648. if (!this._raw) {
  7649. this._tangents[0].normalize();
  7650. }
  7651. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7652. if (!this._raw) {
  7653. this._tangents[l - 1].normalize();
  7654. }
  7655. // normals and binormals at first point : arbitrary vector with _normalVector()
  7656. var tg0 = this._tangents[0];
  7657. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7658. this._normals[0] = pp0;
  7659. if (!this._raw) {
  7660. this._normals[0].normalize();
  7661. }
  7662. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7663. if (!this._raw) {
  7664. this._binormals[0].normalize();
  7665. }
  7666. this._distances[0] = 0.0;
  7667. // normals and binormals : next points
  7668. var prev; // previous vector (segment)
  7669. var cur; // current vector (segment)
  7670. var curTang; // current tangent
  7671. // previous normal
  7672. var prevBinor; // previous binormal
  7673. for (var i = 1; i < l; i++) {
  7674. // tangents
  7675. prev = this._getLastNonNullVector(i);
  7676. if (i < l - 1) {
  7677. cur = this._getFirstNonNullVector(i);
  7678. this._tangents[i] = prev.add(cur);
  7679. this._tangents[i].normalize();
  7680. }
  7681. this._distances[i] = this._distances[i - 1] + prev.length();
  7682. // normals and binormals
  7683. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7684. curTang = this._tangents[i];
  7685. prevBinor = this._binormals[i - 1];
  7686. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7687. if (!this._raw) {
  7688. this._normals[i].normalize();
  7689. }
  7690. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7691. if (!this._raw) {
  7692. this._binormals[i].normalize();
  7693. }
  7694. }
  7695. };
  7696. // private function getFirstNonNullVector(index)
  7697. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7698. Path3D.prototype._getFirstNonNullVector = function (index) {
  7699. var i = 1;
  7700. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7701. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7702. i++;
  7703. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7704. }
  7705. return nNVector;
  7706. };
  7707. // private function getLastNonNullVector(index)
  7708. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7709. Path3D.prototype._getLastNonNullVector = function (index) {
  7710. var i = 1;
  7711. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7712. while (nLVector.length() === 0 && index > i + 1) {
  7713. i++;
  7714. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7715. }
  7716. return nLVector;
  7717. };
  7718. // private function normalVector(v0, vt, va) :
  7719. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7720. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7721. Path3D.prototype._normalVector = function (v0, vt, va) {
  7722. var normal0;
  7723. var tgl = vt.length();
  7724. if (tgl === 0.0) {
  7725. tgl = 1.0;
  7726. }
  7727. if (va === undefined || va === null) {
  7728. var point;
  7729. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7730. point = new Vector3(0.0, -1.0, 0.0);
  7731. }
  7732. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7733. point = new Vector3(1.0, 0.0, 0.0);
  7734. }
  7735. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7736. point = new Vector3(0.0, 0.0, 1.0);
  7737. }
  7738. else {
  7739. point = Vector3.Zero();
  7740. }
  7741. normal0 = Vector3.Cross(vt, point);
  7742. }
  7743. else {
  7744. normal0 = Vector3.Cross(vt, va);
  7745. Vector3.CrossToRef(normal0, vt, normal0);
  7746. }
  7747. normal0.normalize();
  7748. return normal0;
  7749. };
  7750. return Path3D;
  7751. }());
  7752. BABYLON.Path3D = Path3D;
  7753. /**
  7754. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7755. * A Curve3 is designed from a series of successive Vector3.
  7756. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7757. */
  7758. var Curve3 = /** @class */ (function () {
  7759. /**
  7760. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7761. * A Curve3 is designed from a series of successive Vector3.
  7762. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7763. * @param points points which make up the curve
  7764. */
  7765. function Curve3(points) {
  7766. this._length = 0.0;
  7767. this._points = points;
  7768. this._length = this._computeLength(points);
  7769. }
  7770. /**
  7771. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7772. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7773. * @param v1 (Vector3) the control point
  7774. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7775. * @param nbPoints (integer) the wanted number of points in the curve
  7776. * @returns the created Curve3
  7777. */
  7778. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7779. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7780. var bez = new Array();
  7781. var equation = function (t, val0, val1, val2) {
  7782. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7783. return res;
  7784. };
  7785. for (var i = 0; i <= nbPoints; i++) {
  7786. 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)));
  7787. }
  7788. return new Curve3(bez);
  7789. };
  7790. /**
  7791. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7792. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7793. * @param v1 (Vector3) the first control point
  7794. * @param v2 (Vector3) the second control point
  7795. * @param v3 (Vector3) the end point of the Cubic Bezier
  7796. * @param nbPoints (integer) the wanted number of points in the curve
  7797. * @returns the created Curve3
  7798. */
  7799. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7800. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7801. var bez = new Array();
  7802. var equation = function (t, val0, val1, val2, val3) {
  7803. 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;
  7804. return res;
  7805. };
  7806. for (var i = 0; i <= nbPoints; i++) {
  7807. 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)));
  7808. }
  7809. return new Curve3(bez);
  7810. };
  7811. /**
  7812. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7813. * @param p1 (Vector3) the origin point of the Hermite Spline
  7814. * @param t1 (Vector3) the tangent vector at the origin point
  7815. * @param p2 (Vector3) the end point of the Hermite Spline
  7816. * @param t2 (Vector3) the tangent vector at the end point
  7817. * @param nbPoints (integer) the wanted number of points in the curve
  7818. * @returns the created Curve3
  7819. */
  7820. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7821. var hermite = new Array();
  7822. var step = 1.0 / nbPoints;
  7823. for (var i = 0; i <= nbPoints; i++) {
  7824. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7825. }
  7826. return new Curve3(hermite);
  7827. };
  7828. /**
  7829. * Returns a Curve3 object along a CatmullRom Spline curve :
  7830. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7831. * @param nbPoints (integer) the wanted number of points between each curve control points
  7832. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7833. * @returns the created Curve3
  7834. */
  7835. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7836. var catmullRom = new Array();
  7837. var step = 1.0 / nbPoints;
  7838. var amount = 0.0;
  7839. if (closed) {
  7840. var pointsCount = points.length;
  7841. for (var i = 0; i < pointsCount; i++) {
  7842. amount = 0;
  7843. for (var c = 0; c < nbPoints; c++) {
  7844. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7845. amount += step;
  7846. }
  7847. }
  7848. catmullRom.push(catmullRom[0]);
  7849. }
  7850. else {
  7851. var totalPoints = new Array();
  7852. totalPoints.push(points[0].clone());
  7853. Array.prototype.push.apply(totalPoints, points);
  7854. totalPoints.push(points[points.length - 1].clone());
  7855. for (var i = 0; i < totalPoints.length - 3; i++) {
  7856. amount = 0;
  7857. for (var c = 0; c < nbPoints; c++) {
  7858. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7859. amount += step;
  7860. }
  7861. }
  7862. i--;
  7863. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7864. }
  7865. return new Curve3(catmullRom);
  7866. };
  7867. /**
  7868. * @returns the Curve3 stored array of successive Vector3
  7869. */
  7870. Curve3.prototype.getPoints = function () {
  7871. return this._points;
  7872. };
  7873. /**
  7874. * @returns the computed length (float) of the curve.
  7875. */
  7876. Curve3.prototype.length = function () {
  7877. return this._length;
  7878. };
  7879. /**
  7880. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7881. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7882. * curveA and curveB keep unchanged.
  7883. * @param curve the curve to continue from this curve
  7884. * @returns the newly constructed curve
  7885. */
  7886. Curve3.prototype.continue = function (curve) {
  7887. var lastPoint = this._points[this._points.length - 1];
  7888. var continuedPoints = this._points.slice();
  7889. var curvePoints = curve.getPoints();
  7890. for (var i = 1; i < curvePoints.length; i++) {
  7891. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7892. }
  7893. var continuedCurve = new Curve3(continuedPoints);
  7894. return continuedCurve;
  7895. };
  7896. Curve3.prototype._computeLength = function (path) {
  7897. var l = 0;
  7898. for (var i = 1; i < path.length; i++) {
  7899. l += (path[i].subtract(path[i - 1])).length();
  7900. }
  7901. return l;
  7902. };
  7903. return Curve3;
  7904. }());
  7905. BABYLON.Curve3 = Curve3;
  7906. // Vertex formats
  7907. /**
  7908. * Contains position and normal vectors for a vertex
  7909. */
  7910. var PositionNormalVertex = /** @class */ (function () {
  7911. /**
  7912. * Creates a PositionNormalVertex
  7913. * @param position the position of the vertex (defaut: 0,0,0)
  7914. * @param normal the normal of the vertex (defaut: 0,1,0)
  7915. */
  7916. function PositionNormalVertex(
  7917. /** the position of the vertex (defaut: 0,0,0) */
  7918. position,
  7919. /** the normal of the vertex (defaut: 0,1,0) */
  7920. normal) {
  7921. if (position === void 0) { position = Vector3.Zero(); }
  7922. if (normal === void 0) { normal = Vector3.Up(); }
  7923. this.position = position;
  7924. this.normal = normal;
  7925. }
  7926. /**
  7927. * Clones the PositionNormalVertex
  7928. * @returns the cloned PositionNormalVertex
  7929. */
  7930. PositionNormalVertex.prototype.clone = function () {
  7931. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7932. };
  7933. return PositionNormalVertex;
  7934. }());
  7935. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7936. /**
  7937. * Contains position, normal and uv vectors for a vertex
  7938. */
  7939. var PositionNormalTextureVertex = /** @class */ (function () {
  7940. /**
  7941. * Creates a PositionNormalTextureVertex
  7942. * @param position the position of the vertex (defaut: 0,0,0)
  7943. * @param normal the normal of the vertex (defaut: 0,1,0)
  7944. * @param uv the uv of the vertex (default: 0,0)
  7945. */
  7946. function PositionNormalTextureVertex(
  7947. /** the position of the vertex (defaut: 0,0,0) */
  7948. position,
  7949. /** the normal of the vertex (defaut: 0,1,0) */
  7950. normal,
  7951. /** the uv of the vertex (default: 0,0) */
  7952. uv) {
  7953. if (position === void 0) { position = Vector3.Zero(); }
  7954. if (normal === void 0) { normal = Vector3.Up(); }
  7955. if (uv === void 0) { uv = Vector2.Zero(); }
  7956. this.position = position;
  7957. this.normal = normal;
  7958. this.uv = uv;
  7959. }
  7960. /**
  7961. * Clones the PositionNormalTextureVertex
  7962. * @returns the cloned PositionNormalTextureVertex
  7963. */
  7964. PositionNormalTextureVertex.prototype.clone = function () {
  7965. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7966. };
  7967. return PositionNormalTextureVertex;
  7968. }());
  7969. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7970. // Temporary pre-allocated objects for engine internal use
  7971. // usage in any internal function :
  7972. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7973. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7974. /**
  7975. * @hidden
  7976. */
  7977. var Tmp = /** @class */ (function () {
  7978. function Tmp() {
  7979. }
  7980. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7981. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7982. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7983. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7984. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7985. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7986. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7987. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7988. Matrix.Zero(), Matrix.Zero(),
  7989. Matrix.Zero(), Matrix.Zero(),
  7990. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7991. return Tmp;
  7992. }());
  7993. BABYLON.Tmp = Tmp;
  7994. /**
  7995. * @hidden
  7996. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7997. */
  7998. var MathTmp = /** @class */ (function () {
  7999. function MathTmp() {
  8000. }
  8001. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  8002. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  8003. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  8004. return MathTmp;
  8005. }());
  8006. })(BABYLON || (BABYLON = {}));
  8007. //# sourceMappingURL=babylon.math.js.map
  8008. var BABYLON;
  8009. (function (BABYLON) {
  8010. /**
  8011. * Scalar computation library
  8012. */
  8013. var Scalar = /** @class */ (function () {
  8014. function Scalar() {
  8015. }
  8016. /**
  8017. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  8018. * @param a number
  8019. * @param b number
  8020. * @param epsilon (default = 1.401298E-45)
  8021. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  8022. */
  8023. Scalar.WithinEpsilon = function (a, b, epsilon) {
  8024. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  8025. var num = a - b;
  8026. return -epsilon <= num && num <= epsilon;
  8027. };
  8028. /**
  8029. * Returns a string : the upper case translation of the number i to hexadecimal.
  8030. * @param i number
  8031. * @returns the upper case translation of the number i to hexadecimal.
  8032. */
  8033. Scalar.ToHex = function (i) {
  8034. var str = i.toString(16);
  8035. if (i <= 15) {
  8036. return ("0" + str).toUpperCase();
  8037. }
  8038. return str.toUpperCase();
  8039. };
  8040. /**
  8041. * Returns -1 if value is negative and +1 is value is positive.
  8042. * @param value the value
  8043. * @returns the value itself if it's equal to zero.
  8044. */
  8045. Scalar.Sign = function (value) {
  8046. value = +value; // convert to a number
  8047. if (value === 0 || isNaN(value)) {
  8048. return value;
  8049. }
  8050. return value > 0 ? 1 : -1;
  8051. };
  8052. /**
  8053. * Returns the value itself if it's between min and max.
  8054. * Returns min if the value is lower than min.
  8055. * Returns max if the value is greater than max.
  8056. * @param value the value to clmap
  8057. * @param min the min value to clamp to (default: 0)
  8058. * @param max the max value to clamp to (default: 1)
  8059. * @returns the clamped value
  8060. */
  8061. Scalar.Clamp = function (value, min, max) {
  8062. if (min === void 0) { min = 0; }
  8063. if (max === void 0) { max = 1; }
  8064. return Math.min(max, Math.max(min, value));
  8065. };
  8066. /**
  8067. * the log2 of value.
  8068. * @param value the value to compute log2 of
  8069. * @returns the log2 of value.
  8070. */
  8071. Scalar.Log2 = function (value) {
  8072. return Math.log(value) * Math.LOG2E;
  8073. };
  8074. /**
  8075. * Loops the value, so that it is never larger than length and never smaller than 0.
  8076. *
  8077. * This is similar to the modulo operator but it works with floating point numbers.
  8078. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8079. * With t = 5 and length = 2.5, the result would be 0.0.
  8080. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8081. * @param value the value
  8082. * @param length the length
  8083. * @returns the looped value
  8084. */
  8085. Scalar.Repeat = function (value, length) {
  8086. return value - Math.floor(value / length) * length;
  8087. };
  8088. /**
  8089. * Normalize the value between 0.0 and 1.0 using min and max values
  8090. * @param value value to normalize
  8091. * @param min max to normalize between
  8092. * @param max min to normalize between
  8093. * @returns the normalized value
  8094. */
  8095. Scalar.Normalize = function (value, min, max) {
  8096. return (value - min) / (max - min);
  8097. };
  8098. /**
  8099. * Denormalize the value from 0.0 and 1.0 using min and max values
  8100. * @param normalized value to denormalize
  8101. * @param min max to denormalize between
  8102. * @param max min to denormalize between
  8103. * @returns the denormalized value
  8104. */
  8105. Scalar.Denormalize = function (normalized, min, max) {
  8106. return (normalized * (max - min) + min);
  8107. };
  8108. /**
  8109. * Calculates the shortest difference between two given angles given in degrees.
  8110. * @param current current angle in degrees
  8111. * @param target target angle in degrees
  8112. * @returns the delta
  8113. */
  8114. Scalar.DeltaAngle = function (current, target) {
  8115. var num = Scalar.Repeat(target - current, 360.0);
  8116. if (num > 180.0) {
  8117. num -= 360.0;
  8118. }
  8119. return num;
  8120. };
  8121. /**
  8122. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8123. * @param tx value
  8124. * @param length length
  8125. * @returns The returned value will move back and forth between 0 and length
  8126. */
  8127. Scalar.PingPong = function (tx, length) {
  8128. var t = Scalar.Repeat(tx, length * 2.0);
  8129. return length - Math.abs(t - length);
  8130. };
  8131. /**
  8132. * Interpolates between min and max with smoothing at the limits.
  8133. *
  8134. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8135. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8136. * @param from from
  8137. * @param to to
  8138. * @param tx value
  8139. * @returns the smooth stepped value
  8140. */
  8141. Scalar.SmoothStep = function (from, to, tx) {
  8142. var t = Scalar.Clamp(tx);
  8143. t = -2.0 * t * t * t + 3.0 * t * t;
  8144. return to * t + from * (1.0 - t);
  8145. };
  8146. /**
  8147. * Moves a value current towards target.
  8148. *
  8149. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8150. * Negative values of maxDelta pushes the value away from target.
  8151. * @param current current value
  8152. * @param target target value
  8153. * @param maxDelta max distance to move
  8154. * @returns resulting value
  8155. */
  8156. Scalar.MoveTowards = function (current, target, maxDelta) {
  8157. var result = 0;
  8158. if (Math.abs(target - current) <= maxDelta) {
  8159. result = target;
  8160. }
  8161. else {
  8162. result = current + Scalar.Sign(target - current) * maxDelta;
  8163. }
  8164. return result;
  8165. };
  8166. /**
  8167. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8168. *
  8169. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8170. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8171. * @param current current value
  8172. * @param target target value
  8173. * @param maxDelta max distance to move
  8174. * @returns resulting angle
  8175. */
  8176. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8177. var num = Scalar.DeltaAngle(current, target);
  8178. var result = 0;
  8179. if (-maxDelta < num && num < maxDelta) {
  8180. result = target;
  8181. }
  8182. else {
  8183. target = current + num;
  8184. result = Scalar.MoveTowards(current, target, maxDelta);
  8185. }
  8186. return result;
  8187. };
  8188. /**
  8189. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8190. * @param start start value
  8191. * @param end target value
  8192. * @param amount amount to lerp between
  8193. * @returns the lerped value
  8194. */
  8195. Scalar.Lerp = function (start, end, amount) {
  8196. return start + ((end - start) * amount);
  8197. };
  8198. /**
  8199. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8200. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8201. * @param start start value
  8202. * @param end target value
  8203. * @param amount amount to lerp between
  8204. * @returns the lerped value
  8205. */
  8206. Scalar.LerpAngle = function (start, end, amount) {
  8207. var num = Scalar.Repeat(end - start, 360.0);
  8208. if (num > 180.0) {
  8209. num -= 360.0;
  8210. }
  8211. return start + num * Scalar.Clamp(amount);
  8212. };
  8213. /**
  8214. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8215. * @param a start value
  8216. * @param b target value
  8217. * @param value value between a and b
  8218. * @returns the inverseLerp value
  8219. */
  8220. Scalar.InverseLerp = function (a, b, value) {
  8221. var result = 0;
  8222. if (a != b) {
  8223. result = Scalar.Clamp((value - a) / (b - a));
  8224. }
  8225. else {
  8226. result = 0.0;
  8227. }
  8228. return result;
  8229. };
  8230. /**
  8231. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8232. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  8233. * @param value1 spline value
  8234. * @param tangent1 spline value
  8235. * @param value2 spline value
  8236. * @param tangent2 spline value
  8237. * @param amount input value
  8238. * @returns hermite result
  8239. */
  8240. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8241. var squared = amount * amount;
  8242. var cubed = amount * squared;
  8243. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8244. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8245. var part3 = (cubed - (2.0 * squared)) + amount;
  8246. var part4 = cubed - squared;
  8247. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8248. };
  8249. /**
  8250. * Returns a random float number between and min and max values
  8251. * @param min min value of random
  8252. * @param max max value of random
  8253. * @returns random value
  8254. */
  8255. Scalar.RandomRange = function (min, max) {
  8256. if (min === max) {
  8257. return min;
  8258. }
  8259. return ((Math.random() * (max - min)) + min);
  8260. };
  8261. /**
  8262. * This function returns percentage of a number in a given range.
  8263. *
  8264. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8265. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8266. * @param number to convert to percentage
  8267. * @param min min range
  8268. * @param max max range
  8269. * @returns the percentage
  8270. */
  8271. Scalar.RangeToPercent = function (number, min, max) {
  8272. return ((number - min) / (max - min));
  8273. };
  8274. /**
  8275. * This function returns number that corresponds to the percentage in a given range.
  8276. *
  8277. * PercentToRange(0.34,0,100) will return 34.
  8278. * @param percent to convert to number
  8279. * @param min min range
  8280. * @param max max range
  8281. * @returns the number
  8282. */
  8283. Scalar.PercentToRange = function (percent, min, max) {
  8284. return ((max - min) * percent + min);
  8285. };
  8286. /**
  8287. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8288. * @param angle The angle to normalize in radian.
  8289. * @return The converted angle.
  8290. */
  8291. Scalar.NormalizeRadians = function (angle) {
  8292. // More precise but slower version kept for reference.
  8293. // angle = angle % Tools.TwoPi;
  8294. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8295. //if (angle > Math.PI) {
  8296. // angle -= Tools.TwoPi;
  8297. //}
  8298. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8299. return angle;
  8300. };
  8301. /**
  8302. * Two pi constants convenient for computation.
  8303. */
  8304. Scalar.TwoPi = Math.PI * 2;
  8305. return Scalar;
  8306. }());
  8307. BABYLON.Scalar = Scalar;
  8308. })(BABYLON || (BABYLON = {}));
  8309. //# sourceMappingURL=babylon.math.scalar.js.map
  8310. //# sourceMappingURL=babylon.mixins.js.map
  8311. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8312. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8313. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8314. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8315. //# sourceMappingURL=babylon.webgl2.js.map
  8316. var BABYLON;
  8317. (function (BABYLON) {
  8318. var __decoratorInitialStore = {};
  8319. var __mergedStore = {};
  8320. var _copySource = function (creationFunction, source, instanciate) {
  8321. var destination = creationFunction();
  8322. // Tags
  8323. if (BABYLON.Tags) {
  8324. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8325. }
  8326. var classStore = getMergedStore(destination);
  8327. // Properties
  8328. for (var property in classStore) {
  8329. var propertyDescriptor = classStore[property];
  8330. var sourceProperty = source[property];
  8331. var propertyType = propertyDescriptor.type;
  8332. if (sourceProperty !== undefined && sourceProperty !== null) {
  8333. switch (propertyType) {
  8334. case 0: // Value
  8335. case 6: // Mesh reference
  8336. case 11: // Camera reference
  8337. destination[property] = sourceProperty;
  8338. break;
  8339. case 1: // Texture
  8340. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8341. break;
  8342. case 2: // Color3
  8343. case 3: // FresnelParameters
  8344. case 4: // Vector2
  8345. case 5: // Vector3
  8346. case 7: // Color Curves
  8347. case 10: // Quaternion
  8348. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8349. break;
  8350. }
  8351. }
  8352. }
  8353. return destination;
  8354. };
  8355. function getDirectStore(target) {
  8356. var classKey = target.getClassName();
  8357. if (!__decoratorInitialStore[classKey]) {
  8358. __decoratorInitialStore[classKey] = {};
  8359. }
  8360. return __decoratorInitialStore[classKey];
  8361. }
  8362. /**
  8363. * Return the list of properties flagged as serializable
  8364. * @param target: host object
  8365. */
  8366. function getMergedStore(target) {
  8367. var classKey = target.getClassName();
  8368. if (__mergedStore[classKey]) {
  8369. return __mergedStore[classKey];
  8370. }
  8371. __mergedStore[classKey] = {};
  8372. var store = __mergedStore[classKey];
  8373. var currentTarget = target;
  8374. var currentKey = classKey;
  8375. while (currentKey) {
  8376. var initialStore = __decoratorInitialStore[currentKey];
  8377. for (var property in initialStore) {
  8378. store[property] = initialStore[property];
  8379. }
  8380. var parent_1 = void 0;
  8381. var done = false;
  8382. do {
  8383. parent_1 = Object.getPrototypeOf(currentTarget);
  8384. if (!parent_1.getClassName) {
  8385. done = true;
  8386. break;
  8387. }
  8388. if (parent_1.getClassName() !== currentKey) {
  8389. break;
  8390. }
  8391. currentTarget = parent_1;
  8392. } while (parent_1);
  8393. if (done) {
  8394. break;
  8395. }
  8396. currentKey = parent_1.getClassName();
  8397. currentTarget = parent_1;
  8398. }
  8399. return store;
  8400. }
  8401. function generateSerializableMember(type, sourceName) {
  8402. return function (target, propertyKey) {
  8403. var classStore = getDirectStore(target);
  8404. if (!classStore[propertyKey]) {
  8405. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8406. }
  8407. };
  8408. }
  8409. function generateExpandMember(setCallback, targetKey) {
  8410. if (targetKey === void 0) { targetKey = null; }
  8411. return function (target, propertyKey) {
  8412. var key = targetKey || ("_" + propertyKey);
  8413. Object.defineProperty(target, propertyKey, {
  8414. get: function () {
  8415. return this[key];
  8416. },
  8417. set: function (value) {
  8418. if (this[key] === value) {
  8419. return;
  8420. }
  8421. this[key] = value;
  8422. target[setCallback].apply(this);
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. };
  8428. }
  8429. function expandToProperty(callback, targetKey) {
  8430. if (targetKey === void 0) { targetKey = null; }
  8431. return generateExpandMember(callback, targetKey);
  8432. }
  8433. BABYLON.expandToProperty = expandToProperty;
  8434. function serialize(sourceName) {
  8435. return generateSerializableMember(0, sourceName); // value member
  8436. }
  8437. BABYLON.serialize = serialize;
  8438. function serializeAsTexture(sourceName) {
  8439. return generateSerializableMember(1, sourceName); // texture member
  8440. }
  8441. BABYLON.serializeAsTexture = serializeAsTexture;
  8442. function serializeAsColor3(sourceName) {
  8443. return generateSerializableMember(2, sourceName); // color3 member
  8444. }
  8445. BABYLON.serializeAsColor3 = serializeAsColor3;
  8446. function serializeAsFresnelParameters(sourceName) {
  8447. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8448. }
  8449. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8450. function serializeAsVector2(sourceName) {
  8451. return generateSerializableMember(4, sourceName); // vector2 member
  8452. }
  8453. BABYLON.serializeAsVector2 = serializeAsVector2;
  8454. function serializeAsVector3(sourceName) {
  8455. return generateSerializableMember(5, sourceName); // vector3 member
  8456. }
  8457. BABYLON.serializeAsVector3 = serializeAsVector3;
  8458. function serializeAsMeshReference(sourceName) {
  8459. return generateSerializableMember(6, sourceName); // mesh reference member
  8460. }
  8461. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8462. function serializeAsColorCurves(sourceName) {
  8463. return generateSerializableMember(7, sourceName); // color curves
  8464. }
  8465. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8466. function serializeAsColor4(sourceName) {
  8467. return generateSerializableMember(8, sourceName); // color 4
  8468. }
  8469. BABYLON.serializeAsColor4 = serializeAsColor4;
  8470. function serializeAsImageProcessingConfiguration(sourceName) {
  8471. return generateSerializableMember(9, sourceName); // image processing
  8472. }
  8473. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8474. function serializeAsQuaternion(sourceName) {
  8475. return generateSerializableMember(10, sourceName); // quaternion member
  8476. }
  8477. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8478. /**
  8479. * Decorator used to define property that can be serialized as reference to a camera
  8480. * @param sourceName defines the name of the property to decorate
  8481. */
  8482. function serializeAsCameraReference(sourceName) {
  8483. return generateSerializableMember(11, sourceName); // camera reference member
  8484. }
  8485. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8486. /**
  8487. * Class used to help serialization objects
  8488. */
  8489. var SerializationHelper = /** @class */ (function () {
  8490. function SerializationHelper() {
  8491. }
  8492. /**
  8493. * Static function used to serialized a specific entity
  8494. * @param entity defines the entity to serialize
  8495. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  8496. * @returns a JSON compatible object representing the serialization of the entity
  8497. */
  8498. SerializationHelper.Serialize = function (entity, serializationObject) {
  8499. if (!serializationObject) {
  8500. serializationObject = {};
  8501. }
  8502. // Tags
  8503. if (BABYLON.Tags) {
  8504. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8505. }
  8506. var serializedProperties = getMergedStore(entity);
  8507. // Properties
  8508. for (var property in serializedProperties) {
  8509. var propertyDescriptor = serializedProperties[property];
  8510. var targetPropertyName = propertyDescriptor.sourceName || property;
  8511. var propertyType = propertyDescriptor.type;
  8512. var sourceProperty = entity[property];
  8513. if (sourceProperty !== undefined && sourceProperty !== null) {
  8514. switch (propertyType) {
  8515. case 0: // Value
  8516. serializationObject[targetPropertyName] = sourceProperty;
  8517. break;
  8518. case 1: // Texture
  8519. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8520. break;
  8521. case 2: // Color3
  8522. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8523. break;
  8524. case 3: // FresnelParameters
  8525. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8526. break;
  8527. case 4: // Vector2
  8528. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8529. break;
  8530. case 5: // Vector3
  8531. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8532. break;
  8533. case 6: // Mesh reference
  8534. serializationObject[targetPropertyName] = sourceProperty.id;
  8535. break;
  8536. case 7: // Color Curves
  8537. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8538. break;
  8539. case 8: // Color 4
  8540. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8541. break;
  8542. case 9: // Image Processing
  8543. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8544. break;
  8545. case 10: // Quaternion
  8546. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8547. break;
  8548. case 11: // Camera reference
  8549. serializationObject[targetPropertyName] = sourceProperty.id;
  8550. break;
  8551. }
  8552. }
  8553. }
  8554. return serializationObject;
  8555. };
  8556. /**
  8557. * Creates a new entity from a serialization data object
  8558. * @param creationFunction defines a function used to instanciated the new entity
  8559. * @param source defines the source serialization data
  8560. * @param scene defines the hosting scene
  8561. * @param rootUrl defines the root url for resources
  8562. * @returns a new entity
  8563. */
  8564. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8565. if (rootUrl === void 0) { rootUrl = null; }
  8566. var destination = creationFunction();
  8567. if (!rootUrl) {
  8568. rootUrl = "";
  8569. }
  8570. // Tags
  8571. if (BABYLON.Tags) {
  8572. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8573. }
  8574. var classStore = getMergedStore(destination);
  8575. // Properties
  8576. for (var property in classStore) {
  8577. var propertyDescriptor = classStore[property];
  8578. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8579. var propertyType = propertyDescriptor.type;
  8580. if (sourceProperty !== undefined && sourceProperty !== null) {
  8581. var dest = destination;
  8582. switch (propertyType) {
  8583. case 0: // Value
  8584. dest[property] = sourceProperty;
  8585. break;
  8586. case 1: // Texture
  8587. if (scene) {
  8588. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8589. }
  8590. break;
  8591. case 2: // Color3
  8592. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8593. break;
  8594. case 3: // FresnelParameters
  8595. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8596. break;
  8597. case 4: // Vector2
  8598. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8599. break;
  8600. case 5: // Vector3
  8601. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8602. break;
  8603. case 6: // Mesh reference
  8604. if (scene) {
  8605. dest[property] = scene.getLastMeshByID(sourceProperty);
  8606. }
  8607. break;
  8608. case 7: // Color Curves
  8609. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8610. break;
  8611. case 8: // Color 4
  8612. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8613. break;
  8614. case 9: // Image Processing
  8615. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8616. break;
  8617. case 10: // Quaternion
  8618. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8619. break;
  8620. case 11: // Camera reference
  8621. if (scene) {
  8622. dest[property] = scene.getCameraByID(sourceProperty);
  8623. }
  8624. break;
  8625. }
  8626. }
  8627. }
  8628. return destination;
  8629. };
  8630. /**
  8631. * Clones an object
  8632. * @param creationFunction defines the function used to instanciate the new object
  8633. * @param source defines the source object
  8634. * @returns the cloned object
  8635. */
  8636. SerializationHelper.Clone = function (creationFunction, source) {
  8637. return _copySource(creationFunction, source, false);
  8638. };
  8639. /**
  8640. * Instanciates a new object based on a source one (some data will be shared between both object)
  8641. * @param creationFunction defines the function used to instanciate the new object
  8642. * @param source defines the source object
  8643. * @returns the new object
  8644. */
  8645. SerializationHelper.Instanciate = function (creationFunction, source) {
  8646. return _copySource(creationFunction, source, true);
  8647. };
  8648. return SerializationHelper;
  8649. }());
  8650. BABYLON.SerializationHelper = SerializationHelper;
  8651. })(BABYLON || (BABYLON = {}));
  8652. //# sourceMappingURL=babylon.decorators.js.map
  8653. var BABYLON;
  8654. (function (BABYLON) {
  8655. /**
  8656. * Wrapper class for promise with external resolve and reject.
  8657. */
  8658. var Deferred = /** @class */ (function () {
  8659. /**
  8660. * Constructor for this deferred object.
  8661. */
  8662. function Deferred() {
  8663. var _this = this;
  8664. this.promise = new Promise(function (resolve, reject) {
  8665. _this._resolve = resolve;
  8666. _this._reject = reject;
  8667. });
  8668. }
  8669. Object.defineProperty(Deferred.prototype, "resolve", {
  8670. /**
  8671. * The resolve method of the promise associated with this deferred object.
  8672. */
  8673. get: function () {
  8674. return this._resolve;
  8675. },
  8676. enumerable: true,
  8677. configurable: true
  8678. });
  8679. Object.defineProperty(Deferred.prototype, "reject", {
  8680. /**
  8681. * The reject method of the promise associated with this deferred object.
  8682. */
  8683. get: function () {
  8684. return this._reject;
  8685. },
  8686. enumerable: true,
  8687. configurable: true
  8688. });
  8689. return Deferred;
  8690. }());
  8691. BABYLON.Deferred = Deferred;
  8692. })(BABYLON || (BABYLON = {}));
  8693. //# sourceMappingURL=babylon.deferred.js.map
  8694. var BABYLON;
  8695. (function (BABYLON) {
  8696. /**
  8697. * A class serves as a medium between the observable and its observers
  8698. */
  8699. var EventState = /** @class */ (function () {
  8700. /**
  8701. * Create a new EventState
  8702. * @param mask defines the mask associated with this state
  8703. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8704. * @param target defines the original target of the state
  8705. * @param currentTarget defines the current target of the state
  8706. */
  8707. function EventState(mask, skipNextObservers, target, currentTarget) {
  8708. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8709. this.initalize(mask, skipNextObservers, target, currentTarget);
  8710. }
  8711. /**
  8712. * Initialize the current event state
  8713. * @param mask defines the mask associated with this state
  8714. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8715. * @param target defines the original target of the state
  8716. * @param currentTarget defines the current target of the state
  8717. * @returns the current event state
  8718. */
  8719. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8720. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8721. this.mask = mask;
  8722. this.skipNextObservers = skipNextObservers;
  8723. this.target = target;
  8724. this.currentTarget = currentTarget;
  8725. return this;
  8726. };
  8727. return EventState;
  8728. }());
  8729. BABYLON.EventState = EventState;
  8730. /**
  8731. * Represent an Observer registered to a given Observable object.
  8732. */
  8733. var Observer = /** @class */ (function () {
  8734. /**
  8735. * Creates a new observer
  8736. * @param callback defines the callback to call when the observer is notified
  8737. * @param mask defines the mask of the observer (used to filter notifications)
  8738. * @param scope defines the current scope used to restore the JS context
  8739. */
  8740. function Observer(
  8741. /**
  8742. * Defines the callback to call when the observer is notified
  8743. */
  8744. callback,
  8745. /**
  8746. * Defines the mask of the observer (used to filter notifications)
  8747. */
  8748. mask,
  8749. /**
  8750. * Defines the current scope used to restore the JS context
  8751. */
  8752. scope) {
  8753. if (scope === void 0) { scope = null; }
  8754. this.callback = callback;
  8755. this.mask = mask;
  8756. this.scope = scope;
  8757. /** @hidden */
  8758. this._willBeUnregistered = false;
  8759. /**
  8760. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8761. */
  8762. this.unregisterOnNextCall = false;
  8763. }
  8764. return Observer;
  8765. }());
  8766. BABYLON.Observer = Observer;
  8767. /**
  8768. * Represent a list of observers registered to multiple Observables object.
  8769. */
  8770. var MultiObserver = /** @class */ (function () {
  8771. function MultiObserver() {
  8772. }
  8773. /**
  8774. * Release associated resources
  8775. */
  8776. MultiObserver.prototype.dispose = function () {
  8777. if (this._observers && this._observables) {
  8778. for (var index = 0; index < this._observers.length; index++) {
  8779. this._observables[index].remove(this._observers[index]);
  8780. }
  8781. }
  8782. this._observers = null;
  8783. this._observables = null;
  8784. };
  8785. /**
  8786. * Raise a callback when one of the observable will notify
  8787. * @param observables defines a list of observables to watch
  8788. * @param callback defines the callback to call on notification
  8789. * @param mask defines the mask used to filter notifications
  8790. * @param scope defines the current scope used to restore the JS context
  8791. * @returns the new MultiObserver
  8792. */
  8793. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8794. if (mask === void 0) { mask = -1; }
  8795. if (scope === void 0) { scope = null; }
  8796. var result = new MultiObserver();
  8797. result._observers = new Array();
  8798. result._observables = observables;
  8799. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8800. var observable = observables_1[_i];
  8801. var observer = observable.add(callback, mask, false, scope);
  8802. if (observer) {
  8803. result._observers.push(observer);
  8804. }
  8805. }
  8806. return result;
  8807. };
  8808. return MultiObserver;
  8809. }());
  8810. BABYLON.MultiObserver = MultiObserver;
  8811. /**
  8812. * The Observable class is a simple implementation of the Observable pattern.
  8813. *
  8814. * 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.
  8815. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8816. * 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).
  8817. * 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.
  8818. */
  8819. var Observable = /** @class */ (function () {
  8820. /**
  8821. * Creates a new observable
  8822. * @param onObserverAdded defines a callback to call when a new observer is added
  8823. */
  8824. function Observable(onObserverAdded) {
  8825. this._observers = new Array();
  8826. this._eventState = new EventState(0);
  8827. if (onObserverAdded) {
  8828. this._onObserverAdded = onObserverAdded;
  8829. }
  8830. }
  8831. /**
  8832. * Create a new Observer with the specified callback
  8833. * @param callback the callback that will be executed for that Observer
  8834. * @param mask the mask used to filter observers
  8835. * @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.
  8836. * @param scope optional scope for the callback to be called from
  8837. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8838. * @returns the new observer created for the callback
  8839. */
  8840. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8841. if (mask === void 0) { mask = -1; }
  8842. if (insertFirst === void 0) { insertFirst = false; }
  8843. if (scope === void 0) { scope = null; }
  8844. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8845. if (!callback) {
  8846. return null;
  8847. }
  8848. var observer = new Observer(callback, mask, scope);
  8849. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8850. if (insertFirst) {
  8851. this._observers.unshift(observer);
  8852. }
  8853. else {
  8854. this._observers.push(observer);
  8855. }
  8856. if (this._onObserverAdded) {
  8857. this._onObserverAdded(observer);
  8858. }
  8859. return observer;
  8860. };
  8861. /**
  8862. * Create a new Observer with the specified callback and unregisters after the next notification
  8863. * @param callback the callback that will be executed for that Observer
  8864. * @returns the new observer created for the callback
  8865. */
  8866. Observable.prototype.addOnce = function (callback) {
  8867. return this.add(callback, undefined, undefined, undefined, true);
  8868. };
  8869. /**
  8870. * Remove an Observer from the Observable object
  8871. * @param observer the instance of the Observer to remove
  8872. * @returns false if it doesn't belong to this Observable
  8873. */
  8874. Observable.prototype.remove = function (observer) {
  8875. if (!observer) {
  8876. return false;
  8877. }
  8878. var index = this._observers.indexOf(observer);
  8879. if (index !== -1) {
  8880. this._deferUnregister(observer);
  8881. return true;
  8882. }
  8883. return false;
  8884. };
  8885. /**
  8886. * Remove a callback from the Observable object
  8887. * @param callback the callback to remove
  8888. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8889. * @returns false if it doesn't belong to this Observable
  8890. */
  8891. Observable.prototype.removeCallback = function (callback, scope) {
  8892. for (var index = 0; index < this._observers.length; index++) {
  8893. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8894. this._deferUnregister(this._observers[index]);
  8895. return true;
  8896. }
  8897. }
  8898. return false;
  8899. };
  8900. Observable.prototype._deferUnregister = function (observer) {
  8901. var _this = this;
  8902. observer.unregisterOnNextCall = false;
  8903. observer._willBeUnregistered = true;
  8904. BABYLON.Tools.SetImmediate(function () {
  8905. _this._remove(observer);
  8906. });
  8907. };
  8908. // This should only be called when not iterating over _observers to avoid callback skipping.
  8909. // Removes an observer from the _observer Array.
  8910. Observable.prototype._remove = function (observer) {
  8911. if (!observer) {
  8912. return false;
  8913. }
  8914. var index = this._observers.indexOf(observer);
  8915. if (index !== -1) {
  8916. this._observers.splice(index, 1);
  8917. return true;
  8918. }
  8919. return false;
  8920. };
  8921. /**
  8922. * Notify all Observers by calling their respective callback with the given data
  8923. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8924. * @param eventData defines the data to send to all observers
  8925. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8926. * @param target defines the original target of the state
  8927. * @param currentTarget defines the current target of the state
  8928. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8929. */
  8930. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8931. if (mask === void 0) { mask = -1; }
  8932. if (!this._observers.length) {
  8933. return true;
  8934. }
  8935. var state = this._eventState;
  8936. state.mask = mask;
  8937. state.target = target;
  8938. state.currentTarget = currentTarget;
  8939. state.skipNextObservers = false;
  8940. state.lastReturnValue = eventData;
  8941. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8942. var obs = _a[_i];
  8943. if (obs._willBeUnregistered) {
  8944. continue;
  8945. }
  8946. if (obs.mask & mask) {
  8947. if (obs.scope) {
  8948. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8949. }
  8950. else {
  8951. state.lastReturnValue = obs.callback(eventData, state);
  8952. }
  8953. if (obs.unregisterOnNextCall) {
  8954. this._deferUnregister(obs);
  8955. }
  8956. }
  8957. if (state.skipNextObservers) {
  8958. return false;
  8959. }
  8960. }
  8961. return true;
  8962. };
  8963. /**
  8964. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8965. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8966. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8967. * and it is crucial that all callbacks will be executed.
  8968. * The order of the callbacks is kept, callbacks are not executed parallel.
  8969. *
  8970. * @param eventData The data to be sent to each callback
  8971. * @param mask is used to filter observers defaults to -1
  8972. * @param target defines the callback target (see EventState)
  8973. * @param currentTarget defines he current object in the bubbling phase
  8974. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8975. */
  8976. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8977. var _this = this;
  8978. if (mask === void 0) { mask = -1; }
  8979. // create an empty promise
  8980. var p = Promise.resolve(eventData);
  8981. // no observers? return this promise.
  8982. if (!this._observers.length) {
  8983. return p;
  8984. }
  8985. var state = this._eventState;
  8986. state.mask = mask;
  8987. state.target = target;
  8988. state.currentTarget = currentTarget;
  8989. state.skipNextObservers = false;
  8990. // execute one callback after another (not using Promise.all, the order is important)
  8991. this._observers.forEach(function (obs) {
  8992. if (state.skipNextObservers) {
  8993. return;
  8994. }
  8995. if (obs._willBeUnregistered) {
  8996. return;
  8997. }
  8998. if (obs.mask & mask) {
  8999. if (obs.scope) {
  9000. p = p.then(function (lastReturnedValue) {
  9001. state.lastReturnValue = lastReturnedValue;
  9002. return obs.callback.apply(obs.scope, [eventData, state]);
  9003. });
  9004. }
  9005. else {
  9006. p = p.then(function (lastReturnedValue) {
  9007. state.lastReturnValue = lastReturnedValue;
  9008. return obs.callback(eventData, state);
  9009. });
  9010. }
  9011. if (obs.unregisterOnNextCall) {
  9012. _this._deferUnregister(obs);
  9013. }
  9014. }
  9015. });
  9016. // return the eventData
  9017. return p.then(function () { return eventData; });
  9018. };
  9019. /**
  9020. * Notify a specific observer
  9021. * @param observer defines the observer to notify
  9022. * @param eventData defines the data to be sent to each callback
  9023. * @param mask is used to filter observers defaults to -1
  9024. */
  9025. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  9026. if (mask === void 0) { mask = -1; }
  9027. var state = this._eventState;
  9028. state.mask = mask;
  9029. state.skipNextObservers = false;
  9030. observer.callback(eventData, state);
  9031. };
  9032. /**
  9033. * Gets a boolean indicating if the observable has at least one observer
  9034. * @returns true is the Observable has at least one Observer registered
  9035. */
  9036. Observable.prototype.hasObservers = function () {
  9037. return this._observers.length > 0;
  9038. };
  9039. /**
  9040. * Clear the list of observers
  9041. */
  9042. Observable.prototype.clear = function () {
  9043. this._observers = new Array();
  9044. this._onObserverAdded = null;
  9045. };
  9046. /**
  9047. * Clone the current observable
  9048. * @returns a new observable
  9049. */
  9050. Observable.prototype.clone = function () {
  9051. var result = new Observable();
  9052. result._observers = this._observers.slice(0);
  9053. return result;
  9054. };
  9055. /**
  9056. * Does this observable handles observer registered with a given mask
  9057. * @param mask defines the mask to be tested
  9058. * @return whether or not one observer registered with the given mask is handeled
  9059. **/
  9060. Observable.prototype.hasSpecificMask = function (mask) {
  9061. if (mask === void 0) { mask = -1; }
  9062. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  9063. var obs = _a[_i];
  9064. if (obs.mask & mask || obs.mask === mask) {
  9065. return true;
  9066. }
  9067. }
  9068. return false;
  9069. };
  9070. return Observable;
  9071. }());
  9072. BABYLON.Observable = Observable;
  9073. })(BABYLON || (BABYLON = {}));
  9074. //# sourceMappingURL=babylon.observable.js.map
  9075. var BABYLON;
  9076. (function (BABYLON) {
  9077. /**
  9078. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9079. */
  9080. var SmartArray = /** @class */ (function () {
  9081. /**
  9082. * Instantiates a Smart Array.
  9083. * @param capacity defines the default capacity of the array.
  9084. */
  9085. function SmartArray(capacity) {
  9086. /**
  9087. * The active length of the array.
  9088. */
  9089. this.length = 0;
  9090. this.data = new Array(capacity);
  9091. this._id = SmartArray._GlobalId++;
  9092. }
  9093. /**
  9094. * Pushes a value at the end of the active data.
  9095. * @param value defines the object to push in the array.
  9096. */
  9097. SmartArray.prototype.push = function (value) {
  9098. this.data[this.length++] = value;
  9099. if (this.length > this.data.length) {
  9100. this.data.length *= 2;
  9101. }
  9102. };
  9103. /**
  9104. * Iterates over the active data and apply the lambda to them.
  9105. * @param func defines the action to apply on each value.
  9106. */
  9107. SmartArray.prototype.forEach = function (func) {
  9108. for (var index = 0; index < this.length; index++) {
  9109. func(this.data[index]);
  9110. }
  9111. };
  9112. /**
  9113. * Sorts the full sets of data.
  9114. * @param compareFn defines the comparison function to apply.
  9115. */
  9116. SmartArray.prototype.sort = function (compareFn) {
  9117. this.data.sort(compareFn);
  9118. };
  9119. /**
  9120. * Resets the active data to an empty array.
  9121. */
  9122. SmartArray.prototype.reset = function () {
  9123. this.length = 0;
  9124. };
  9125. /**
  9126. * Releases all the data from the array as well as the array.
  9127. */
  9128. SmartArray.prototype.dispose = function () {
  9129. this.reset();
  9130. if (this.data) {
  9131. this.data.length = 0;
  9132. this.data = [];
  9133. }
  9134. };
  9135. /**
  9136. * Concats the active data with a given array.
  9137. * @param array defines the data to concatenate with.
  9138. */
  9139. SmartArray.prototype.concat = function (array) {
  9140. if (array.length === 0) {
  9141. return;
  9142. }
  9143. if (this.length + array.length > this.data.length) {
  9144. this.data.length = (this.length + array.length) * 2;
  9145. }
  9146. for (var index = 0; index < array.length; index++) {
  9147. this.data[this.length++] = (array.data || array)[index];
  9148. }
  9149. };
  9150. /**
  9151. * Returns the position of a value in the active data.
  9152. * @param value defines the value to find the index for
  9153. * @returns the index if found in the active data otherwise -1
  9154. */
  9155. SmartArray.prototype.indexOf = function (value) {
  9156. var position = this.data.indexOf(value);
  9157. if (position >= this.length) {
  9158. return -1;
  9159. }
  9160. return position;
  9161. };
  9162. /**
  9163. * Returns whether an element is part of the active data.
  9164. * @param value defines the value to look for
  9165. * @returns true if found in the active data otherwise false
  9166. */
  9167. SmartArray.prototype.contains = function (value) {
  9168. return this.indexOf(value) !== -1;
  9169. };
  9170. // Statics
  9171. SmartArray._GlobalId = 0;
  9172. return SmartArray;
  9173. }());
  9174. BABYLON.SmartArray = SmartArray;
  9175. /**
  9176. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9177. * The data in this array can only be present once
  9178. */
  9179. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9180. __extends(SmartArrayNoDuplicate, _super);
  9181. function SmartArrayNoDuplicate() {
  9182. var _this = _super !== null && _super.apply(this, arguments) || this;
  9183. _this._duplicateId = 0;
  9184. return _this;
  9185. }
  9186. /**
  9187. * Pushes a value at the end of the active data.
  9188. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9189. * @param value defines the object to push in the array.
  9190. */
  9191. SmartArrayNoDuplicate.prototype.push = function (value) {
  9192. _super.prototype.push.call(this, value);
  9193. if (!value.__smartArrayFlags) {
  9194. value.__smartArrayFlags = {};
  9195. }
  9196. value.__smartArrayFlags[this._id] = this._duplicateId;
  9197. };
  9198. /**
  9199. * Pushes a value at the end of the active data.
  9200. * If the data is already present, it won t be added again
  9201. * @param value defines the object to push in the array.
  9202. * @returns true if added false if it was already present
  9203. */
  9204. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9205. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9206. return false;
  9207. }
  9208. this.push(value);
  9209. return true;
  9210. };
  9211. /**
  9212. * Resets the active data to an empty array.
  9213. */
  9214. SmartArrayNoDuplicate.prototype.reset = function () {
  9215. _super.prototype.reset.call(this);
  9216. this._duplicateId++;
  9217. };
  9218. /**
  9219. * Concats the active data with a given array.
  9220. * This ensures no dupplicate will be present in the result.
  9221. * @param array defines the data to concatenate with.
  9222. */
  9223. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9224. if (array.length === 0) {
  9225. return;
  9226. }
  9227. if (this.length + array.length > this.data.length) {
  9228. this.data.length = (this.length + array.length) * 2;
  9229. }
  9230. for (var index = 0; index < array.length; index++) {
  9231. var item = (array.data || array)[index];
  9232. this.pushNoDuplicate(item);
  9233. }
  9234. };
  9235. return SmartArrayNoDuplicate;
  9236. }(SmartArray));
  9237. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9238. })(BABYLON || (BABYLON = {}));
  9239. //# sourceMappingURL=babylon.smartArray.js.map
  9240. var BABYLON;
  9241. (function (BABYLON) {
  9242. /** Class used to store color4 gradient */
  9243. var ColorGradient = /** @class */ (function () {
  9244. function ColorGradient() {
  9245. }
  9246. /**
  9247. * Will get a color picked randomly between color1 and color2.
  9248. * If color2 is undefined then color1 will be used
  9249. * @param result defines the target Color4 to store the result in
  9250. */
  9251. ColorGradient.prototype.getColorToRef = function (result) {
  9252. if (!this.color2) {
  9253. result.copyFrom(this.color1);
  9254. return;
  9255. }
  9256. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9257. };
  9258. return ColorGradient;
  9259. }());
  9260. BABYLON.ColorGradient = ColorGradient;
  9261. /** Class used to store color 3 gradient */
  9262. var Color3Gradient = /** @class */ (function () {
  9263. function Color3Gradient() {
  9264. }
  9265. return Color3Gradient;
  9266. }());
  9267. BABYLON.Color3Gradient = Color3Gradient;
  9268. /** Class used to store factor gradient */
  9269. var FactorGradient = /** @class */ (function () {
  9270. function FactorGradient() {
  9271. }
  9272. /**
  9273. * Will get a number picked randomly between factor1 and factor2.
  9274. * If factor2 is undefined then factor1 will be used
  9275. * @returns the picked number
  9276. */
  9277. FactorGradient.prototype.getFactor = function () {
  9278. if (this.factor2 === undefined) {
  9279. return this.factor1;
  9280. }
  9281. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9282. };
  9283. return FactorGradient;
  9284. }());
  9285. BABYLON.FactorGradient = FactorGradient;
  9286. /**
  9287. * @ignore
  9288. * Application error to support additional information when loading a file
  9289. */
  9290. var LoadFileError = /** @class */ (function (_super) {
  9291. __extends(LoadFileError, _super);
  9292. /**
  9293. * Creates a new LoadFileError
  9294. * @param message defines the message of the error
  9295. * @param request defines the optional XHR request
  9296. */
  9297. function LoadFileError(message,
  9298. /** defines the optional XHR request */
  9299. request) {
  9300. var _this = _super.call(this, message) || this;
  9301. _this.request = request;
  9302. _this.name = "LoadFileError";
  9303. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9304. return _this;
  9305. }
  9306. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9307. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9308. // Polyfill for Object.setPrototypeOf if necessary.
  9309. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9310. return LoadFileError;
  9311. }(Error));
  9312. BABYLON.LoadFileError = LoadFileError;
  9313. /**
  9314. * Class used to define a retry strategy when error happens while loading assets
  9315. */
  9316. var RetryStrategy = /** @class */ (function () {
  9317. function RetryStrategy() {
  9318. }
  9319. /**
  9320. * Function used to defines an exponential back off strategy
  9321. * @param maxRetries defines the maximum number of retries (3 by default)
  9322. * @param baseInterval defines the interval between retries
  9323. * @returns the strategy function to use
  9324. */
  9325. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9326. if (maxRetries === void 0) { maxRetries = 3; }
  9327. if (baseInterval === void 0) { baseInterval = 500; }
  9328. return function (url, request, retryIndex) {
  9329. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9330. return -1;
  9331. }
  9332. return Math.pow(2, retryIndex) * baseInterval;
  9333. };
  9334. };
  9335. return RetryStrategy;
  9336. }());
  9337. BABYLON.RetryStrategy = RetryStrategy;
  9338. // Screenshots
  9339. var screenshotCanvas;
  9340. var cloneValue = function (source, destinationObject) {
  9341. if (!source) {
  9342. return null;
  9343. }
  9344. if (source instanceof BABYLON.Mesh) {
  9345. return null;
  9346. }
  9347. if (source instanceof BABYLON.SubMesh) {
  9348. return source.clone(destinationObject);
  9349. }
  9350. else if (source.clone) {
  9351. return source.clone();
  9352. }
  9353. return null;
  9354. };
  9355. /**
  9356. * Class containing a set of static utilities functions
  9357. */
  9358. var Tools = /** @class */ (function () {
  9359. function Tools() {
  9360. }
  9361. /**
  9362. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9363. * @param u defines the coordinate on X axis
  9364. * @param v defines the coordinate on Y axis
  9365. * @param width defines the width of the source data
  9366. * @param height defines the height of the source data
  9367. * @param pixels defines the source byte array
  9368. * @param color defines the output color
  9369. */
  9370. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9371. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9372. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9373. var position = (wrappedU + wrappedV * width) * 4;
  9374. color.r = pixels[position] / 255;
  9375. color.g = pixels[position + 1] / 255;
  9376. color.b = pixels[position + 2] / 255;
  9377. color.a = pixels[position + 3] / 255;
  9378. };
  9379. /**
  9380. * Interpolates between a and b via alpha
  9381. * @param a The lower value (returned when alpha = 0)
  9382. * @param b The upper value (returned when alpha = 1)
  9383. * @param alpha The interpolation-factor
  9384. * @return The mixed value
  9385. */
  9386. Tools.Mix = function (a, b, alpha) {
  9387. return a * (1 - alpha) + b * alpha;
  9388. };
  9389. /**
  9390. * Tries to instantiate a new object from a given class name
  9391. * @param className defines the class name to instantiate
  9392. * @returns the new object or null if the system was not able to do the instantiation
  9393. */
  9394. Tools.Instantiate = function (className) {
  9395. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9396. return Tools.RegisteredExternalClasses[className];
  9397. }
  9398. var arr = className.split(".");
  9399. var fn = (window || this);
  9400. for (var i = 0, len = arr.length; i < len; i++) {
  9401. fn = fn[arr[i]];
  9402. }
  9403. if (typeof fn !== "function") {
  9404. return null;
  9405. }
  9406. return fn;
  9407. };
  9408. /**
  9409. * Provides a slice function that will work even on IE
  9410. * @param data defines the array to slice
  9411. * @param start defines the start of the data (optional)
  9412. * @param end defines the end of the data (optional)
  9413. * @returns the new sliced array
  9414. */
  9415. Tools.Slice = function (data, start, end) {
  9416. if (data.slice) {
  9417. return data.slice(start, end);
  9418. }
  9419. return Array.prototype.slice.call(data, start, end);
  9420. };
  9421. /**
  9422. * Polyfill for setImmediate
  9423. * @param action defines the action to execute after the current execution block
  9424. */
  9425. Tools.SetImmediate = function (action) {
  9426. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9427. window.setImmediate(action);
  9428. }
  9429. else {
  9430. setTimeout(action, 1);
  9431. }
  9432. };
  9433. /**
  9434. * Function indicating if a number is an exponent of 2
  9435. * @param value defines the value to test
  9436. * @returns true if the value is an exponent of 2
  9437. */
  9438. Tools.IsExponentOfTwo = function (value) {
  9439. var count = 1;
  9440. do {
  9441. count *= 2;
  9442. } while (count < value);
  9443. return count === value;
  9444. };
  9445. /**
  9446. * Returns the nearest 32-bit single precision float representation of a Number
  9447. * @param value A Number. If the parameter is of a different type, it will get converted
  9448. * to a number or to NaN if it cannot be converted
  9449. * @returns number
  9450. */
  9451. Tools.FloatRound = function (value) {
  9452. if (Math.fround) {
  9453. return Math.fround(value);
  9454. }
  9455. return (Tools._tmpFloatArray[0] = value);
  9456. };
  9457. /**
  9458. * Find the next highest power of two.
  9459. * @param x Number to start search from.
  9460. * @return Next highest power of two.
  9461. */
  9462. Tools.CeilingPOT = function (x) {
  9463. x--;
  9464. x |= x >> 1;
  9465. x |= x >> 2;
  9466. x |= x >> 4;
  9467. x |= x >> 8;
  9468. x |= x >> 16;
  9469. x++;
  9470. return x;
  9471. };
  9472. /**
  9473. * Find the next lowest power of two.
  9474. * @param x Number to start search from.
  9475. * @return Next lowest power of two.
  9476. */
  9477. Tools.FloorPOT = function (x) {
  9478. x = x | (x >> 1);
  9479. x = x | (x >> 2);
  9480. x = x | (x >> 4);
  9481. x = x | (x >> 8);
  9482. x = x | (x >> 16);
  9483. return x - (x >> 1);
  9484. };
  9485. /**
  9486. * Find the nearest power of two.
  9487. * @param x Number to start search from.
  9488. * @return Next nearest power of two.
  9489. */
  9490. Tools.NearestPOT = function (x) {
  9491. var c = Tools.CeilingPOT(x);
  9492. var f = Tools.FloorPOT(x);
  9493. return (c - x) > (x - f) ? f : c;
  9494. };
  9495. /**
  9496. * Get the closest exponent of two
  9497. * @param value defines the value to approximate
  9498. * @param max defines the maximum value to return
  9499. * @param mode defines how to define the closest value
  9500. * @returns closest exponent of two of the given value
  9501. */
  9502. Tools.GetExponentOfTwo = function (value, max, mode) {
  9503. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9504. var pot;
  9505. switch (mode) {
  9506. case BABYLON.Engine.SCALEMODE_FLOOR:
  9507. pot = Tools.FloorPOT(value);
  9508. break;
  9509. case BABYLON.Engine.SCALEMODE_NEAREST:
  9510. pot = Tools.NearestPOT(value);
  9511. break;
  9512. case BABYLON.Engine.SCALEMODE_CEILING:
  9513. default:
  9514. pot = Tools.CeilingPOT(value);
  9515. break;
  9516. }
  9517. return Math.min(pot, max);
  9518. };
  9519. /**
  9520. * Extracts the filename from a path
  9521. * @param path defines the path to use
  9522. * @returns the filename
  9523. */
  9524. Tools.GetFilename = function (path) {
  9525. var index = path.lastIndexOf("/");
  9526. if (index < 0) {
  9527. return path;
  9528. }
  9529. return path.substring(index + 1);
  9530. };
  9531. /**
  9532. * Extracts the "folder" part of a path (everything before the filename).
  9533. * @param uri The URI to extract the info from
  9534. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9535. * @returns The "folder" part of the path
  9536. */
  9537. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9538. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9539. var index = uri.lastIndexOf("/");
  9540. if (index < 0) {
  9541. if (returnUnchangedIfNoSlash) {
  9542. return uri;
  9543. }
  9544. return "";
  9545. }
  9546. return uri.substring(0, index + 1);
  9547. };
  9548. /**
  9549. * Extracts text content from a DOM element hierarchy
  9550. * @param element defines the root element
  9551. * @returns a string
  9552. */
  9553. Tools.GetDOMTextContent = function (element) {
  9554. var result = "";
  9555. var child = element.firstChild;
  9556. while (child) {
  9557. if (child.nodeType === 3) {
  9558. result += child.textContent;
  9559. }
  9560. child = child.nextSibling;
  9561. }
  9562. return result;
  9563. };
  9564. /**
  9565. * Convert an angle in radians to degrees
  9566. * @param angle defines the angle to convert
  9567. * @returns the angle in degrees
  9568. */
  9569. Tools.ToDegrees = function (angle) {
  9570. return angle * 180 / Math.PI;
  9571. };
  9572. /**
  9573. * Convert an angle in degrees to radians
  9574. * @param angle defines the angle to convert
  9575. * @returns the angle in radians
  9576. */
  9577. Tools.ToRadians = function (angle) {
  9578. return angle * Math.PI / 180;
  9579. };
  9580. /**
  9581. * Encode a buffer to a base64 string
  9582. * @param buffer defines the buffer to encode
  9583. * @returns the encoded string
  9584. */
  9585. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9586. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9587. var output = "";
  9588. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9589. var i = 0;
  9590. var bytes = new Uint8Array(buffer);
  9591. while (i < bytes.length) {
  9592. chr1 = bytes[i++];
  9593. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9594. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9595. enc1 = chr1 >> 2;
  9596. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9597. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9598. enc4 = chr3 & 63;
  9599. if (isNaN(chr2)) {
  9600. enc3 = enc4 = 64;
  9601. }
  9602. else if (isNaN(chr3)) {
  9603. enc4 = 64;
  9604. }
  9605. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9606. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9607. }
  9608. return "data:image/png;base64," + output;
  9609. };
  9610. /**
  9611. * Extracts minimum and maximum values from a list of indexed positions
  9612. * @param positions defines the positions to use
  9613. * @param indices defines the indices to the positions
  9614. * @param indexStart defines the start index
  9615. * @param indexCount defines the end index
  9616. * @param bias defines bias value to add to the result
  9617. * @return minimum and maximum values
  9618. */
  9619. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9620. if (bias === void 0) { bias = null; }
  9621. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9622. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9623. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9624. var offset = indices[index] * 3;
  9625. var x = positions[offset];
  9626. var y = positions[offset + 1];
  9627. var z = positions[offset + 2];
  9628. minimum.minimizeInPlaceFromFloats(x, y, z);
  9629. maximum.maximizeInPlaceFromFloats(x, y, z);
  9630. }
  9631. if (bias) {
  9632. minimum.x -= minimum.x * bias.x + bias.y;
  9633. minimum.y -= minimum.y * bias.x + bias.y;
  9634. minimum.z -= minimum.z * bias.x + bias.y;
  9635. maximum.x += maximum.x * bias.x + bias.y;
  9636. maximum.y += maximum.y * bias.x + bias.y;
  9637. maximum.z += maximum.z * bias.x + bias.y;
  9638. }
  9639. return {
  9640. minimum: minimum,
  9641. maximum: maximum
  9642. };
  9643. };
  9644. /**
  9645. * Extracts minimum and maximum values from a list of positions
  9646. * @param positions defines the positions to use
  9647. * @param start defines the start index in the positions array
  9648. * @param count defines the number of positions to handle
  9649. * @param bias defines bias value to add to the result
  9650. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9651. * @return minimum and maximum values
  9652. */
  9653. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9654. if (bias === void 0) { bias = null; }
  9655. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9656. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9657. if (!stride) {
  9658. stride = 3;
  9659. }
  9660. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9661. var x = positions[offset];
  9662. var y = positions[offset + 1];
  9663. var z = positions[offset + 2];
  9664. minimum.minimizeInPlaceFromFloats(x, y, z);
  9665. maximum.maximizeInPlaceFromFloats(x, y, z);
  9666. }
  9667. if (bias) {
  9668. minimum.x -= minimum.x * bias.x + bias.y;
  9669. minimum.y -= minimum.y * bias.x + bias.y;
  9670. minimum.z -= minimum.z * bias.x + bias.y;
  9671. maximum.x += maximum.x * bias.x + bias.y;
  9672. maximum.y += maximum.y * bias.x + bias.y;
  9673. maximum.z += maximum.z * bias.x + bias.y;
  9674. }
  9675. return {
  9676. minimum: minimum,
  9677. maximum: maximum
  9678. };
  9679. };
  9680. /**
  9681. * Returns an array if obj is not an array
  9682. * @param obj defines the object to evaluate as an array
  9683. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9684. * @returns either obj directly if obj is an array or a new array containing obj
  9685. */
  9686. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9687. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  9688. return null;
  9689. }
  9690. return Array.isArray(obj) ? obj : [obj];
  9691. };
  9692. /**
  9693. * Gets the pointer prefix to use
  9694. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9695. */
  9696. Tools.GetPointerPrefix = function () {
  9697. var eventPrefix = "pointer";
  9698. // Check if pointer events are supported
  9699. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9700. eventPrefix = "mouse";
  9701. }
  9702. return eventPrefix;
  9703. };
  9704. /**
  9705. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9706. * @param func - the function to be called
  9707. * @param requester - the object that will request the next frame. Falls back to window.
  9708. * @returns frame number
  9709. */
  9710. Tools.QueueNewFrame = function (func, requester) {
  9711. if (!Tools.IsWindowObjectExist()) {
  9712. return setTimeout(func, 16);
  9713. }
  9714. if (!requester) {
  9715. requester = window;
  9716. }
  9717. if (requester.requestAnimationFrame) {
  9718. return requester.requestAnimationFrame(func);
  9719. }
  9720. else if (requester.msRequestAnimationFrame) {
  9721. return requester.msRequestAnimationFrame(func);
  9722. }
  9723. else if (requester.webkitRequestAnimationFrame) {
  9724. return requester.webkitRequestAnimationFrame(func);
  9725. }
  9726. else if (requester.mozRequestAnimationFrame) {
  9727. return requester.mozRequestAnimationFrame(func);
  9728. }
  9729. else if (requester.oRequestAnimationFrame) {
  9730. return requester.oRequestAnimationFrame(func);
  9731. }
  9732. else {
  9733. return window.setTimeout(func, 16);
  9734. }
  9735. };
  9736. /**
  9737. * Ask the browser to promote the current element to fullscreen rendering mode
  9738. * @param element defines the DOM element to promote
  9739. */
  9740. Tools.RequestFullscreen = function (element) {
  9741. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9742. if (!requestFunction) {
  9743. return;
  9744. }
  9745. requestFunction.call(element);
  9746. };
  9747. /**
  9748. * Asks the browser to exit fullscreen mode
  9749. */
  9750. Tools.ExitFullscreen = function () {
  9751. if (document.exitFullscreen) {
  9752. document.exitFullscreen();
  9753. }
  9754. else if (document.mozCancelFullScreen) {
  9755. document.mozCancelFullScreen();
  9756. }
  9757. else if (document.webkitCancelFullScreen) {
  9758. document.webkitCancelFullScreen();
  9759. }
  9760. else if (document.msCancelFullScreen) {
  9761. document.msCancelFullScreen();
  9762. }
  9763. };
  9764. /**
  9765. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9766. * @param url define the url we are trying
  9767. * @param element define the dom element where to configure the cors policy
  9768. */
  9769. Tools.SetCorsBehavior = function (url, element) {
  9770. if (url && url.indexOf("data:") === 0) {
  9771. return;
  9772. }
  9773. if (Tools.CorsBehavior) {
  9774. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9775. element.crossOrigin = Tools.CorsBehavior;
  9776. }
  9777. else {
  9778. var result = Tools.CorsBehavior(url);
  9779. if (result) {
  9780. element.crossOrigin = result;
  9781. }
  9782. }
  9783. }
  9784. };
  9785. // External files
  9786. /**
  9787. * Removes unwanted characters from an url
  9788. * @param url defines the url to clean
  9789. * @returns the cleaned url
  9790. */
  9791. Tools.CleanUrl = function (url) {
  9792. url = url.replace(/#/mg, "%23");
  9793. return url;
  9794. };
  9795. /**
  9796. * Loads an image as an HTMLImageElement.
  9797. * @param input url string, ArrayBuffer, or Blob to load
  9798. * @param onLoad callback called when the image successfully loads
  9799. * @param onError callback called when the image fails to load
  9800. * @param database database for caching
  9801. * @returns the HTMLImageElement of the loaded image
  9802. */
  9803. Tools.LoadImage = function (input, onLoad, onError, database) {
  9804. var url;
  9805. var usingObjectURL = false;
  9806. if (input instanceof ArrayBuffer) {
  9807. url = URL.createObjectURL(new Blob([input]));
  9808. usingObjectURL = true;
  9809. }
  9810. else if (input instanceof Blob) {
  9811. url = URL.createObjectURL(input);
  9812. usingObjectURL = true;
  9813. }
  9814. else {
  9815. url = Tools.CleanUrl(input);
  9816. url = Tools.PreprocessUrl(input);
  9817. }
  9818. var img = new Image();
  9819. Tools.SetCorsBehavior(url, img);
  9820. var loadHandler = function () {
  9821. if (usingObjectURL && img.src) {
  9822. URL.revokeObjectURL(img.src);
  9823. }
  9824. img.removeEventListener("load", loadHandler);
  9825. img.removeEventListener("error", errorHandler);
  9826. onLoad(img);
  9827. };
  9828. var errorHandler = function (err) {
  9829. if (usingObjectURL && img.src) {
  9830. URL.revokeObjectURL(img.src);
  9831. }
  9832. img.removeEventListener("load", loadHandler);
  9833. img.removeEventListener("error", errorHandler);
  9834. Tools.Error("Error while trying to load image: " + input);
  9835. if (onError) {
  9836. onError("Error while trying to load image: " + input, err);
  9837. }
  9838. };
  9839. img.addEventListener("load", loadHandler);
  9840. img.addEventListener("error", errorHandler);
  9841. var noIndexedDB = function () {
  9842. img.src = url;
  9843. };
  9844. var loadFromIndexedDB = function () {
  9845. if (database) {
  9846. database.loadImageFromDB(url, img);
  9847. }
  9848. };
  9849. //ANY database to do!
  9850. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9851. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9852. }
  9853. else {
  9854. if (url.indexOf("file:") !== -1) {
  9855. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9856. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9857. try {
  9858. var blobURL;
  9859. try {
  9860. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9861. }
  9862. catch (ex) {
  9863. // Chrome doesn't support oneTimeOnly parameter
  9864. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9865. }
  9866. img.src = blobURL;
  9867. usingObjectURL = true;
  9868. }
  9869. catch (e) {
  9870. img.src = "";
  9871. }
  9872. return img;
  9873. }
  9874. }
  9875. noIndexedDB();
  9876. }
  9877. return img;
  9878. };
  9879. /**
  9880. * Loads a file
  9881. * @param url url string, ArrayBuffer, or Blob to load
  9882. * @param onSuccess callback called when the file successfully loads
  9883. * @param onProgress callback called while file is loading (if the server supports this mode)
  9884. * @param database database for caching
  9885. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9886. * @param onError callback called when the file fails to load
  9887. * @returns a file request object
  9888. */
  9889. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9890. url = Tools.CleanUrl(url);
  9891. url = Tools.PreprocessUrl(url);
  9892. // If file and file input are set
  9893. if (url.indexOf("file:") !== -1) {
  9894. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9895. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9896. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9897. }
  9898. }
  9899. var loadUrl = Tools.BaseUrl + url;
  9900. var aborted = false;
  9901. var fileRequest = {
  9902. onCompleteObservable: new BABYLON.Observable(),
  9903. abort: function () { return aborted = true; },
  9904. };
  9905. var requestFile = function () {
  9906. var request = new XMLHttpRequest();
  9907. var retryHandle = null;
  9908. fileRequest.abort = function () {
  9909. aborted = true;
  9910. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9911. request.abort();
  9912. }
  9913. if (retryHandle !== null) {
  9914. clearTimeout(retryHandle);
  9915. retryHandle = null;
  9916. }
  9917. };
  9918. var retryLoop = function (retryIndex) {
  9919. request.open('GET', loadUrl, true);
  9920. if (useArrayBuffer) {
  9921. request.responseType = "arraybuffer";
  9922. }
  9923. if (onProgress) {
  9924. request.addEventListener("progress", onProgress);
  9925. }
  9926. var onLoadEnd = function () {
  9927. request.removeEventListener("loadend", onLoadEnd);
  9928. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9929. fileRequest.onCompleteObservable.clear();
  9930. };
  9931. request.addEventListener("loadend", onLoadEnd);
  9932. var onReadyStateChange = function () {
  9933. if (aborted) {
  9934. return;
  9935. }
  9936. // In case of undefined state in some browsers.
  9937. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9938. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9939. request.removeEventListener("readystatechange", onReadyStateChange);
  9940. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9941. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9942. return;
  9943. }
  9944. var retryStrategy = Tools.DefaultRetryStrategy;
  9945. if (retryStrategy) {
  9946. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9947. if (waitTime !== -1) {
  9948. // Prevent the request from completing for retry.
  9949. request.removeEventListener("loadend", onLoadEnd);
  9950. request = new XMLHttpRequest();
  9951. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9952. return;
  9953. }
  9954. }
  9955. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9956. if (onError) {
  9957. onError(request, e);
  9958. }
  9959. else {
  9960. throw e;
  9961. }
  9962. }
  9963. };
  9964. request.addEventListener("readystatechange", onReadyStateChange);
  9965. request.send();
  9966. };
  9967. retryLoop(0);
  9968. };
  9969. // Caching all files
  9970. if (database && database.enableSceneOffline) {
  9971. var noIndexedDB_1 = function (request) {
  9972. if (request && request.status > 400) {
  9973. if (onError) {
  9974. onError(request);
  9975. }
  9976. }
  9977. else {
  9978. if (!aborted) {
  9979. requestFile();
  9980. }
  9981. }
  9982. };
  9983. var loadFromIndexedDB = function () {
  9984. // TODO: database needs to support aborting and should return a IFileRequest
  9985. if (aborted) {
  9986. return;
  9987. }
  9988. if (database) {
  9989. database.loadFileFromDB(url, function (data) {
  9990. if (!aborted) {
  9991. onSuccess(data);
  9992. }
  9993. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9994. }, onProgress ? function (event) {
  9995. if (!aborted) {
  9996. onProgress(event);
  9997. }
  9998. } : undefined, noIndexedDB_1, useArrayBuffer);
  9999. }
  10000. };
  10001. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  10002. }
  10003. else {
  10004. requestFile();
  10005. }
  10006. return fileRequest;
  10007. };
  10008. /**
  10009. * Load a script (identified by an url). When the url returns, the
  10010. * content of this file is added into a new script element, attached to the DOM (body element)
  10011. * @param scriptUrl defines the url of the script to laod
  10012. * @param onSuccess defines the callback called when the script is loaded
  10013. * @param onError defines the callback to call if an error occurs
  10014. */
  10015. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  10016. if (!Tools.IsWindowObjectExist()) {
  10017. return;
  10018. }
  10019. var head = document.getElementsByTagName('head')[0];
  10020. var script = document.createElement('script');
  10021. script.type = 'text/javascript';
  10022. script.src = scriptUrl;
  10023. script.onload = function () {
  10024. if (onSuccess) {
  10025. onSuccess();
  10026. }
  10027. };
  10028. script.onerror = function (e) {
  10029. if (onError) {
  10030. onError("Unable to load script '" + scriptUrl + "'", e);
  10031. }
  10032. };
  10033. head.appendChild(script);
  10034. };
  10035. /**
  10036. * Loads a file from a blob
  10037. * @param fileToLoad defines the blob to use
  10038. * @param callback defines the callback to call when data is loaded
  10039. * @param progressCallback defines the callback to call during loading process
  10040. * @returns a file request object
  10041. */
  10042. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  10043. var reader = new FileReader();
  10044. var request = {
  10045. onCompleteObservable: new BABYLON.Observable(),
  10046. abort: function () { return reader.abort(); },
  10047. };
  10048. reader.onloadend = function (e) {
  10049. request.onCompleteObservable.notifyObservers(request);
  10050. };
  10051. reader.onload = function (e) {
  10052. //target doesn't have result from ts 1.3
  10053. callback(e.target['result']);
  10054. };
  10055. reader.onprogress = progressCallback;
  10056. reader.readAsDataURL(fileToLoad);
  10057. return request;
  10058. };
  10059. /**
  10060. * Loads a file
  10061. * @param fileToLoad defines the file to load
  10062. * @param callback defines the callback to call when data is loaded
  10063. * @param progressCallBack defines the callback to call during loading process
  10064. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  10065. * @returns a file request object
  10066. */
  10067. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  10068. var reader = new FileReader();
  10069. var request = {
  10070. onCompleteObservable: new BABYLON.Observable(),
  10071. abort: function () { return reader.abort(); },
  10072. };
  10073. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  10074. reader.onerror = function (e) {
  10075. Tools.Log("Error while reading file: " + fileToLoad.name);
  10076. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  10077. };
  10078. reader.onload = function (e) {
  10079. //target doesn't have result from ts 1.3
  10080. callback(e.target['result']);
  10081. };
  10082. if (progressCallBack) {
  10083. reader.onprogress = progressCallBack;
  10084. }
  10085. if (!useArrayBuffer) {
  10086. // Asynchronous read
  10087. reader.readAsText(fileToLoad);
  10088. }
  10089. else {
  10090. reader.readAsArrayBuffer(fileToLoad);
  10091. }
  10092. return request;
  10093. };
  10094. /**
  10095. * Creates a data url from a given string content
  10096. * @param content defines the content to convert
  10097. * @returns the new data url link
  10098. */
  10099. Tools.FileAsURL = function (content) {
  10100. var fileBlob = new Blob([content]);
  10101. var url = window.URL || window.webkitURL;
  10102. var link = url.createObjectURL(fileBlob);
  10103. return link;
  10104. };
  10105. /**
  10106. * Format the given number to a specific decimal format
  10107. * @param value defines the number to format
  10108. * @param decimals defines the number of decimals to use
  10109. * @returns the formatted string
  10110. */
  10111. Tools.Format = function (value, decimals) {
  10112. if (decimals === void 0) { decimals = 2; }
  10113. return value.toFixed(decimals);
  10114. };
  10115. /**
  10116. * Checks if a given vector is inside a specific range
  10117. * @param v defines the vector to test
  10118. * @param min defines the minimum range
  10119. * @param max defines the maximum range
  10120. */
  10121. Tools.CheckExtends = function (v, min, max) {
  10122. if (v.x < min.x) {
  10123. min.x = v.x;
  10124. }
  10125. if (v.y < min.y) {
  10126. min.y = v.y;
  10127. }
  10128. if (v.z < min.z) {
  10129. min.z = v.z;
  10130. }
  10131. if (v.x > max.x) {
  10132. max.x = v.x;
  10133. }
  10134. if (v.y > max.y) {
  10135. max.y = v.y;
  10136. }
  10137. if (v.z > max.z) {
  10138. max.z = v.z;
  10139. }
  10140. };
  10141. /**
  10142. * Tries to copy an object by duplicating every property
  10143. * @param source defines the source object
  10144. * @param destination defines the target object
  10145. * @param doNotCopyList defines a list of properties to avoid
  10146. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  10147. */
  10148. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10149. for (var prop in source) {
  10150. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10151. continue;
  10152. }
  10153. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10154. continue;
  10155. }
  10156. var sourceValue = source[prop];
  10157. var typeOfSourceValue = typeof sourceValue;
  10158. if (typeOfSourceValue === "function") {
  10159. continue;
  10160. }
  10161. try {
  10162. if (typeOfSourceValue === "object") {
  10163. if (sourceValue instanceof Array) {
  10164. destination[prop] = [];
  10165. if (sourceValue.length > 0) {
  10166. if (typeof sourceValue[0] == "object") {
  10167. for (var index = 0; index < sourceValue.length; index++) {
  10168. var clonedValue = cloneValue(sourceValue[index], destination);
  10169. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10170. destination[prop].push(clonedValue);
  10171. }
  10172. }
  10173. }
  10174. else {
  10175. destination[prop] = sourceValue.slice(0);
  10176. }
  10177. }
  10178. }
  10179. else {
  10180. destination[prop] = cloneValue(sourceValue, destination);
  10181. }
  10182. }
  10183. else {
  10184. destination[prop] = sourceValue;
  10185. }
  10186. }
  10187. catch (e) {
  10188. // Just ignore error (it could be because of a read-only property)
  10189. }
  10190. }
  10191. };
  10192. /**
  10193. * Gets a boolean indicating if the given object has no own property
  10194. * @param obj defines the object to test
  10195. * @returns true if object has no own property
  10196. */
  10197. Tools.IsEmpty = function (obj) {
  10198. for (var i in obj) {
  10199. if (obj.hasOwnProperty(i)) {
  10200. return false;
  10201. }
  10202. }
  10203. return true;
  10204. };
  10205. /**
  10206. * Function used to register events at window level
  10207. * @param events defines the events to register
  10208. */
  10209. Tools.RegisterTopRootEvents = function (events) {
  10210. for (var index = 0; index < events.length; index++) {
  10211. var event = events[index];
  10212. window.addEventListener(event.name, event.handler, false);
  10213. try {
  10214. if (window.parent) {
  10215. window.parent.addEventListener(event.name, event.handler, false);
  10216. }
  10217. }
  10218. catch (e) {
  10219. // Silently fails...
  10220. }
  10221. }
  10222. };
  10223. /**
  10224. * Function used to unregister events from window level
  10225. * @param events defines the events to unregister
  10226. */
  10227. Tools.UnregisterTopRootEvents = function (events) {
  10228. for (var index = 0; index < events.length; index++) {
  10229. var event = events[index];
  10230. window.removeEventListener(event.name, event.handler);
  10231. try {
  10232. if (window.parent) {
  10233. window.parent.removeEventListener(event.name, event.handler);
  10234. }
  10235. }
  10236. catch (e) {
  10237. // Silently fails...
  10238. }
  10239. }
  10240. };
  10241. /**
  10242. * Dumps the current bound framebuffer
  10243. * @param width defines the rendering width
  10244. * @param height defines the rendering height
  10245. * @param engine defines the hosting engine
  10246. * @param successCallback defines the callback triggered once the data are available
  10247. * @param mimeType defines the mime type of the result
  10248. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10249. */
  10250. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10251. if (mimeType === void 0) { mimeType = "image/png"; }
  10252. // Read the contents of the framebuffer
  10253. var numberOfChannelsByLine = width * 4;
  10254. var halfHeight = height / 2;
  10255. //Reading datas from WebGL
  10256. var data = engine.readPixels(0, 0, width, height);
  10257. //To flip image on Y axis.
  10258. for (var i = 0; i < halfHeight; i++) {
  10259. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10260. var currentCell = j + i * numberOfChannelsByLine;
  10261. var targetLine = height - i - 1;
  10262. var targetCell = j + targetLine * numberOfChannelsByLine;
  10263. var temp = data[currentCell];
  10264. data[currentCell] = data[targetCell];
  10265. data[targetCell] = temp;
  10266. }
  10267. }
  10268. // Create a 2D canvas to store the result
  10269. if (!screenshotCanvas) {
  10270. screenshotCanvas = document.createElement('canvas');
  10271. }
  10272. screenshotCanvas.width = width;
  10273. screenshotCanvas.height = height;
  10274. var context = screenshotCanvas.getContext('2d');
  10275. if (context) {
  10276. // Copy the pixels to a 2D canvas
  10277. var imageData = context.createImageData(width, height);
  10278. var castData = (imageData.data);
  10279. castData.set(data);
  10280. context.putImageData(imageData, 0, 0);
  10281. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10282. }
  10283. };
  10284. /**
  10285. * Converts the canvas data to blob.
  10286. * This acts as a polyfill for browsers not supporting the to blob function.
  10287. * @param canvas Defines the canvas to extract the data from
  10288. * @param successCallback Defines the callback triggered once the data are available
  10289. * @param mimeType Defines the mime type of the result
  10290. */
  10291. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10292. if (mimeType === void 0) { mimeType = "image/png"; }
  10293. // We need HTMLCanvasElement.toBlob for HD screenshots
  10294. if (!canvas.toBlob) {
  10295. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10296. canvas.toBlob = function (callback, type, quality) {
  10297. var _this = this;
  10298. setTimeout(function () {
  10299. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10300. for (var i = 0; i < len; i++) {
  10301. arr[i] = binStr.charCodeAt(i);
  10302. }
  10303. callback(new Blob([arr]));
  10304. });
  10305. };
  10306. }
  10307. canvas.toBlob(function (blob) {
  10308. successCallback(blob);
  10309. }, mimeType);
  10310. };
  10311. /**
  10312. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10313. * @param successCallback defines the callback triggered once the data are available
  10314. * @param mimeType defines the mime type of the result
  10315. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10316. */
  10317. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10318. if (mimeType === void 0) { mimeType = "image/png"; }
  10319. if (successCallback) {
  10320. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10321. successCallback(base64Image);
  10322. }
  10323. else {
  10324. this.ToBlob(screenshotCanvas, function (blob) {
  10325. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10326. if (("download" in document.createElement("a"))) {
  10327. if (!fileName) {
  10328. var date = new Date();
  10329. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10330. fileName = "screenshot_" + stringDate + ".png";
  10331. }
  10332. Tools.Download(blob, fileName);
  10333. }
  10334. else {
  10335. var url = URL.createObjectURL(blob);
  10336. var newWindow = window.open("");
  10337. if (!newWindow) {
  10338. return;
  10339. }
  10340. var img = newWindow.document.createElement("img");
  10341. img.onload = function () {
  10342. // no longer need to read the blob so it's revoked
  10343. URL.revokeObjectURL(url);
  10344. };
  10345. img.src = url;
  10346. newWindow.document.body.appendChild(img);
  10347. }
  10348. }, mimeType);
  10349. }
  10350. };
  10351. /**
  10352. * Downloads a blob in the browser
  10353. * @param blob defines the blob to download
  10354. * @param fileName defines the name of the downloaded file
  10355. */
  10356. Tools.Download = function (blob, fileName) {
  10357. if (navigator && navigator.msSaveBlob) {
  10358. navigator.msSaveBlob(blob, fileName);
  10359. return;
  10360. }
  10361. var url = window.URL.createObjectURL(blob);
  10362. var a = document.createElement("a");
  10363. document.body.appendChild(a);
  10364. a.style.display = "none";
  10365. a.href = url;
  10366. a.download = fileName;
  10367. a.addEventListener("click", function () {
  10368. if (a.parentElement) {
  10369. a.parentElement.removeChild(a);
  10370. }
  10371. });
  10372. a.click();
  10373. window.URL.revokeObjectURL(url);
  10374. };
  10375. /**
  10376. * Captures a screenshot of the current rendering
  10377. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10378. * @param engine defines the rendering engine
  10379. * @param camera defines the source camera
  10380. * @param size This parameter can be set to a single number or to an object with the
  10381. * following (optional) properties: precision, width, height. If a single number is passed,
  10382. * it will be used for both width and height. If an object is passed, the screenshot size
  10383. * will be derived from the parameters. The precision property is a multiplier allowing
  10384. * rendering at a higher or lower resolution
  10385. * @param successCallback defines the callback receives a single parameter which contains the
  10386. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10387. * src parameter of an <img> to display it
  10388. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10389. * Check your browser for supported MIME types
  10390. */
  10391. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10392. if (mimeType === void 0) { mimeType = "image/png"; }
  10393. var width;
  10394. var height;
  10395. // If a precision value is specified
  10396. if (size.precision) {
  10397. width = Math.round(engine.getRenderWidth() * size.precision);
  10398. height = Math.round(width / engine.getAspectRatio(camera));
  10399. }
  10400. else if (size.width && size.height) {
  10401. width = size.width;
  10402. height = size.height;
  10403. }
  10404. //If passing only width, computing height to keep display canvas ratio.
  10405. else if (size.width && !size.height) {
  10406. width = size.width;
  10407. height = Math.round(width / engine.getAspectRatio(camera));
  10408. }
  10409. //If passing only height, computing width to keep display canvas ratio.
  10410. else if (size.height && !size.width) {
  10411. height = size.height;
  10412. width = Math.round(height * engine.getAspectRatio(camera));
  10413. }
  10414. //Assuming here that "size" parameter is a number
  10415. else if (!isNaN(size)) {
  10416. height = size;
  10417. width = size;
  10418. }
  10419. else {
  10420. Tools.Error("Invalid 'size' parameter !");
  10421. return;
  10422. }
  10423. if (!screenshotCanvas) {
  10424. screenshotCanvas = document.createElement('canvas');
  10425. }
  10426. screenshotCanvas.width = width;
  10427. screenshotCanvas.height = height;
  10428. var renderContext = screenshotCanvas.getContext("2d");
  10429. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10430. var newWidth = width;
  10431. var newHeight = newWidth / ratio;
  10432. if (newHeight > height) {
  10433. newHeight = height;
  10434. newWidth = newHeight * ratio;
  10435. }
  10436. var offsetX = Math.max(0, width - newWidth) / 2;
  10437. var offsetY = Math.max(0, height - newHeight) / 2;
  10438. var renderingCanvas = engine.getRenderingCanvas();
  10439. if (renderContext && renderingCanvas) {
  10440. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10441. }
  10442. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10443. };
  10444. /**
  10445. * Generates an image screenshot from the specified camera.
  10446. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10447. * @param engine The engine to use for rendering
  10448. * @param camera The camera to use for rendering
  10449. * @param size This parameter can be set to a single number or to an object with the
  10450. * following (optional) properties: precision, width, height. If a single number is passed,
  10451. * it will be used for both width and height. If an object is passed, the screenshot size
  10452. * will be derived from the parameters. The precision property is a multiplier allowing
  10453. * rendering at a higher or lower resolution
  10454. * @param successCallback The callback receives a single parameter which contains the
  10455. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10456. * src parameter of an <img> to display it
  10457. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10458. * Check your browser for supported MIME types
  10459. * @param samples Texture samples (default: 1)
  10460. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10461. * @param fileName A name for for the downloaded file.
  10462. */
  10463. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10464. if (mimeType === void 0) { mimeType = "image/png"; }
  10465. if (samples === void 0) { samples = 1; }
  10466. if (antialiasing === void 0) { antialiasing = false; }
  10467. var width;
  10468. var height;
  10469. //If a precision value is specified
  10470. if (size.precision) {
  10471. width = Math.round(engine.getRenderWidth() * size.precision);
  10472. height = Math.round(width / engine.getAspectRatio(camera));
  10473. size = { width: width, height: height };
  10474. }
  10475. else if (size.width && size.height) {
  10476. width = size.width;
  10477. height = size.height;
  10478. }
  10479. //If passing only width, computing height to keep display canvas ratio.
  10480. else if (size.width && !size.height) {
  10481. width = size.width;
  10482. height = Math.round(width / engine.getAspectRatio(camera));
  10483. size = { width: width, height: height };
  10484. }
  10485. //If passing only height, computing width to keep display canvas ratio.
  10486. else if (size.height && !size.width) {
  10487. height = size.height;
  10488. width = Math.round(height * engine.getAspectRatio(camera));
  10489. size = { width: width, height: height };
  10490. }
  10491. //Assuming here that "size" parameter is a number
  10492. else if (!isNaN(size)) {
  10493. height = size;
  10494. width = size;
  10495. }
  10496. else {
  10497. Tools.Error("Invalid 'size' parameter !");
  10498. return;
  10499. }
  10500. var scene = camera.getScene();
  10501. var previousCamera = null;
  10502. if (scene.activeCamera !== camera) {
  10503. previousCamera = scene.activeCamera;
  10504. scene.activeCamera = camera;
  10505. }
  10506. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10507. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10508. texture.renderList = null;
  10509. texture.samples = samples;
  10510. if (antialiasing) {
  10511. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10512. }
  10513. texture.onAfterRenderObservable.add(function () {
  10514. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10515. });
  10516. scene.incrementRenderId();
  10517. scene.resetCachedMaterial();
  10518. texture.render(true);
  10519. texture.dispose();
  10520. if (previousCamera) {
  10521. scene.activeCamera = previousCamera;
  10522. }
  10523. camera.getProjectionMatrix(true); // Force cache refresh;
  10524. };
  10525. /**
  10526. * Validates if xhr data is correct
  10527. * @param xhr defines the request to validate
  10528. * @param dataType defines the expected data type
  10529. * @returns true if data is correct
  10530. */
  10531. Tools.ValidateXHRData = function (xhr, dataType) {
  10532. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10533. if (dataType === void 0) { dataType = 7; }
  10534. try {
  10535. if (dataType & 1) {
  10536. if (xhr.responseText && xhr.responseText.length > 0) {
  10537. return true;
  10538. }
  10539. else if (dataType === 1) {
  10540. return false;
  10541. }
  10542. }
  10543. if (dataType & 2) {
  10544. // Check header width and height since there is no "TGA" magic number
  10545. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10546. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10547. return true;
  10548. }
  10549. else if (dataType === 2) {
  10550. return false;
  10551. }
  10552. }
  10553. if (dataType & 4) {
  10554. // Check for the "DDS" magic number
  10555. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10556. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10557. return true;
  10558. }
  10559. else {
  10560. return false;
  10561. }
  10562. }
  10563. }
  10564. catch (e) {
  10565. // Global protection
  10566. }
  10567. return false;
  10568. };
  10569. /**
  10570. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10571. * Be aware Math.random() could cause collisions, but:
  10572. * "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"
  10573. * @returns a pseudo random id
  10574. */
  10575. Tools.RandomId = function () {
  10576. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10577. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10578. return v.toString(16);
  10579. });
  10580. };
  10581. /**
  10582. * Test if the given uri is a base64 string
  10583. * @param uri The uri to test
  10584. * @return True if the uri is a base64 string or false otherwise
  10585. */
  10586. Tools.IsBase64 = function (uri) {
  10587. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10588. };
  10589. /**
  10590. * Decode the given base64 uri.
  10591. * @param uri The uri to decode
  10592. * @return The decoded base64 data.
  10593. */
  10594. Tools.DecodeBase64 = function (uri) {
  10595. var decodedString = atob(uri.split(",")[1]);
  10596. var bufferLength = decodedString.length;
  10597. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10598. for (var i = 0; i < bufferLength; i++) {
  10599. bufferView[i] = decodedString.charCodeAt(i);
  10600. }
  10601. return bufferView.buffer;
  10602. };
  10603. Tools._AddLogEntry = function (entry) {
  10604. Tools._LogCache = entry + Tools._LogCache;
  10605. if (Tools.OnNewCacheEntry) {
  10606. Tools.OnNewCacheEntry(entry);
  10607. }
  10608. };
  10609. Tools._FormatMessage = function (message) {
  10610. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10611. var date = new Date();
  10612. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10613. };
  10614. Tools._LogDisabled = function (message) {
  10615. // nothing to do
  10616. };
  10617. Tools._LogEnabled = function (message) {
  10618. var formattedMessage = Tools._FormatMessage(message);
  10619. console.log("BJS - " + formattedMessage);
  10620. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10621. Tools._AddLogEntry(entry);
  10622. };
  10623. Tools._WarnDisabled = function (message) {
  10624. // nothing to do
  10625. };
  10626. Tools._WarnEnabled = function (message) {
  10627. var formattedMessage = Tools._FormatMessage(message);
  10628. console.warn("BJS - " + formattedMessage);
  10629. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10630. Tools._AddLogEntry(entry);
  10631. };
  10632. Tools._ErrorDisabled = function (message) {
  10633. // nothing to do
  10634. };
  10635. Tools._ErrorEnabled = function (message) {
  10636. Tools.errorsCount++;
  10637. var formattedMessage = Tools._FormatMessage(message);
  10638. console.error("BJS - " + formattedMessage);
  10639. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10640. Tools._AddLogEntry(entry);
  10641. };
  10642. Object.defineProperty(Tools, "LogCache", {
  10643. /**
  10644. * Gets current log cache (list of logs)
  10645. */
  10646. get: function () {
  10647. return Tools._LogCache;
  10648. },
  10649. enumerable: true,
  10650. configurable: true
  10651. });
  10652. /**
  10653. * Clears the log cache
  10654. */
  10655. Tools.ClearLogCache = function () {
  10656. Tools._LogCache = "";
  10657. Tools.errorsCount = 0;
  10658. };
  10659. Object.defineProperty(Tools, "LogLevels", {
  10660. /**
  10661. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10662. */
  10663. set: function (level) {
  10664. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10665. Tools.Log = Tools._LogEnabled;
  10666. }
  10667. else {
  10668. Tools.Log = Tools._LogDisabled;
  10669. }
  10670. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10671. Tools.Warn = Tools._WarnEnabled;
  10672. }
  10673. else {
  10674. Tools.Warn = Tools._WarnDisabled;
  10675. }
  10676. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10677. Tools.Error = Tools._ErrorEnabled;
  10678. }
  10679. else {
  10680. Tools.Error = Tools._ErrorDisabled;
  10681. }
  10682. },
  10683. enumerable: true,
  10684. configurable: true
  10685. });
  10686. /**
  10687. * Checks if the loaded document was accessed via `file:`-Protocol.
  10688. * @returns boolean
  10689. */
  10690. Tools.IsFileURL = function () {
  10691. return location.protocol === "file:";
  10692. };
  10693. /**
  10694. * Checks if the window object exists
  10695. * @returns true if the window object exists
  10696. */
  10697. Tools.IsWindowObjectExist = function () {
  10698. return (typeof window) !== "undefined";
  10699. };
  10700. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10701. /**
  10702. * Sets the current performance log level
  10703. */
  10704. set: function (level) {
  10705. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10706. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10707. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10708. return;
  10709. }
  10710. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10711. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10712. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10713. return;
  10714. }
  10715. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10716. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10722. };
  10723. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10724. };
  10725. Tools._StartUserMark = function (counterName, condition) {
  10726. if (condition === void 0) { condition = true; }
  10727. if (!Tools._performance) {
  10728. if (!Tools.IsWindowObjectExist()) {
  10729. return;
  10730. }
  10731. Tools._performance = window.performance;
  10732. }
  10733. if (!condition || !Tools._performance.mark) {
  10734. return;
  10735. }
  10736. Tools._performance.mark(counterName + "-Begin");
  10737. };
  10738. Tools._EndUserMark = function (counterName, condition) {
  10739. if (condition === void 0) { condition = true; }
  10740. if (!condition || !Tools._performance.mark) {
  10741. return;
  10742. }
  10743. Tools._performance.mark(counterName + "-End");
  10744. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10745. };
  10746. Tools._StartPerformanceConsole = function (counterName, condition) {
  10747. if (condition === void 0) { condition = true; }
  10748. if (!condition) {
  10749. return;
  10750. }
  10751. Tools._StartUserMark(counterName, condition);
  10752. if (console.time) {
  10753. console.time(counterName);
  10754. }
  10755. };
  10756. Tools._EndPerformanceConsole = function (counterName, condition) {
  10757. if (condition === void 0) { condition = true; }
  10758. if (!condition) {
  10759. return;
  10760. }
  10761. Tools._EndUserMark(counterName, condition);
  10762. if (console.time) {
  10763. console.timeEnd(counterName);
  10764. }
  10765. };
  10766. Object.defineProperty(Tools, "Now", {
  10767. /**
  10768. * Gets either window.performance.now() if supported or Date.now() else
  10769. */
  10770. get: function () {
  10771. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10772. return window.performance.now();
  10773. }
  10774. return Date.now();
  10775. },
  10776. enumerable: true,
  10777. configurable: true
  10778. });
  10779. /**
  10780. * This method will return the name of the class used to create the instance of the given object.
  10781. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10782. * @param object the object to get the class name from
  10783. * @param isType defines if the object is actually a type
  10784. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10785. */
  10786. Tools.GetClassName = function (object, isType) {
  10787. if (isType === void 0) { isType = false; }
  10788. var name = null;
  10789. if (!isType && object.getClassName) {
  10790. name = object.getClassName();
  10791. }
  10792. else {
  10793. if (object instanceof Object) {
  10794. var classObj = isType ? object : Object.getPrototypeOf(object);
  10795. name = classObj.constructor["__bjsclassName__"];
  10796. }
  10797. if (!name) {
  10798. name = typeof object;
  10799. }
  10800. }
  10801. return name;
  10802. };
  10803. /**
  10804. * Gets the first element of an array satisfying a given predicate
  10805. * @param array defines the array to browse
  10806. * @param predicate defines the predicate to use
  10807. * @returns null if not found or the element
  10808. */
  10809. Tools.First = function (array, predicate) {
  10810. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10811. var el = array_1[_i];
  10812. if (predicate(el)) {
  10813. return el;
  10814. }
  10815. }
  10816. return null;
  10817. };
  10818. /**
  10819. * This method will return the name of the full name of the class, including its owning module (if any).
  10820. * 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).
  10821. * @param object the object to get the class name from
  10822. * @param isType defines if the object is actually a type
  10823. * @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.
  10824. * @ignorenaming
  10825. */
  10826. Tools.getFullClassName = function (object, isType) {
  10827. if (isType === void 0) { isType = false; }
  10828. var className = null;
  10829. var moduleName = null;
  10830. if (!isType && object.getClassName) {
  10831. className = object.getClassName();
  10832. }
  10833. else {
  10834. if (object instanceof Object) {
  10835. var classObj = isType ? object : Object.getPrototypeOf(object);
  10836. className = classObj.constructor["__bjsclassName__"];
  10837. moduleName = classObj.constructor["__bjsmoduleName__"];
  10838. }
  10839. if (!className) {
  10840. className = typeof object;
  10841. }
  10842. }
  10843. if (!className) {
  10844. return null;
  10845. }
  10846. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10847. };
  10848. /**
  10849. * Returns a promise that resolves after the given amount of time.
  10850. * @param delay Number of milliseconds to delay
  10851. * @returns Promise that resolves after the given amount of time
  10852. */
  10853. Tools.DelayAsync = function (delay) {
  10854. return new Promise(function (resolve) {
  10855. setTimeout(function () {
  10856. resolve();
  10857. }, delay);
  10858. });
  10859. };
  10860. /**
  10861. * Gets the current gradient from an array of IValueGradient
  10862. * @param ratio defines the current ratio to get
  10863. * @param gradients defines the array of IValueGradient
  10864. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10865. */
  10866. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10867. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10868. var currentGradient = gradients[gradientIndex];
  10869. var nextGradient = gradients[gradientIndex + 1];
  10870. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10871. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10872. updateFunc(currentGradient, nextGradient, scale);
  10873. return;
  10874. }
  10875. }
  10876. // Use last index if over
  10877. var lastIndex = gradients.length - 1;
  10878. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10879. };
  10880. /**
  10881. * Gets or sets the base URL to use to load assets
  10882. */
  10883. Tools.BaseUrl = "";
  10884. /**
  10885. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10886. */
  10887. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10888. /**
  10889. * Default behaviour for cors in the application.
  10890. * It can be a string if the expected behavior is identical in the entire app.
  10891. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10892. */
  10893. Tools.CorsBehavior = "anonymous";
  10894. /**
  10895. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10896. * @ignorenaming
  10897. */
  10898. Tools.UseFallbackTexture = true;
  10899. /**
  10900. * Use this object to register external classes like custom textures or material
  10901. * to allow the laoders to instantiate them
  10902. */
  10903. Tools.RegisteredExternalClasses = {};
  10904. /**
  10905. * Texture content used if a texture cannot loaded
  10906. * @ignorenaming
  10907. */
  10908. 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";
  10909. Tools._tmpFloatArray = new Float32Array(1);
  10910. /**
  10911. * Gets or sets a function used to pre-process url before using them to load assets
  10912. */
  10913. Tools.PreprocessUrl = function (url) {
  10914. return url;
  10915. };
  10916. // Logs
  10917. /**
  10918. * No log
  10919. */
  10920. Tools.NoneLogLevel = 0;
  10921. /**
  10922. * Only message logs
  10923. */
  10924. Tools.MessageLogLevel = 1;
  10925. /**
  10926. * Only warning logs
  10927. */
  10928. Tools.WarningLogLevel = 2;
  10929. /**
  10930. * Only error logs
  10931. */
  10932. Tools.ErrorLogLevel = 4;
  10933. /**
  10934. * All logs
  10935. */
  10936. Tools.AllLogLevel = 7;
  10937. Tools._LogCache = "";
  10938. /**
  10939. * Gets a value indicating the number of loading errors
  10940. * @ignorenaming
  10941. */
  10942. Tools.errorsCount = 0;
  10943. /**
  10944. * Log a message to the console
  10945. */
  10946. Tools.Log = Tools._LogEnabled;
  10947. /**
  10948. * Write a warning message to the console
  10949. */
  10950. Tools.Warn = Tools._WarnEnabled;
  10951. /**
  10952. * Write an error message to the console
  10953. */
  10954. Tools.Error = Tools._ErrorEnabled;
  10955. // Performances
  10956. /**
  10957. * No performance log
  10958. */
  10959. Tools.PerformanceNoneLogLevel = 0;
  10960. /**
  10961. * Use user marks to log performance
  10962. */
  10963. Tools.PerformanceUserMarkLogLevel = 1;
  10964. /**
  10965. * Log performance to the console
  10966. */
  10967. Tools.PerformanceConsoleLogLevel = 2;
  10968. /**
  10969. * Starts a performance counter
  10970. */
  10971. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10972. /**
  10973. * Ends a specific performance coutner
  10974. */
  10975. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10976. return Tools;
  10977. }());
  10978. BABYLON.Tools = Tools;
  10979. /**
  10980. * This class is used to track a performance counter which is number based.
  10981. * The user has access to many properties which give statistics of different nature.
  10982. *
  10983. * The implementer can track two kinds of Performance Counter: time and count.
  10984. * 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.
  10985. * 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.
  10986. */
  10987. var PerfCounter = /** @class */ (function () {
  10988. /**
  10989. * Creates a new counter
  10990. */
  10991. function PerfCounter() {
  10992. this._startMonitoringTime = 0;
  10993. this._min = 0;
  10994. this._max = 0;
  10995. this._average = 0;
  10996. this._lastSecAverage = 0;
  10997. this._current = 0;
  10998. this._totalValueCount = 0;
  10999. this._totalAccumulated = 0;
  11000. this._lastSecAccumulated = 0;
  11001. this._lastSecTime = 0;
  11002. this._lastSecValueCount = 0;
  11003. }
  11004. Object.defineProperty(PerfCounter.prototype, "min", {
  11005. /**
  11006. * Returns the smallest value ever
  11007. */
  11008. get: function () {
  11009. return this._min;
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. Object.defineProperty(PerfCounter.prototype, "max", {
  11015. /**
  11016. * Returns the biggest value ever
  11017. */
  11018. get: function () {
  11019. return this._max;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(PerfCounter.prototype, "average", {
  11025. /**
  11026. * Returns the average value since the performance counter is running
  11027. */
  11028. get: function () {
  11029. return this._average;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  11035. /**
  11036. * Returns the average value of the last second the counter was monitored
  11037. */
  11038. get: function () {
  11039. return this._lastSecAverage;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Object.defineProperty(PerfCounter.prototype, "current", {
  11045. /**
  11046. * Returns the current value
  11047. */
  11048. get: function () {
  11049. return this._current;
  11050. },
  11051. enumerable: true,
  11052. configurable: true
  11053. });
  11054. Object.defineProperty(PerfCounter.prototype, "total", {
  11055. /**
  11056. * Gets the accumulated total
  11057. */
  11058. get: function () {
  11059. return this._totalAccumulated;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(PerfCounter.prototype, "count", {
  11065. /**
  11066. * Gets the total value count
  11067. */
  11068. get: function () {
  11069. return this._totalValueCount;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. /**
  11075. * Call this method to start monitoring a new frame.
  11076. * 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.
  11077. */
  11078. PerfCounter.prototype.fetchNewFrame = function () {
  11079. this._totalValueCount++;
  11080. this._current = 0;
  11081. this._lastSecValueCount++;
  11082. };
  11083. /**
  11084. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  11085. * @param newCount the count value to add to the monitored count
  11086. * @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.
  11087. */
  11088. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  11089. if (!PerfCounter.Enabled) {
  11090. return;
  11091. }
  11092. this._current += newCount;
  11093. if (fetchResult) {
  11094. this._fetchResult();
  11095. }
  11096. };
  11097. /**
  11098. * Start monitoring this performance counter
  11099. */
  11100. PerfCounter.prototype.beginMonitoring = function () {
  11101. if (!PerfCounter.Enabled) {
  11102. return;
  11103. }
  11104. this._startMonitoringTime = Tools.Now;
  11105. };
  11106. /**
  11107. * Compute the time lapsed since the previous beginMonitoring() call.
  11108. * @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
  11109. */
  11110. PerfCounter.prototype.endMonitoring = function (newFrame) {
  11111. if (newFrame === void 0) { newFrame = true; }
  11112. if (!PerfCounter.Enabled) {
  11113. return;
  11114. }
  11115. if (newFrame) {
  11116. this.fetchNewFrame();
  11117. }
  11118. var currentTime = Tools.Now;
  11119. this._current = currentTime - this._startMonitoringTime;
  11120. if (newFrame) {
  11121. this._fetchResult();
  11122. }
  11123. };
  11124. PerfCounter.prototype._fetchResult = function () {
  11125. this._totalAccumulated += this._current;
  11126. this._lastSecAccumulated += this._current;
  11127. // Min/Max update
  11128. this._min = Math.min(this._min, this._current);
  11129. this._max = Math.max(this._max, this._current);
  11130. this._average = this._totalAccumulated / this._totalValueCount;
  11131. // Reset last sec?
  11132. var now = Tools.Now;
  11133. if ((now - this._lastSecTime) > 1000) {
  11134. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  11135. this._lastSecTime = now;
  11136. this._lastSecAccumulated = 0;
  11137. this._lastSecValueCount = 0;
  11138. }
  11139. };
  11140. /**
  11141. * Gets or sets a global boolean to turn on and off all the counters
  11142. */
  11143. PerfCounter.Enabled = true;
  11144. return PerfCounter;
  11145. }());
  11146. BABYLON.PerfCounter = PerfCounter;
  11147. /**
  11148. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11149. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11150. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11151. * @param name The name of the class, case should be preserved
  11152. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11153. */
  11154. function className(name, module) {
  11155. return function (target) {
  11156. target["__bjsclassName__"] = name;
  11157. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11158. };
  11159. }
  11160. BABYLON.className = className;
  11161. /**
  11162. * An implementation of a loop for asynchronous functions.
  11163. */
  11164. var AsyncLoop = /** @class */ (function () {
  11165. /**
  11166. * Constructor.
  11167. * @param iterations the number of iterations.
  11168. * @param func the function to run each iteration
  11169. * @param successCallback the callback that will be called upon succesful execution
  11170. * @param offset starting offset.
  11171. */
  11172. function AsyncLoop(
  11173. /**
  11174. * Defines the number of iterations for the loop
  11175. */
  11176. iterations, func, successCallback, offset) {
  11177. if (offset === void 0) { offset = 0; }
  11178. this.iterations = iterations;
  11179. this.index = offset - 1;
  11180. this._done = false;
  11181. this._fn = func;
  11182. this._successCallback = successCallback;
  11183. }
  11184. /**
  11185. * Execute the next iteration. Must be called after the last iteration was finished.
  11186. */
  11187. AsyncLoop.prototype.executeNext = function () {
  11188. if (!this._done) {
  11189. if (this.index + 1 < this.iterations) {
  11190. ++this.index;
  11191. this._fn(this);
  11192. }
  11193. else {
  11194. this.breakLoop();
  11195. }
  11196. }
  11197. };
  11198. /**
  11199. * Break the loop and run the success callback.
  11200. */
  11201. AsyncLoop.prototype.breakLoop = function () {
  11202. this._done = true;
  11203. this._successCallback();
  11204. };
  11205. /**
  11206. * Create and run an async loop.
  11207. * @param iterations the number of iterations.
  11208. * @param fn the function to run each iteration
  11209. * @param successCallback the callback that will be called upon succesful execution
  11210. * @param offset starting offset.
  11211. * @returns the created async loop object
  11212. */
  11213. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11214. if (offset === void 0) { offset = 0; }
  11215. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11216. loop.executeNext();
  11217. return loop;
  11218. };
  11219. /**
  11220. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11221. * @param iterations total number of iterations
  11222. * @param syncedIterations number of synchronous iterations in each async iteration.
  11223. * @param fn the function to call each iteration.
  11224. * @param callback a success call back that will be called when iterating stops.
  11225. * @param breakFunction a break condition (optional)
  11226. * @param timeout timeout settings for the setTimeout function. default - 0.
  11227. * @returns the created async loop object
  11228. */
  11229. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11230. if (timeout === void 0) { timeout = 0; }
  11231. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11232. if (breakFunction && breakFunction()) {
  11233. loop.breakLoop();
  11234. }
  11235. else {
  11236. setTimeout(function () {
  11237. for (var i = 0; i < syncedIterations; ++i) {
  11238. var iteration = (loop.index * syncedIterations) + i;
  11239. if (iteration >= iterations) {
  11240. break;
  11241. }
  11242. fn(iteration);
  11243. if (breakFunction && breakFunction()) {
  11244. loop.breakLoop();
  11245. break;
  11246. }
  11247. }
  11248. loop.executeNext();
  11249. }, timeout);
  11250. }
  11251. }, callback);
  11252. };
  11253. return AsyncLoop;
  11254. }());
  11255. BABYLON.AsyncLoop = AsyncLoop;
  11256. })(BABYLON || (BABYLON = {}));
  11257. //# sourceMappingURL=babylon.tools.js.map
  11258. var BABYLON;
  11259. (function (BABYLON) {
  11260. var PromiseStates;
  11261. (function (PromiseStates) {
  11262. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11263. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11264. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11265. })(PromiseStates || (PromiseStates = {}));
  11266. var FulFillmentAgregator = /** @class */ (function () {
  11267. function FulFillmentAgregator() {
  11268. this.count = 0;
  11269. this.target = 0;
  11270. this.results = [];
  11271. }
  11272. return FulFillmentAgregator;
  11273. }());
  11274. var InternalPromise = /** @class */ (function () {
  11275. function InternalPromise(resolver) {
  11276. var _this = this;
  11277. this._state = PromiseStates.Pending;
  11278. this._children = new Array();
  11279. this._rejectWasConsumed = false;
  11280. if (!resolver) {
  11281. return;
  11282. }
  11283. try {
  11284. resolver(function (value) {
  11285. _this._resolve(value);
  11286. }, function (reason) {
  11287. _this._reject(reason);
  11288. });
  11289. }
  11290. catch (e) {
  11291. this._reject(e);
  11292. }
  11293. }
  11294. Object.defineProperty(InternalPromise.prototype, "_result", {
  11295. get: function () {
  11296. return this._resultValue;
  11297. },
  11298. set: function (value) {
  11299. this._resultValue = value;
  11300. if (this._parent && this._parent._result === undefined) {
  11301. this._parent._result = value;
  11302. }
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. InternalPromise.prototype.catch = function (onRejected) {
  11308. return this.then(undefined, onRejected);
  11309. };
  11310. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11311. var _this = this;
  11312. var newPromise = new InternalPromise();
  11313. newPromise._onFulfilled = onFulfilled;
  11314. newPromise._onRejected = onRejected;
  11315. // Composition
  11316. this._children.push(newPromise);
  11317. newPromise._parent = this;
  11318. if (this._state !== PromiseStates.Pending) {
  11319. BABYLON.Tools.SetImmediate(function () {
  11320. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11321. var returnedValue = newPromise._resolve(_this._result);
  11322. if (returnedValue !== undefined && returnedValue !== null) {
  11323. if (returnedValue._state !== undefined) {
  11324. var returnedPromise = returnedValue;
  11325. newPromise._children.push(returnedPromise);
  11326. returnedPromise._parent = newPromise;
  11327. newPromise = returnedPromise;
  11328. }
  11329. else {
  11330. newPromise._result = returnedValue;
  11331. }
  11332. }
  11333. }
  11334. else {
  11335. newPromise._reject(_this._reason);
  11336. }
  11337. });
  11338. }
  11339. return newPromise;
  11340. };
  11341. InternalPromise.prototype._moveChildren = function (children) {
  11342. var _this = this;
  11343. var _a;
  11344. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11345. this._children.forEach(function (child) {
  11346. child._parent = _this;
  11347. });
  11348. if (this._state === PromiseStates.Fulfilled) {
  11349. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11350. var child = _b[_i];
  11351. child._resolve(this._result);
  11352. }
  11353. }
  11354. else if (this._state === PromiseStates.Rejected) {
  11355. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11356. var child = _d[_c];
  11357. child._reject(this._reason);
  11358. }
  11359. }
  11360. };
  11361. InternalPromise.prototype._resolve = function (value) {
  11362. try {
  11363. this._state = PromiseStates.Fulfilled;
  11364. var returnedValue = null;
  11365. if (this._onFulfilled) {
  11366. returnedValue = this._onFulfilled(value);
  11367. }
  11368. if (returnedValue !== undefined && returnedValue !== null) {
  11369. if (returnedValue._state !== undefined) {
  11370. // Transmit children
  11371. var returnedPromise = returnedValue;
  11372. returnedPromise._parent = this;
  11373. returnedPromise._moveChildren(this._children);
  11374. value = returnedPromise._result;
  11375. }
  11376. else {
  11377. value = returnedValue;
  11378. }
  11379. }
  11380. this._result = value;
  11381. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11382. var child = _a[_i];
  11383. child._resolve(value);
  11384. }
  11385. this._children.length = 0;
  11386. delete this._onFulfilled;
  11387. delete this._onRejected;
  11388. }
  11389. catch (e) {
  11390. this._reject(e, true);
  11391. }
  11392. };
  11393. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11394. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11395. this._state = PromiseStates.Rejected;
  11396. this._reason = reason;
  11397. if (this._onRejected && !onLocalThrow) {
  11398. try {
  11399. this._onRejected(reason);
  11400. this._rejectWasConsumed = true;
  11401. }
  11402. catch (e) {
  11403. reason = e;
  11404. }
  11405. }
  11406. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11407. var child = _a[_i];
  11408. if (this._rejectWasConsumed) {
  11409. child._resolve(null);
  11410. }
  11411. else {
  11412. child._reject(reason);
  11413. }
  11414. }
  11415. this._children.length = 0;
  11416. delete this._onFulfilled;
  11417. delete this._onRejected;
  11418. };
  11419. InternalPromise.resolve = function (value) {
  11420. var newPromise = new InternalPromise();
  11421. newPromise._resolve(value);
  11422. return newPromise;
  11423. };
  11424. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11425. promise.then(function (value) {
  11426. agregator.results[index] = value;
  11427. agregator.count++;
  11428. if (agregator.count === agregator.target) {
  11429. agregator.rootPromise._resolve(agregator.results);
  11430. }
  11431. return null;
  11432. }, function (reason) {
  11433. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11434. agregator.rootPromise._reject(reason);
  11435. }
  11436. });
  11437. };
  11438. InternalPromise.all = function (promises) {
  11439. var newPromise = new InternalPromise();
  11440. var agregator = new FulFillmentAgregator();
  11441. agregator.target = promises.length;
  11442. agregator.rootPromise = newPromise;
  11443. if (promises.length) {
  11444. for (var index = 0; index < promises.length; index++) {
  11445. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11446. }
  11447. }
  11448. else {
  11449. newPromise._resolve([]);
  11450. }
  11451. return newPromise;
  11452. };
  11453. InternalPromise.race = function (promises) {
  11454. var newPromise = new InternalPromise();
  11455. if (promises.length) {
  11456. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11457. var promise = promises_1[_i];
  11458. promise.then(function (value) {
  11459. if (newPromise) {
  11460. newPromise._resolve(value);
  11461. newPromise = null;
  11462. }
  11463. return null;
  11464. }, function (reason) {
  11465. if (newPromise) {
  11466. newPromise._reject(reason);
  11467. newPromise = null;
  11468. }
  11469. });
  11470. }
  11471. }
  11472. return newPromise;
  11473. };
  11474. return InternalPromise;
  11475. }());
  11476. /**
  11477. * Helper class that provides a small promise polyfill
  11478. */
  11479. var PromisePolyfill = /** @class */ (function () {
  11480. function PromisePolyfill() {
  11481. }
  11482. /**
  11483. * Static function used to check if the polyfill is required
  11484. * If this is the case then the function will inject the polyfill to window.Promise
  11485. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11486. */
  11487. PromisePolyfill.Apply = function (force) {
  11488. if (force === void 0) { force = false; }
  11489. if (force || typeof Promise === 'undefined') {
  11490. var root = window;
  11491. root.Promise = InternalPromise;
  11492. }
  11493. };
  11494. return PromisePolyfill;
  11495. }());
  11496. BABYLON.PromisePolyfill = PromisePolyfill;
  11497. })(BABYLON || (BABYLON = {}));
  11498. //# sourceMappingURL=babylon.promise.js.map
  11499. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11500. var BABYLON;
  11501. (function (BABYLON) {
  11502. /**
  11503. * Helper class to push actions to a pool of workers.
  11504. */
  11505. var WorkerPool = /** @class */ (function () {
  11506. /**
  11507. * Constructor
  11508. * @param workers Array of workers to use for actions
  11509. */
  11510. function WorkerPool(workers) {
  11511. this._pendingActions = new Array();
  11512. this._workerInfos = workers.map(function (worker) { return ({
  11513. worker: worker,
  11514. active: false
  11515. }); });
  11516. }
  11517. /**
  11518. * Terminates all workers and clears any pending actions.
  11519. */
  11520. WorkerPool.prototype.dispose = function () {
  11521. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11522. var workerInfo = _a[_i];
  11523. workerInfo.worker.terminate();
  11524. }
  11525. delete this._workerInfos;
  11526. delete this._pendingActions;
  11527. };
  11528. /**
  11529. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11530. * pended until a worker has completed its action.
  11531. * @param action The action to perform. Call onComplete when the action is complete.
  11532. */
  11533. WorkerPool.prototype.push = function (action) {
  11534. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11535. var workerInfo = _a[_i];
  11536. if (!workerInfo.active) {
  11537. this._execute(workerInfo, action);
  11538. return;
  11539. }
  11540. }
  11541. this._pendingActions.push(action);
  11542. };
  11543. WorkerPool.prototype._execute = function (workerInfo, action) {
  11544. var _this = this;
  11545. workerInfo.active = true;
  11546. action(workerInfo.worker, function () {
  11547. workerInfo.active = false;
  11548. var nextAction = _this._pendingActions.shift();
  11549. if (nextAction) {
  11550. _this._execute(workerInfo, nextAction);
  11551. }
  11552. });
  11553. };
  11554. return WorkerPool;
  11555. }());
  11556. BABYLON.WorkerPool = WorkerPool;
  11557. })(BABYLON || (BABYLON = {}));
  11558. //# sourceMappingURL=babylon.workerPool.js.map
  11559. var BABYLON;
  11560. (function (BABYLON) {
  11561. /**
  11562. * @hidden
  11563. **/
  11564. var _AlphaState = /** @class */ (function () {
  11565. /**
  11566. * Initializes the state.
  11567. */
  11568. function _AlphaState() {
  11569. this._isAlphaBlendDirty = false;
  11570. this._isBlendFunctionParametersDirty = false;
  11571. this._isBlendEquationParametersDirty = false;
  11572. this._isBlendConstantsDirty = false;
  11573. this._alphaBlend = false;
  11574. this._blendFunctionParameters = new Array(4);
  11575. this._blendEquationParameters = new Array(2);
  11576. this._blendConstants = new Array(4);
  11577. this.reset();
  11578. }
  11579. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11580. get: function () {
  11581. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11587. get: function () {
  11588. return this._alphaBlend;
  11589. },
  11590. set: function (value) {
  11591. if (this._alphaBlend === value) {
  11592. return;
  11593. }
  11594. this._alphaBlend = value;
  11595. this._isAlphaBlendDirty = true;
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11601. if (this._blendConstants[0] === r &&
  11602. this._blendConstants[1] === g &&
  11603. this._blendConstants[2] === b &&
  11604. this._blendConstants[3] === a) {
  11605. return;
  11606. }
  11607. this._blendConstants[0] = r;
  11608. this._blendConstants[1] = g;
  11609. this._blendConstants[2] = b;
  11610. this._blendConstants[3] = a;
  11611. this._isBlendConstantsDirty = true;
  11612. };
  11613. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11614. if (this._blendFunctionParameters[0] === value0 &&
  11615. this._blendFunctionParameters[1] === value1 &&
  11616. this._blendFunctionParameters[2] === value2 &&
  11617. this._blendFunctionParameters[3] === value3) {
  11618. return;
  11619. }
  11620. this._blendFunctionParameters[0] = value0;
  11621. this._blendFunctionParameters[1] = value1;
  11622. this._blendFunctionParameters[2] = value2;
  11623. this._blendFunctionParameters[3] = value3;
  11624. this._isBlendFunctionParametersDirty = true;
  11625. };
  11626. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11627. if (this._blendEquationParameters[0] === rgb &&
  11628. this._blendEquationParameters[1] === alpha) {
  11629. return;
  11630. }
  11631. this._blendEquationParameters[0] = rgb;
  11632. this._blendEquationParameters[1] = alpha;
  11633. this._isBlendEquationParametersDirty = true;
  11634. };
  11635. _AlphaState.prototype.reset = function () {
  11636. this._alphaBlend = false;
  11637. this._blendFunctionParameters[0] = null;
  11638. this._blendFunctionParameters[1] = null;
  11639. this._blendFunctionParameters[2] = null;
  11640. this._blendFunctionParameters[3] = null;
  11641. this._blendEquationParameters[0] = null;
  11642. this._blendEquationParameters[1] = null;
  11643. this._blendConstants[0] = null;
  11644. this._blendConstants[1] = null;
  11645. this._blendConstants[2] = null;
  11646. this._blendConstants[3] = null;
  11647. this._isAlphaBlendDirty = true;
  11648. this._isBlendFunctionParametersDirty = false;
  11649. this._isBlendEquationParametersDirty = false;
  11650. this._isBlendConstantsDirty = false;
  11651. };
  11652. _AlphaState.prototype.apply = function (gl) {
  11653. if (!this.isDirty) {
  11654. return;
  11655. }
  11656. // Alpha blend
  11657. if (this._isAlphaBlendDirty) {
  11658. if (this._alphaBlend) {
  11659. gl.enable(gl.BLEND);
  11660. }
  11661. else {
  11662. gl.disable(gl.BLEND);
  11663. }
  11664. this._isAlphaBlendDirty = false;
  11665. }
  11666. // Alpha function
  11667. if (this._isBlendFunctionParametersDirty) {
  11668. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11669. this._isBlendFunctionParametersDirty = false;
  11670. }
  11671. // Alpha equation
  11672. if (this._isBlendEquationParametersDirty) {
  11673. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11674. this._isBlendEquationParametersDirty = false;
  11675. }
  11676. // Constants
  11677. if (this._isBlendConstantsDirty) {
  11678. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11679. this._isBlendConstantsDirty = false;
  11680. }
  11681. };
  11682. return _AlphaState;
  11683. }());
  11684. BABYLON._AlphaState = _AlphaState;
  11685. })(BABYLON || (BABYLON = {}));
  11686. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11687. var BABYLON;
  11688. (function (BABYLON) {
  11689. /**
  11690. * @hidden
  11691. **/
  11692. var _DepthCullingState = /** @class */ (function () {
  11693. /**
  11694. * Initializes the state.
  11695. */
  11696. function _DepthCullingState() {
  11697. this._isDepthTestDirty = false;
  11698. this._isDepthMaskDirty = false;
  11699. this._isDepthFuncDirty = false;
  11700. this._isCullFaceDirty = false;
  11701. this._isCullDirty = false;
  11702. this._isZOffsetDirty = false;
  11703. this._isFrontFaceDirty = false;
  11704. this.reset();
  11705. }
  11706. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11707. get: function () {
  11708. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11714. get: function () {
  11715. return this._zOffset;
  11716. },
  11717. set: function (value) {
  11718. if (this._zOffset === value) {
  11719. return;
  11720. }
  11721. this._zOffset = value;
  11722. this._isZOffsetDirty = true;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11728. get: function () {
  11729. return this._cullFace;
  11730. },
  11731. set: function (value) {
  11732. if (this._cullFace === value) {
  11733. return;
  11734. }
  11735. this._cullFace = value;
  11736. this._isCullFaceDirty = true;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11742. get: function () {
  11743. return this._cull;
  11744. },
  11745. set: function (value) {
  11746. if (this._cull === value) {
  11747. return;
  11748. }
  11749. this._cull = value;
  11750. this._isCullDirty = true;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11756. get: function () {
  11757. return this._depthFunc;
  11758. },
  11759. set: function (value) {
  11760. if (this._depthFunc === value) {
  11761. return;
  11762. }
  11763. this._depthFunc = value;
  11764. this._isDepthFuncDirty = true;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11770. get: function () {
  11771. return this._depthMask;
  11772. },
  11773. set: function (value) {
  11774. if (this._depthMask === value) {
  11775. return;
  11776. }
  11777. this._depthMask = value;
  11778. this._isDepthMaskDirty = true;
  11779. },
  11780. enumerable: true,
  11781. configurable: true
  11782. });
  11783. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11784. get: function () {
  11785. return this._depthTest;
  11786. },
  11787. set: function (value) {
  11788. if (this._depthTest === value) {
  11789. return;
  11790. }
  11791. this._depthTest = value;
  11792. this._isDepthTestDirty = true;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11798. get: function () {
  11799. return this._frontFace;
  11800. },
  11801. set: function (value) {
  11802. if (this._frontFace === value) {
  11803. return;
  11804. }
  11805. this._frontFace = value;
  11806. this._isFrontFaceDirty = true;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. _DepthCullingState.prototype.reset = function () {
  11812. this._depthMask = true;
  11813. this._depthTest = true;
  11814. this._depthFunc = null;
  11815. this._cullFace = null;
  11816. this._cull = null;
  11817. this._zOffset = 0;
  11818. this._frontFace = null;
  11819. this._isDepthTestDirty = true;
  11820. this._isDepthMaskDirty = true;
  11821. this._isDepthFuncDirty = false;
  11822. this._isCullFaceDirty = false;
  11823. this._isCullDirty = false;
  11824. this._isZOffsetDirty = false;
  11825. this._isFrontFaceDirty = false;
  11826. };
  11827. _DepthCullingState.prototype.apply = function (gl) {
  11828. if (!this.isDirty) {
  11829. return;
  11830. }
  11831. // Cull
  11832. if (this._isCullDirty) {
  11833. if (this.cull) {
  11834. gl.enable(gl.CULL_FACE);
  11835. }
  11836. else {
  11837. gl.disable(gl.CULL_FACE);
  11838. }
  11839. this._isCullDirty = false;
  11840. }
  11841. // Cull face
  11842. if (this._isCullFaceDirty) {
  11843. gl.cullFace(this.cullFace);
  11844. this._isCullFaceDirty = false;
  11845. }
  11846. // Depth mask
  11847. if (this._isDepthMaskDirty) {
  11848. gl.depthMask(this.depthMask);
  11849. this._isDepthMaskDirty = false;
  11850. }
  11851. // Depth test
  11852. if (this._isDepthTestDirty) {
  11853. if (this.depthTest) {
  11854. gl.enable(gl.DEPTH_TEST);
  11855. }
  11856. else {
  11857. gl.disable(gl.DEPTH_TEST);
  11858. }
  11859. this._isDepthTestDirty = false;
  11860. }
  11861. // Depth func
  11862. if (this._isDepthFuncDirty) {
  11863. gl.depthFunc(this.depthFunc);
  11864. this._isDepthFuncDirty = false;
  11865. }
  11866. // zOffset
  11867. if (this._isZOffsetDirty) {
  11868. if (this.zOffset) {
  11869. gl.enable(gl.POLYGON_OFFSET_FILL);
  11870. gl.polygonOffset(this.zOffset, 0);
  11871. }
  11872. else {
  11873. gl.disable(gl.POLYGON_OFFSET_FILL);
  11874. }
  11875. this._isZOffsetDirty = false;
  11876. }
  11877. // Front face
  11878. if (this._isFrontFaceDirty) {
  11879. gl.frontFace(this.frontFace);
  11880. this._isFrontFaceDirty = false;
  11881. }
  11882. };
  11883. return _DepthCullingState;
  11884. }());
  11885. BABYLON._DepthCullingState = _DepthCullingState;
  11886. })(BABYLON || (BABYLON = {}));
  11887. //# sourceMappingURL=babylon.depthCullingState.js.map
  11888. var BABYLON;
  11889. (function (BABYLON) {
  11890. /**
  11891. * @hidden
  11892. **/
  11893. var _StencilState = /** @class */ (function () {
  11894. function _StencilState() {
  11895. this._isStencilTestDirty = false;
  11896. this._isStencilMaskDirty = false;
  11897. this._isStencilFuncDirty = false;
  11898. this._isStencilOpDirty = false;
  11899. this.reset();
  11900. }
  11901. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11902. get: function () {
  11903. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11909. get: function () {
  11910. return this._stencilFunc;
  11911. },
  11912. set: function (value) {
  11913. if (this._stencilFunc === value) {
  11914. return;
  11915. }
  11916. this._stencilFunc = value;
  11917. this._isStencilFuncDirty = true;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11923. get: function () {
  11924. return this._stencilFuncRef;
  11925. },
  11926. set: function (value) {
  11927. if (this._stencilFuncRef === value) {
  11928. return;
  11929. }
  11930. this._stencilFuncRef = value;
  11931. this._isStencilFuncDirty = true;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11937. get: function () {
  11938. return this._stencilFuncMask;
  11939. },
  11940. set: function (value) {
  11941. if (this._stencilFuncMask === value) {
  11942. return;
  11943. }
  11944. this._stencilFuncMask = value;
  11945. this._isStencilFuncDirty = true;
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11951. get: function () {
  11952. return this._stencilOpStencilFail;
  11953. },
  11954. set: function (value) {
  11955. if (this._stencilOpStencilFail === value) {
  11956. return;
  11957. }
  11958. this._stencilOpStencilFail = value;
  11959. this._isStencilOpDirty = true;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11965. get: function () {
  11966. return this._stencilOpDepthFail;
  11967. },
  11968. set: function (value) {
  11969. if (this._stencilOpDepthFail === value) {
  11970. return;
  11971. }
  11972. this._stencilOpDepthFail = value;
  11973. this._isStencilOpDirty = true;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11979. get: function () {
  11980. return this._stencilOpStencilDepthPass;
  11981. },
  11982. set: function (value) {
  11983. if (this._stencilOpStencilDepthPass === value) {
  11984. return;
  11985. }
  11986. this._stencilOpStencilDepthPass = value;
  11987. this._isStencilOpDirty = true;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11993. get: function () {
  11994. return this._stencilMask;
  11995. },
  11996. set: function (value) {
  11997. if (this._stencilMask === value) {
  11998. return;
  11999. }
  12000. this._stencilMask = value;
  12001. this._isStencilMaskDirty = true;
  12002. },
  12003. enumerable: true,
  12004. configurable: true
  12005. });
  12006. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  12007. get: function () {
  12008. return this._stencilTest;
  12009. },
  12010. set: function (value) {
  12011. if (this._stencilTest === value) {
  12012. return;
  12013. }
  12014. this._stencilTest = value;
  12015. this._isStencilTestDirty = true;
  12016. },
  12017. enumerable: true,
  12018. configurable: true
  12019. });
  12020. _StencilState.prototype.reset = function () {
  12021. this._stencilTest = false;
  12022. this._stencilMask = 0xFF;
  12023. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12024. this._stencilFuncRef = 1;
  12025. this._stencilFuncMask = 0xFF;
  12026. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12027. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12028. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12029. this._isStencilTestDirty = true;
  12030. this._isStencilMaskDirty = true;
  12031. this._isStencilFuncDirty = true;
  12032. this._isStencilOpDirty = true;
  12033. };
  12034. _StencilState.prototype.apply = function (gl) {
  12035. if (!this.isDirty) {
  12036. return;
  12037. }
  12038. // Stencil test
  12039. if (this._isStencilTestDirty) {
  12040. if (this.stencilTest) {
  12041. gl.enable(gl.STENCIL_TEST);
  12042. }
  12043. else {
  12044. gl.disable(gl.STENCIL_TEST);
  12045. }
  12046. this._isStencilTestDirty = false;
  12047. }
  12048. // Stencil mask
  12049. if (this._isStencilMaskDirty) {
  12050. gl.stencilMask(this.stencilMask);
  12051. this._isStencilMaskDirty = false;
  12052. }
  12053. // Stencil func
  12054. if (this._isStencilFuncDirty) {
  12055. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12056. this._isStencilFuncDirty = false;
  12057. }
  12058. // Stencil op
  12059. if (this._isStencilOpDirty) {
  12060. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12061. this._isStencilOpDirty = false;
  12062. }
  12063. };
  12064. return _StencilState;
  12065. }());
  12066. BABYLON._StencilState = _StencilState;
  12067. })(BABYLON || (BABYLON = {}));
  12068. //# sourceMappingURL=babylon.stencilState.js.map
  12069. var __assign = (this && this.__assign) || function () {
  12070. __assign = Object.assign || function(t) {
  12071. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12072. s = arguments[i];
  12073. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12074. t[p] = s[p];
  12075. }
  12076. return t;
  12077. };
  12078. return __assign.apply(this, arguments);
  12079. };
  12080. var BABYLON;
  12081. (function (BABYLON) {
  12082. /**
  12083. * Keeps track of all the buffer info used in engine.
  12084. */
  12085. var BufferPointer = /** @class */ (function () {
  12086. function BufferPointer() {
  12087. }
  12088. return BufferPointer;
  12089. }());
  12090. /**
  12091. * Interface for attribute information associated with buffer instanciation
  12092. */
  12093. var InstancingAttributeInfo = /** @class */ (function () {
  12094. function InstancingAttributeInfo() {
  12095. }
  12096. return InstancingAttributeInfo;
  12097. }());
  12098. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12099. /**
  12100. * Define options used to create a render target texture
  12101. */
  12102. var RenderTargetCreationOptions = /** @class */ (function () {
  12103. function RenderTargetCreationOptions() {
  12104. }
  12105. return RenderTargetCreationOptions;
  12106. }());
  12107. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12108. /**
  12109. * Define options used to create a depth texture
  12110. */
  12111. var DepthTextureCreationOptions = /** @class */ (function () {
  12112. function DepthTextureCreationOptions() {
  12113. }
  12114. return DepthTextureCreationOptions;
  12115. }());
  12116. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12117. /**
  12118. * Class used to describe the capabilities of the engine relatively to the current browser
  12119. */
  12120. var EngineCapabilities = /** @class */ (function () {
  12121. function EngineCapabilities() {
  12122. }
  12123. return EngineCapabilities;
  12124. }());
  12125. BABYLON.EngineCapabilities = EngineCapabilities;
  12126. /**
  12127. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12128. */
  12129. var Engine = /** @class */ (function () {
  12130. /**
  12131. * Creates a new engine
  12132. * @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
  12133. * @param antialias defines enable antialiasing (default: false)
  12134. * @param options defines further options to be sent to the getContext() function
  12135. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12136. */
  12137. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12138. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12139. var _this = this;
  12140. // Public members
  12141. /**
  12142. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12143. */
  12144. this.forcePOTTextures = false;
  12145. /**
  12146. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12147. */
  12148. this.isFullscreen = false;
  12149. /**
  12150. * Gets a boolean indicating if the pointer is currently locked
  12151. */
  12152. this.isPointerLock = false;
  12153. /**
  12154. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12155. */
  12156. this.cullBackFaces = true;
  12157. /**
  12158. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12159. */
  12160. this.renderEvenInBackground = true;
  12161. /**
  12162. * Gets or sets a boolean indicating that cache can be kept between frames
  12163. */
  12164. this.preventCacheWipeBetweenFrames = false;
  12165. /**
  12166. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12167. **/
  12168. this.enableOfflineSupport = false;
  12169. /**
  12170. * 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)
  12171. **/
  12172. this.disableManifestCheck = false;
  12173. /**
  12174. * Gets the list of created scenes
  12175. */
  12176. this.scenes = new Array();
  12177. /**
  12178. * Gets the list of created postprocesses
  12179. */
  12180. this.postProcesses = new Array();
  12181. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12182. this.validateShaderPrograms = false;
  12183. // Observables
  12184. /**
  12185. * Observable event triggered each time the rendering canvas is resized
  12186. */
  12187. this.onResizeObservable = new BABYLON.Observable();
  12188. /**
  12189. * Observable event triggered each time the canvas loses focus
  12190. */
  12191. this.onCanvasBlurObservable = new BABYLON.Observable();
  12192. /**
  12193. * Observable event triggered each time the canvas gains focus
  12194. */
  12195. this.onCanvasFocusObservable = new BABYLON.Observable();
  12196. /**
  12197. * Observable event triggered each time the canvas receives pointerout event
  12198. */
  12199. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12200. /**
  12201. * Observable event triggered before each texture is initialized
  12202. */
  12203. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12204. //WebVR
  12205. this._vrDisplay = undefined;
  12206. this._vrSupported = false;
  12207. this._vrExclusivePointerMode = false;
  12208. // Uniform buffers list
  12209. /**
  12210. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12211. */
  12212. this.disableUniformBuffers = false;
  12213. /** @hidden */
  12214. this._uniformBuffers = new Array();
  12215. // Observables
  12216. /**
  12217. * Observable raised when the engine begins a new frame
  12218. */
  12219. this.onBeginFrameObservable = new BABYLON.Observable();
  12220. /**
  12221. * Observable raised when the engine ends the current frame
  12222. */
  12223. this.onEndFrameObservable = new BABYLON.Observable();
  12224. /**
  12225. * Observable raised when the engine is about to compile a shader
  12226. */
  12227. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12228. /**
  12229. * Observable raised when the engine has jsut compiled a shader
  12230. */
  12231. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12232. this._windowIsBackground = false;
  12233. this._webGLVersion = 1.0;
  12234. /** @hidden */
  12235. this._badOS = false;
  12236. /** @hidden */
  12237. this._badDesktopOS = false;
  12238. /**
  12239. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12240. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12241. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12242. */
  12243. this.disableTextureBindingOptimization = false;
  12244. /**
  12245. * Observable signaled when VR display mode changes
  12246. */
  12247. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12248. /**
  12249. * Observable signaled when VR request present is complete
  12250. */
  12251. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12252. /**
  12253. * Observable signaled when VR request present starts
  12254. */
  12255. this.onVRRequestPresentStart = new BABYLON.Observable();
  12256. this._colorWrite = true;
  12257. /** @hidden */
  12258. this._drawCalls = new BABYLON.PerfCounter();
  12259. /** @hidden */
  12260. this._textureCollisions = new BABYLON.PerfCounter();
  12261. this._renderingQueueLaunched = false;
  12262. this._activeRenderLoops = new Array();
  12263. // Deterministic lockstepMaxSteps
  12264. this._deterministicLockstep = false;
  12265. this._lockstepMaxSteps = 4;
  12266. // Lost context
  12267. /**
  12268. * Observable signaled when a context lost event is raised
  12269. */
  12270. this.onContextLostObservable = new BABYLON.Observable();
  12271. /**
  12272. * Observable signaled when a context restored event is raised
  12273. */
  12274. this.onContextRestoredObservable = new BABYLON.Observable();
  12275. this._contextWasLost = false;
  12276. this._doNotHandleContextLost = false;
  12277. // FPS
  12278. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12279. this._fps = 60;
  12280. this._deltaTime = 0;
  12281. /**
  12282. * Turn this value on if you want to pause FPS computation when in background
  12283. */
  12284. this.disablePerformanceMonitorInBackground = false;
  12285. // States
  12286. /** @hidden */
  12287. this._depthCullingState = new BABYLON._DepthCullingState();
  12288. /** @hidden */
  12289. this._stencilState = new BABYLON._StencilState();
  12290. /** @hidden */
  12291. this._alphaState = new BABYLON._AlphaState();
  12292. /** @hidden */
  12293. this._alphaMode = Engine.ALPHA_DISABLE;
  12294. // Cache
  12295. this._internalTexturesCache = new Array();
  12296. /** @hidden */
  12297. this._activeChannel = 0;
  12298. this._currentTextureChannel = -1;
  12299. /** @hidden */
  12300. this._boundTexturesCache = {};
  12301. this._compiledEffects = {};
  12302. this._vertexAttribArraysEnabled = [];
  12303. this._uintIndicesCurrentlySet = false;
  12304. this._currentBoundBuffer = new Array();
  12305. /** @hidden */
  12306. this._currentFramebuffer = null;
  12307. this._currentBufferPointers = new Array();
  12308. this._currentInstanceLocations = new Array();
  12309. this._currentInstanceBuffers = new Array();
  12310. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12311. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12312. this._vaoRecordInProgress = false;
  12313. this._mustWipeVertexAttributes = false;
  12314. this._nextFreeTextureSlots = new Array();
  12315. this._maxSimultaneousTextures = 0;
  12316. this._activeRequests = new Array();
  12317. // Hardware supported Compressed Textures
  12318. this._texturesSupported = new Array();
  12319. /**
  12320. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12321. */
  12322. this.premultipliedAlpha = true;
  12323. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12324. this._onVRFullScreenTriggered = function () {
  12325. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12326. //get the old size before we change
  12327. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12328. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12329. //get the width and height, change the render size
  12330. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12331. _this.setHardwareScalingLevel(1);
  12332. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12333. }
  12334. else {
  12335. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12336. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12337. }
  12338. };
  12339. this._unpackFlipYCached = null;
  12340. /**
  12341. * In case you are sharing the context with other applications, it might
  12342. * be interested to not cache the unpack flip y state to ensure a consistent
  12343. * value would be set.
  12344. */
  12345. this.enableUnpackFlipYCached = true;
  12346. this._boundUniforms = {};
  12347. // Register promises
  12348. BABYLON.PromisePolyfill.Apply();
  12349. var canvas = null;
  12350. Engine.Instances.push(this);
  12351. if (!canvasOrContext) {
  12352. return;
  12353. }
  12354. options = options || {};
  12355. if (canvasOrContext.getContext) {
  12356. canvas = canvasOrContext;
  12357. this._renderingCanvas = canvas;
  12358. if (antialias != null) {
  12359. options.antialias = antialias;
  12360. }
  12361. if (options.deterministicLockstep === undefined) {
  12362. options.deterministicLockstep = false;
  12363. }
  12364. if (options.lockstepMaxSteps === undefined) {
  12365. options.lockstepMaxSteps = 4;
  12366. }
  12367. if (options.preserveDrawingBuffer === undefined) {
  12368. options.preserveDrawingBuffer = false;
  12369. }
  12370. if (options.audioEngine === undefined) {
  12371. options.audioEngine = true;
  12372. }
  12373. if (options.stencil === undefined) {
  12374. options.stencil = true;
  12375. }
  12376. if (options.premultipliedAlpha === false) {
  12377. this.premultipliedAlpha = false;
  12378. }
  12379. this._deterministicLockstep = options.deterministicLockstep;
  12380. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12381. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12382. // Exceptions
  12383. if (navigator && navigator.userAgent) {
  12384. var ua = navigator.userAgent;
  12385. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12386. var exception = _a[_i];
  12387. var key = exception.key;
  12388. var targets = exception.targets;
  12389. if (ua.indexOf(key) > -1) {
  12390. if (exception.capture && exception.captureConstraint) {
  12391. var capture = exception.capture;
  12392. var constraint = exception.captureConstraint;
  12393. var regex = new RegExp(capture);
  12394. var matches = regex.exec(ua);
  12395. if (matches && matches.length > 0) {
  12396. var capturedValue = parseInt(matches[matches.length - 1]);
  12397. if (capturedValue >= constraint) {
  12398. continue;
  12399. }
  12400. }
  12401. }
  12402. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12403. var target = targets_1[_b];
  12404. switch (target) {
  12405. case "uniformBuffer":
  12406. this.disableUniformBuffers = true;
  12407. break;
  12408. case "textureBindingOptimization":
  12409. this.disableTextureBindingOptimization = true;
  12410. break;
  12411. }
  12412. }
  12413. }
  12414. }
  12415. }
  12416. // GL
  12417. if (!options.disableWebGL2Support) {
  12418. try {
  12419. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12420. if (this._gl) {
  12421. this._webGLVersion = 2.0;
  12422. // Prevent weird browsers to lie :-)
  12423. if (!this._gl.deleteQuery) {
  12424. this._webGLVersion = 1.0;
  12425. }
  12426. }
  12427. }
  12428. catch (e) {
  12429. // Do nothing
  12430. }
  12431. }
  12432. if (!this._gl) {
  12433. if (!canvas) {
  12434. throw new Error("The provided canvas is null or undefined.");
  12435. }
  12436. try {
  12437. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12438. }
  12439. catch (e) {
  12440. throw new Error("WebGL not supported");
  12441. }
  12442. }
  12443. if (!this._gl) {
  12444. throw new Error("WebGL not supported");
  12445. }
  12446. this._onCanvasFocus = function () {
  12447. _this.onCanvasFocusObservable.notifyObservers(_this);
  12448. };
  12449. this._onCanvasBlur = function () {
  12450. _this.onCanvasBlurObservable.notifyObservers(_this);
  12451. };
  12452. canvas.addEventListener("focus", this._onCanvasFocus);
  12453. canvas.addEventListener("blur", this._onCanvasBlur);
  12454. this._onBlur = function () {
  12455. if (_this.disablePerformanceMonitorInBackground) {
  12456. _this._performanceMonitor.disable();
  12457. }
  12458. _this._windowIsBackground = true;
  12459. };
  12460. this._onFocus = function () {
  12461. if (_this.disablePerformanceMonitorInBackground) {
  12462. _this._performanceMonitor.enable();
  12463. }
  12464. _this._windowIsBackground = false;
  12465. };
  12466. this._onCanvasPointerOut = function (ev) {
  12467. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12468. };
  12469. window.addEventListener("blur", this._onBlur);
  12470. window.addEventListener("focus", this._onFocus);
  12471. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12472. // Context lost
  12473. if (!this._doNotHandleContextLost) {
  12474. this._onContextLost = function (evt) {
  12475. evt.preventDefault();
  12476. _this._contextWasLost = true;
  12477. BABYLON.Tools.Warn("WebGL context lost.");
  12478. _this.onContextLostObservable.notifyObservers(_this);
  12479. };
  12480. this._onContextRestored = function (evt) {
  12481. // Adding a timeout to avoid race condition at browser level
  12482. setTimeout(function () {
  12483. // Rebuild gl context
  12484. _this._initGLContext();
  12485. // Rebuild effects
  12486. _this._rebuildEffects();
  12487. // Rebuild textures
  12488. _this._rebuildInternalTextures();
  12489. // Rebuild buffers
  12490. _this._rebuildBuffers();
  12491. // Cache
  12492. _this.wipeCaches(true);
  12493. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12494. _this.onContextRestoredObservable.notifyObservers(_this);
  12495. _this._contextWasLost = false;
  12496. }, 0);
  12497. };
  12498. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12499. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12500. }
  12501. }
  12502. else {
  12503. this._gl = canvasOrContext;
  12504. this._renderingCanvas = this._gl.canvas;
  12505. if (this._gl.renderbufferStorageMultisample) {
  12506. this._webGLVersion = 2.0;
  12507. }
  12508. options.stencil = this._gl.getContextAttributes().stencil;
  12509. }
  12510. // Viewport
  12511. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12512. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12513. this.resize();
  12514. this._isStencilEnable = options.stencil ? true : false;
  12515. this._initGLContext();
  12516. if (canvas) {
  12517. // Fullscreen
  12518. this._onFullscreenChange = function () {
  12519. if (document.fullscreen !== undefined) {
  12520. _this.isFullscreen = document.fullscreen;
  12521. }
  12522. else if (document.mozFullScreen !== undefined) {
  12523. _this.isFullscreen = document.mozFullScreen;
  12524. }
  12525. else if (document.webkitIsFullScreen !== undefined) {
  12526. _this.isFullscreen = document.webkitIsFullScreen;
  12527. }
  12528. else if (document.msIsFullScreen !== undefined) {
  12529. _this.isFullscreen = document.msIsFullScreen;
  12530. }
  12531. // Pointer lock
  12532. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12533. canvas.requestPointerLock = canvas.requestPointerLock ||
  12534. canvas.msRequestPointerLock ||
  12535. canvas.mozRequestPointerLock ||
  12536. canvas.webkitRequestPointerLock;
  12537. if (canvas.requestPointerLock) {
  12538. canvas.requestPointerLock();
  12539. }
  12540. }
  12541. };
  12542. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12543. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12544. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12545. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12546. // Pointer lock
  12547. this._onPointerLockChange = function () {
  12548. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12549. document.webkitPointerLockElement === canvas ||
  12550. document.msPointerLockElement === canvas ||
  12551. document.pointerLockElement === canvas);
  12552. };
  12553. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12554. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12555. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12556. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12557. this._onVRDisplayPointerRestricted = function () {
  12558. if (canvas) {
  12559. canvas.requestPointerLock();
  12560. }
  12561. };
  12562. this._onVRDisplayPointerUnrestricted = function () {
  12563. document.exitPointerLock();
  12564. };
  12565. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12566. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12567. }
  12568. // Create Audio Engine if needed.
  12569. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12570. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12571. }
  12572. // Prepare buffer pointers
  12573. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12574. this._currentBufferPointers[i] = new BufferPointer();
  12575. }
  12576. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12577. // Load WebVR Devices
  12578. if (options.autoEnableWebVR) {
  12579. this.initWebVR();
  12580. }
  12581. // Detect if we are running on a faulty buggy OS.
  12582. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12583. // Detect if we are running on a faulty buggy desktop OS.
  12584. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12585. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12586. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12587. }
  12588. Object.defineProperty(Engine, "LastCreatedEngine", {
  12589. /**
  12590. * Gets the latest created engine
  12591. */
  12592. get: function () {
  12593. if (Engine.Instances.length === 0) {
  12594. return null;
  12595. }
  12596. return Engine.Instances[Engine.Instances.length - 1];
  12597. },
  12598. enumerable: true,
  12599. configurable: true
  12600. });
  12601. Object.defineProperty(Engine, "LastCreatedScene", {
  12602. /**
  12603. * Gets the latest created scene
  12604. */
  12605. get: function () {
  12606. var lastCreatedEngine = Engine.LastCreatedEngine;
  12607. if (!lastCreatedEngine) {
  12608. return null;
  12609. }
  12610. if (lastCreatedEngine.scenes.length === 0) {
  12611. return null;
  12612. }
  12613. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12614. },
  12615. enumerable: true,
  12616. configurable: true
  12617. });
  12618. /**
  12619. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12620. * @param flag defines which part of the materials must be marked as dirty
  12621. * @param predicate defines a predicate used to filter which materials should be affected
  12622. */
  12623. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12624. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12625. var engine = Engine.Instances[engineIndex];
  12626. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12627. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12628. }
  12629. }
  12630. };
  12631. Object.defineProperty(Engine, "Version", {
  12632. /**
  12633. * Returns the current version of the framework
  12634. */
  12635. get: function () {
  12636. return "3.3.0-rc.4";
  12637. },
  12638. enumerable: true,
  12639. configurable: true
  12640. });
  12641. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12642. /**
  12643. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12644. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12645. */
  12646. get: function () {
  12647. return this._vrExclusivePointerMode;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12653. /**
  12654. * Gets a boolean indicating that the engine supports uniform buffers
  12655. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12656. */
  12657. get: function () {
  12658. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12659. },
  12660. enumerable: true,
  12661. configurable: true
  12662. });
  12663. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12664. /**
  12665. * Gets a boolean indicating that only power of 2 textures are supported
  12666. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12667. */
  12668. get: function () {
  12669. return this._webGLVersion < 2 || this.forcePOTTextures;
  12670. },
  12671. enumerable: true,
  12672. configurable: true
  12673. });
  12674. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12675. /**
  12676. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12677. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12678. */
  12679. get: function () {
  12680. return this._doNotHandleContextLost;
  12681. },
  12682. set: function (value) {
  12683. this._doNotHandleContextLost = value;
  12684. },
  12685. enumerable: true,
  12686. configurable: true
  12687. });
  12688. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12689. /**
  12690. * Gets the performance monitor attached to this engine
  12691. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12692. */
  12693. get: function () {
  12694. return this._performanceMonitor;
  12695. },
  12696. enumerable: true,
  12697. configurable: true
  12698. });
  12699. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12700. /**
  12701. * Gets the list of texture formats supported
  12702. */
  12703. get: function () {
  12704. return this._texturesSupported;
  12705. },
  12706. enumerable: true,
  12707. configurable: true
  12708. });
  12709. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12710. /**
  12711. * Gets the list of texture formats in use
  12712. */
  12713. get: function () {
  12714. return this._textureFormatInUse;
  12715. },
  12716. enumerable: true,
  12717. configurable: true
  12718. });
  12719. Object.defineProperty(Engine.prototype, "currentViewport", {
  12720. /**
  12721. * Gets the current viewport
  12722. */
  12723. get: function () {
  12724. return this._cachedViewport;
  12725. },
  12726. enumerable: true,
  12727. configurable: true
  12728. });
  12729. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12730. /**
  12731. * Gets the default empty texture
  12732. */
  12733. get: function () {
  12734. if (!this._emptyTexture) {
  12735. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12736. }
  12737. return this._emptyTexture;
  12738. },
  12739. enumerable: true,
  12740. configurable: true
  12741. });
  12742. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12743. /**
  12744. * Gets the default empty 3D texture
  12745. */
  12746. get: function () {
  12747. if (!this._emptyTexture3D) {
  12748. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12749. }
  12750. return this._emptyTexture3D;
  12751. },
  12752. enumerable: true,
  12753. configurable: true
  12754. });
  12755. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12756. /**
  12757. * Gets the default empty cube texture
  12758. */
  12759. get: function () {
  12760. if (!this._emptyCubeTexture) {
  12761. var faceData = new Uint8Array(4);
  12762. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12763. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12764. }
  12765. return this._emptyCubeTexture;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Engine.prototype._rebuildInternalTextures = function () {
  12771. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12772. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12773. var internalTexture = currentState_1[_i];
  12774. internalTexture._rebuild();
  12775. }
  12776. };
  12777. Engine.prototype._rebuildEffects = function () {
  12778. for (var key in this._compiledEffects) {
  12779. var effect = this._compiledEffects[key];
  12780. effect._prepareEffect();
  12781. }
  12782. BABYLON.Effect.ResetCache();
  12783. };
  12784. Engine.prototype._rebuildBuffers = function () {
  12785. // Index / Vertex
  12786. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12787. var scene = _a[_i];
  12788. scene.resetCachedMaterial();
  12789. scene._rebuildGeometries();
  12790. scene._rebuildTextures();
  12791. }
  12792. // Uniforms
  12793. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12794. var uniformBuffer = _c[_b];
  12795. uniformBuffer._rebuild();
  12796. }
  12797. };
  12798. Engine.prototype._initGLContext = function () {
  12799. // Caps
  12800. this._caps = new EngineCapabilities();
  12801. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12802. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12803. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12804. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12805. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12806. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12807. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12808. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12809. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12810. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12811. // Infos
  12812. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12813. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12814. if (rendererInfo != null) {
  12815. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12816. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12817. }
  12818. if (!this._glVendor) {
  12819. this._glVendor = "Unknown vendor";
  12820. }
  12821. if (!this._glRenderer) {
  12822. this._glRenderer = "Unknown renderer";
  12823. }
  12824. // Constants
  12825. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12826. if (this._gl.RGBA16F !== 0x881A) {
  12827. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12828. }
  12829. if (this._gl.RGBA32F !== 0x8814) {
  12830. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12831. }
  12832. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12833. this._gl.DEPTH24_STENCIL8 = 35056;
  12834. }
  12835. // Extensions
  12836. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12837. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12838. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12839. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12840. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12841. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12842. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12843. 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');
  12844. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12845. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12846. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12847. this._caps.highPrecisionShaderSupported = true;
  12848. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12849. if (this._caps.timerQuery) {
  12850. if (this._webGLVersion === 1) {
  12851. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12852. }
  12853. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12854. }
  12855. // Checks if some of the format renders first to allow the use of webgl inspector.
  12856. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12857. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12858. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12859. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12860. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12861. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12862. if (this._webGLVersion > 1) {
  12863. this._gl.HALF_FLOAT_OES = 0x140B;
  12864. }
  12865. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12866. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12867. // Draw buffers
  12868. if (this._webGLVersion > 1) {
  12869. this._caps.drawBuffersExtension = true;
  12870. }
  12871. else {
  12872. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12873. if (drawBuffersExtension !== null) {
  12874. this._caps.drawBuffersExtension = true;
  12875. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12876. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12877. for (var i = 0; i < 16; i++) {
  12878. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12879. }
  12880. }
  12881. else {
  12882. this._caps.drawBuffersExtension = false;
  12883. }
  12884. }
  12885. // Depth Texture
  12886. if (this._webGLVersion > 1) {
  12887. this._caps.depthTextureExtension = true;
  12888. }
  12889. else {
  12890. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12891. if (depthTextureExtension != null) {
  12892. this._caps.depthTextureExtension = true;
  12893. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12894. }
  12895. }
  12896. // Vertex array object
  12897. if (this._webGLVersion > 1) {
  12898. this._caps.vertexArrayObject = true;
  12899. }
  12900. else {
  12901. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12902. if (vertexArrayObjectExtension != null) {
  12903. this._caps.vertexArrayObject = true;
  12904. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12905. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12906. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12907. }
  12908. else {
  12909. this._caps.vertexArrayObject = false;
  12910. }
  12911. }
  12912. // Instances count
  12913. if (this._webGLVersion > 1) {
  12914. this._caps.instancedArrays = true;
  12915. }
  12916. else {
  12917. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12918. if (instanceExtension != null) {
  12919. this._caps.instancedArrays = true;
  12920. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12921. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12922. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12923. }
  12924. else {
  12925. this._caps.instancedArrays = false;
  12926. }
  12927. }
  12928. // Intelligently add supported compressed formats in order to check for.
  12929. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12930. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12931. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12932. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12933. if (this._caps.astc) {
  12934. this.texturesSupported.push('-astc.ktx');
  12935. }
  12936. if (this._caps.s3tc) {
  12937. this.texturesSupported.push('-dxt.ktx');
  12938. }
  12939. if (this._caps.pvrtc) {
  12940. this.texturesSupported.push('-pvrtc.ktx');
  12941. }
  12942. if (this._caps.etc2) {
  12943. this.texturesSupported.push('-etc2.ktx');
  12944. }
  12945. if (this._caps.etc1) {
  12946. this.texturesSupported.push('-etc1.ktx');
  12947. }
  12948. if (this._gl.getShaderPrecisionFormat) {
  12949. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12950. if (highp) {
  12951. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12952. }
  12953. }
  12954. // Depth buffer
  12955. this.setDepthBuffer(true);
  12956. this.setDepthFunctionToLessOrEqual();
  12957. this.setDepthWrite(true);
  12958. // Texture maps
  12959. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12960. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12961. this._nextFreeTextureSlots.push(slot);
  12962. }
  12963. };
  12964. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12965. /**
  12966. * Gets version of the current webGL context
  12967. */
  12968. get: function () {
  12969. return this._webGLVersion;
  12970. },
  12971. enumerable: true,
  12972. configurable: true
  12973. });
  12974. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12975. /**
  12976. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12977. */
  12978. get: function () {
  12979. return this._isStencilEnable;
  12980. },
  12981. enumerable: true,
  12982. configurable: true
  12983. });
  12984. Engine.prototype._prepareWorkingCanvas = function () {
  12985. if (this._workingCanvas) {
  12986. return;
  12987. }
  12988. this._workingCanvas = document.createElement("canvas");
  12989. var context = this._workingCanvas.getContext("2d");
  12990. if (context) {
  12991. this._workingContext = context;
  12992. }
  12993. };
  12994. /**
  12995. * Reset the texture cache to empty state
  12996. */
  12997. Engine.prototype.resetTextureCache = function () {
  12998. for (var key in this._boundTexturesCache) {
  12999. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13000. continue;
  13001. }
  13002. var boundTexture = this._boundTexturesCache[key];
  13003. if (boundTexture) {
  13004. this._removeDesignatedSlot(boundTexture);
  13005. }
  13006. this._boundTexturesCache[key] = null;
  13007. }
  13008. if (!this.disableTextureBindingOptimization) {
  13009. this._nextFreeTextureSlots = [];
  13010. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13011. this._nextFreeTextureSlots.push(slot);
  13012. }
  13013. }
  13014. this._currentTextureChannel = -1;
  13015. };
  13016. /**
  13017. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13018. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13019. * @returns true if engine is in deterministic lock step mode
  13020. */
  13021. Engine.prototype.isDeterministicLockStep = function () {
  13022. return this._deterministicLockstep;
  13023. };
  13024. /**
  13025. * Gets the max steps when engine is running in deterministic lock step
  13026. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13027. * @returns the max steps
  13028. */
  13029. Engine.prototype.getLockstepMaxSteps = function () {
  13030. return this._lockstepMaxSteps;
  13031. };
  13032. /**
  13033. * Gets an object containing information about the current webGL context
  13034. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13035. */
  13036. Engine.prototype.getGlInfo = function () {
  13037. return {
  13038. vendor: this._glVendor,
  13039. renderer: this._glRenderer,
  13040. version: this._glVersion
  13041. };
  13042. };
  13043. /**
  13044. * Gets current aspect ratio
  13045. * @param camera defines the camera to use to get the aspect ratio
  13046. * @param useScreen defines if screen size must be used (or the current render target if any)
  13047. * @returns a number defining the aspect ratio
  13048. */
  13049. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13050. if (useScreen === void 0) { useScreen = false; }
  13051. var viewport = camera.viewport;
  13052. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13053. };
  13054. /**
  13055. * Gets current screen aspect ratio
  13056. * @returns a number defining the aspect ratio
  13057. */
  13058. Engine.prototype.getScreenAspectRatio = function () {
  13059. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13060. };
  13061. /**
  13062. * Gets the current render width
  13063. * @param useScreen defines if screen size must be used (or the current render target if any)
  13064. * @returns a number defining the current render width
  13065. */
  13066. Engine.prototype.getRenderWidth = function (useScreen) {
  13067. if (useScreen === void 0) { useScreen = false; }
  13068. if (!useScreen && this._currentRenderTarget) {
  13069. return this._currentRenderTarget.width;
  13070. }
  13071. return this._gl.drawingBufferWidth;
  13072. };
  13073. /**
  13074. * Gets the current render height
  13075. * @param useScreen defines if screen size must be used (or the current render target if any)
  13076. * @returns a number defining the current render height
  13077. */
  13078. Engine.prototype.getRenderHeight = function (useScreen) {
  13079. if (useScreen === void 0) { useScreen = false; }
  13080. if (!useScreen && this._currentRenderTarget) {
  13081. return this._currentRenderTarget.height;
  13082. }
  13083. return this._gl.drawingBufferHeight;
  13084. };
  13085. /**
  13086. * Gets the HTML canvas attached with the current webGL context
  13087. * @returns a HTML canvas
  13088. */
  13089. Engine.prototype.getRenderingCanvas = function () {
  13090. return this._renderingCanvas;
  13091. };
  13092. /**
  13093. * Gets the client rect of the HTML canvas attached with the current webGL context
  13094. * @returns a client rectanglee
  13095. */
  13096. Engine.prototype.getRenderingCanvasClientRect = function () {
  13097. if (!this._renderingCanvas) {
  13098. return null;
  13099. }
  13100. return this._renderingCanvas.getBoundingClientRect();
  13101. };
  13102. /**
  13103. * Defines the hardware scaling level.
  13104. * By default the hardware scaling level is computed from the window device ratio.
  13105. * 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.
  13106. * @param level defines the level to use
  13107. */
  13108. Engine.prototype.setHardwareScalingLevel = function (level) {
  13109. this._hardwareScalingLevel = level;
  13110. this.resize();
  13111. };
  13112. /**
  13113. * Gets the current hardware scaling level.
  13114. * By default the hardware scaling level is computed from the window device ratio.
  13115. * 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.
  13116. * @returns a number indicating the current hardware scaling level
  13117. */
  13118. Engine.prototype.getHardwareScalingLevel = function () {
  13119. return this._hardwareScalingLevel;
  13120. };
  13121. /**
  13122. * Gets the list of loaded textures
  13123. * @returns an array containing all loaded textures
  13124. */
  13125. Engine.prototype.getLoadedTexturesCache = function () {
  13126. return this._internalTexturesCache;
  13127. };
  13128. /**
  13129. * Gets the object containing all engine capabilities
  13130. * @returns the EngineCapabilities object
  13131. */
  13132. Engine.prototype.getCaps = function () {
  13133. return this._caps;
  13134. };
  13135. Object.defineProperty(Engine.prototype, "drawCalls", {
  13136. /** @hidden */
  13137. get: function () {
  13138. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13139. return 0;
  13140. },
  13141. enumerable: true,
  13142. configurable: true
  13143. });
  13144. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13145. /** @hidden */
  13146. get: function () {
  13147. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13148. return null;
  13149. },
  13150. enumerable: true,
  13151. configurable: true
  13152. });
  13153. /**
  13154. * Gets the current depth function
  13155. * @returns a number defining the depth function
  13156. */
  13157. Engine.prototype.getDepthFunction = function () {
  13158. return this._depthCullingState.depthFunc;
  13159. };
  13160. /**
  13161. * Sets the current depth function
  13162. * @param depthFunc defines the function to use
  13163. */
  13164. Engine.prototype.setDepthFunction = function (depthFunc) {
  13165. this._depthCullingState.depthFunc = depthFunc;
  13166. };
  13167. /**
  13168. * Sets the current depth function to GREATER
  13169. */
  13170. Engine.prototype.setDepthFunctionToGreater = function () {
  13171. this._depthCullingState.depthFunc = this._gl.GREATER;
  13172. };
  13173. /**
  13174. * Sets the current depth function to GEQUAL
  13175. */
  13176. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13177. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13178. };
  13179. /**
  13180. * Sets the current depth function to LESS
  13181. */
  13182. Engine.prototype.setDepthFunctionToLess = function () {
  13183. this._depthCullingState.depthFunc = this._gl.LESS;
  13184. };
  13185. /**
  13186. * Sets the current depth function to LEQUAL
  13187. */
  13188. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13189. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13190. };
  13191. /**
  13192. * Gets a boolean indicating if stencil buffer is enabled
  13193. * @returns the current stencil buffer state
  13194. */
  13195. Engine.prototype.getStencilBuffer = function () {
  13196. return this._stencilState.stencilTest;
  13197. };
  13198. /**
  13199. * Enable or disable the stencil buffer
  13200. * @param enable defines if the stencil buffer must be enabled or disabled
  13201. */
  13202. Engine.prototype.setStencilBuffer = function (enable) {
  13203. this._stencilState.stencilTest = enable;
  13204. };
  13205. /**
  13206. * Gets the current stencil mask
  13207. * @returns a number defining the new stencil mask to use
  13208. */
  13209. Engine.prototype.getStencilMask = function () {
  13210. return this._stencilState.stencilMask;
  13211. };
  13212. /**
  13213. * Sets the current stencil mask
  13214. * @param mask defines the new stencil mask to use
  13215. */
  13216. Engine.prototype.setStencilMask = function (mask) {
  13217. this._stencilState.stencilMask = mask;
  13218. };
  13219. /**
  13220. * Gets the current stencil function
  13221. * @returns a number defining the stencil function to use
  13222. */
  13223. Engine.prototype.getStencilFunction = function () {
  13224. return this._stencilState.stencilFunc;
  13225. };
  13226. /**
  13227. * Gets the current stencil reference value
  13228. * @returns a number defining the stencil reference value to use
  13229. */
  13230. Engine.prototype.getStencilFunctionReference = function () {
  13231. return this._stencilState.stencilFuncRef;
  13232. };
  13233. /**
  13234. * Gets the current stencil mask
  13235. * @returns a number defining the stencil mask to use
  13236. */
  13237. Engine.prototype.getStencilFunctionMask = function () {
  13238. return this._stencilState.stencilFuncMask;
  13239. };
  13240. /**
  13241. * Sets the current stencil function
  13242. * @param stencilFunc defines the new stencil function to use
  13243. */
  13244. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13245. this._stencilState.stencilFunc = stencilFunc;
  13246. };
  13247. /**
  13248. * Sets the current stencil reference
  13249. * @param reference defines the new stencil reference to use
  13250. */
  13251. Engine.prototype.setStencilFunctionReference = function (reference) {
  13252. this._stencilState.stencilFuncRef = reference;
  13253. };
  13254. /**
  13255. * Sets the current stencil mask
  13256. * @param mask defines the new stencil mask to use
  13257. */
  13258. Engine.prototype.setStencilFunctionMask = function (mask) {
  13259. this._stencilState.stencilFuncMask = mask;
  13260. };
  13261. /**
  13262. * Gets the current stencil operation when stencil fails
  13263. * @returns a number defining stencil operation to use when stencil fails
  13264. */
  13265. Engine.prototype.getStencilOperationFail = function () {
  13266. return this._stencilState.stencilOpStencilFail;
  13267. };
  13268. /**
  13269. * Gets the current stencil operation when depth fails
  13270. * @returns a number defining stencil operation to use when depth fails
  13271. */
  13272. Engine.prototype.getStencilOperationDepthFail = function () {
  13273. return this._stencilState.stencilOpDepthFail;
  13274. };
  13275. /**
  13276. * Gets the current stencil operation when stencil passes
  13277. * @returns a number defining stencil operation to use when stencil passes
  13278. */
  13279. Engine.prototype.getStencilOperationPass = function () {
  13280. return this._stencilState.stencilOpStencilDepthPass;
  13281. };
  13282. /**
  13283. * Sets the stencil operation to use when stencil fails
  13284. * @param operation defines the stencil operation to use when stencil fails
  13285. */
  13286. Engine.prototype.setStencilOperationFail = function (operation) {
  13287. this._stencilState.stencilOpStencilFail = operation;
  13288. };
  13289. /**
  13290. * Sets the stencil operation to use when depth fails
  13291. * @param operation defines the stencil operation to use when depth fails
  13292. */
  13293. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13294. this._stencilState.stencilOpDepthFail = operation;
  13295. };
  13296. /**
  13297. * Sets the stencil operation to use when stencil passes
  13298. * @param operation defines the stencil operation to use when stencil passes
  13299. */
  13300. Engine.prototype.setStencilOperationPass = function (operation) {
  13301. this._stencilState.stencilOpStencilDepthPass = operation;
  13302. };
  13303. /**
  13304. * Sets a boolean indicating if the dithering state is enabled or disabled
  13305. * @param value defines the dithering state
  13306. */
  13307. Engine.prototype.setDitheringState = function (value) {
  13308. if (value) {
  13309. this._gl.enable(this._gl.DITHER);
  13310. }
  13311. else {
  13312. this._gl.disable(this._gl.DITHER);
  13313. }
  13314. };
  13315. /**
  13316. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13317. * @param value defines the rasterizer state
  13318. */
  13319. Engine.prototype.setRasterizerState = function (value) {
  13320. if (value) {
  13321. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13322. }
  13323. else {
  13324. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13325. }
  13326. };
  13327. /**
  13328. * stop executing a render loop function and remove it from the execution array
  13329. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13330. */
  13331. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13332. if (!renderFunction) {
  13333. this._activeRenderLoops = [];
  13334. return;
  13335. }
  13336. var index = this._activeRenderLoops.indexOf(renderFunction);
  13337. if (index >= 0) {
  13338. this._activeRenderLoops.splice(index, 1);
  13339. }
  13340. };
  13341. /** @hidden */
  13342. Engine.prototype._renderLoop = function () {
  13343. if (!this._contextWasLost) {
  13344. var shouldRender = true;
  13345. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13346. shouldRender = false;
  13347. }
  13348. if (shouldRender) {
  13349. // Start new frame
  13350. this.beginFrame();
  13351. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13352. var renderFunction = this._activeRenderLoops[index];
  13353. renderFunction();
  13354. }
  13355. // Present
  13356. this.endFrame();
  13357. }
  13358. }
  13359. if (this._activeRenderLoops.length > 0) {
  13360. // Register new frame
  13361. var requester = null;
  13362. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13363. requester = this._vrDisplay;
  13364. }
  13365. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13366. }
  13367. else {
  13368. this._renderingQueueLaunched = false;
  13369. }
  13370. };
  13371. /**
  13372. * Register and execute a render loop. The engine can have more than one render function
  13373. * @param renderFunction defines the function to continuously execute
  13374. */
  13375. Engine.prototype.runRenderLoop = function (renderFunction) {
  13376. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13377. return;
  13378. }
  13379. this._activeRenderLoops.push(renderFunction);
  13380. if (!this._renderingQueueLaunched) {
  13381. this._renderingQueueLaunched = true;
  13382. this._bindedRenderFunction = this._renderLoop.bind(this);
  13383. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13384. }
  13385. };
  13386. /**
  13387. * Toggle full screen mode
  13388. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13389. */
  13390. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13391. if (this.isFullscreen) {
  13392. BABYLON.Tools.ExitFullscreen();
  13393. }
  13394. else {
  13395. this._pointerLockRequested = requestPointerLock;
  13396. if (this._renderingCanvas) {
  13397. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13398. }
  13399. }
  13400. };
  13401. /**
  13402. * Clear the current render buffer or the current render target (if any is set up)
  13403. * @param color defines the color to use
  13404. * @param backBuffer defines if the back buffer must be cleared
  13405. * @param depth defines if the depth buffer must be cleared
  13406. * @param stencil defines if the stencil buffer must be cleared
  13407. */
  13408. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13409. if (stencil === void 0) { stencil = false; }
  13410. this.applyStates();
  13411. var mode = 0;
  13412. if (backBuffer && color) {
  13413. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13414. mode |= this._gl.COLOR_BUFFER_BIT;
  13415. }
  13416. if (depth) {
  13417. this._gl.clearDepth(1.0);
  13418. mode |= this._gl.DEPTH_BUFFER_BIT;
  13419. }
  13420. if (stencil) {
  13421. this._gl.clearStencil(0);
  13422. mode |= this._gl.STENCIL_BUFFER_BIT;
  13423. }
  13424. this._gl.clear(mode);
  13425. };
  13426. /**
  13427. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13428. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13429. * @param y defines the y-coordinate of the corner of the clear rectangle
  13430. * @param width defines the width of the clear rectangle
  13431. * @param height defines the height of the clear rectangle
  13432. * @param clearColor defines the clear color
  13433. */
  13434. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13435. var gl = this._gl;
  13436. // Save state
  13437. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13438. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13439. // Change state
  13440. gl.enable(gl.SCISSOR_TEST);
  13441. gl.scissor(x, y, width, height);
  13442. // Clear
  13443. this.clear(clearColor, true, true, true);
  13444. // Restore state
  13445. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13446. if (curScissor === true) {
  13447. gl.enable(gl.SCISSOR_TEST);
  13448. }
  13449. else {
  13450. gl.disable(gl.SCISSOR_TEST);
  13451. }
  13452. };
  13453. /** @hidden */
  13454. Engine.prototype._viewport = function (x, y, width, height) {
  13455. if (x !== this._viewportCached.x ||
  13456. y !== this._viewportCached.y ||
  13457. width !== this._viewportCached.z ||
  13458. height !== this._viewportCached.w) {
  13459. this._viewportCached.x = x;
  13460. this._viewportCached.y = y;
  13461. this._viewportCached.z = width;
  13462. this._viewportCached.w = height;
  13463. this._gl.viewport(x, y, width, height);
  13464. }
  13465. };
  13466. /**
  13467. * Set the WebGL's viewport
  13468. * @param viewport defines the viewport element to be used
  13469. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13470. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13471. */
  13472. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13473. var width = requiredWidth || this.getRenderWidth();
  13474. var height = requiredHeight || this.getRenderHeight();
  13475. var x = viewport.x || 0;
  13476. var y = viewport.y || 0;
  13477. this._cachedViewport = viewport;
  13478. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13479. };
  13480. /**
  13481. * Directly set the WebGL Viewport
  13482. * @param x defines the x coordinate of the viewport (in screen space)
  13483. * @param y defines the y coordinate of the viewport (in screen space)
  13484. * @param width defines the width of the viewport (in screen space)
  13485. * @param height defines the height of the viewport (in screen space)
  13486. * @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
  13487. */
  13488. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13489. var currentViewport = this._cachedViewport;
  13490. this._cachedViewport = null;
  13491. this._viewport(x, y, width, height);
  13492. return currentViewport;
  13493. };
  13494. /**
  13495. * Begin a new frame
  13496. */
  13497. Engine.prototype.beginFrame = function () {
  13498. this.onBeginFrameObservable.notifyObservers(this);
  13499. this._measureFps();
  13500. };
  13501. /**
  13502. * Enf the current frame
  13503. */
  13504. Engine.prototype.endFrame = function () {
  13505. // Force a flush in case we are using a bad OS.
  13506. if (this._badOS) {
  13507. this.flushFramebuffer();
  13508. }
  13509. // Submit frame to the vr device, if enabled
  13510. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13511. // TODO: We should only submit the frame if we read frameData successfully.
  13512. this._vrDisplay.submitFrame();
  13513. }
  13514. this.onEndFrameObservable.notifyObservers(this);
  13515. };
  13516. /**
  13517. * Resize the view according to the canvas' size
  13518. */
  13519. Engine.prototype.resize = function () {
  13520. // We're not resizing the size of the canvas while in VR mode & presenting
  13521. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13522. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13523. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13524. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13525. }
  13526. };
  13527. /**
  13528. * Force a specific size of the canvas
  13529. * @param width defines the new canvas' width
  13530. * @param height defines the new canvas' height
  13531. */
  13532. Engine.prototype.setSize = function (width, height) {
  13533. if (!this._renderingCanvas) {
  13534. return;
  13535. }
  13536. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13537. return;
  13538. }
  13539. this._renderingCanvas.width = width;
  13540. this._renderingCanvas.height = height;
  13541. for (var index = 0; index < this.scenes.length; index++) {
  13542. var scene = this.scenes[index];
  13543. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13544. var cam = scene.cameras[camIndex];
  13545. cam._currentRenderId = 0;
  13546. }
  13547. }
  13548. if (this.onResizeObservable.hasObservers) {
  13549. this.onResizeObservable.notifyObservers(this);
  13550. }
  13551. };
  13552. // WebVR functions
  13553. /**
  13554. * Gets a boolean indicating if a webVR device was detected
  13555. * @returns true if a webVR device was detected
  13556. */
  13557. Engine.prototype.isVRDevicePresent = function () {
  13558. return !!this._vrDisplay;
  13559. };
  13560. /**
  13561. * Gets the current webVR device
  13562. * @returns the current webVR device (or null)
  13563. */
  13564. Engine.prototype.getVRDevice = function () {
  13565. return this._vrDisplay;
  13566. };
  13567. /**
  13568. * Initializes a webVR display and starts listening to display change events
  13569. * The onVRDisplayChangedObservable will be notified upon these changes
  13570. * @returns The onVRDisplayChangedObservable
  13571. */
  13572. Engine.prototype.initWebVR = function () {
  13573. this.initWebVRAsync();
  13574. return this.onVRDisplayChangedObservable;
  13575. };
  13576. /**
  13577. * Initializes a webVR display and starts listening to display change events
  13578. * The onVRDisplayChangedObservable will be notified upon these changes
  13579. * @returns A promise containing a VRDisplay and if vr is supported
  13580. */
  13581. Engine.prototype.initWebVRAsync = function () {
  13582. var _this = this;
  13583. var notifyObservers = function () {
  13584. var eventArgs = {
  13585. vrDisplay: _this._vrDisplay,
  13586. vrSupported: _this._vrSupported
  13587. };
  13588. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13589. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13590. };
  13591. if (!this._onVrDisplayConnect) {
  13592. this._onVrDisplayConnect = function (event) {
  13593. _this._vrDisplay = event.display;
  13594. notifyObservers();
  13595. };
  13596. this._onVrDisplayDisconnect = function () {
  13597. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13598. _this._vrDisplay = undefined;
  13599. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13600. notifyObservers();
  13601. };
  13602. this._onVrDisplayPresentChange = function () {
  13603. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13604. };
  13605. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13606. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13607. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13608. }
  13609. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13610. this._webVRInitPromise.then(notifyObservers);
  13611. return this._webVRInitPromise;
  13612. };
  13613. /**
  13614. * Call this function to switch to webVR mode
  13615. * Will do nothing if webVR is not supported or if there is no webVR device
  13616. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13617. */
  13618. Engine.prototype.enableVR = function () {
  13619. var _this = this;
  13620. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13621. var onResolved = function () {
  13622. _this.onVRRequestPresentComplete.notifyObservers(true);
  13623. _this._onVRFullScreenTriggered();
  13624. };
  13625. var onRejected = function () {
  13626. _this.onVRRequestPresentComplete.notifyObservers(false);
  13627. };
  13628. this.onVRRequestPresentStart.notifyObservers(this);
  13629. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13630. }
  13631. };
  13632. /**
  13633. * Call this function to leave webVR mode
  13634. * Will do nothing if webVR is not supported or if there is no webVR device
  13635. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13636. */
  13637. Engine.prototype.disableVR = function () {
  13638. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13639. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13640. }
  13641. };
  13642. Engine.prototype._getVRDisplaysAsync = function () {
  13643. var _this = this;
  13644. return new Promise(function (res, rej) {
  13645. if (navigator.getVRDisplays) {
  13646. navigator.getVRDisplays().then(function (devices) {
  13647. _this._vrSupported = true;
  13648. // note that devices may actually be an empty array. This is fine;
  13649. // we expect this._vrDisplay to be undefined in this case.
  13650. _this._vrDisplay = devices[0];
  13651. res({
  13652. vrDisplay: _this._vrDisplay,
  13653. vrSupported: _this._vrSupported
  13654. });
  13655. });
  13656. }
  13657. else {
  13658. _this._vrDisplay = undefined;
  13659. _this._vrSupported = false;
  13660. res({
  13661. vrDisplay: _this._vrDisplay,
  13662. vrSupported: _this._vrSupported
  13663. });
  13664. }
  13665. });
  13666. };
  13667. /**
  13668. * Binds the frame buffer to the specified texture.
  13669. * @param texture The texture to render to or null for the default canvas
  13670. * @param faceIndex The face of the texture to render to in case of cube texture
  13671. * @param requiredWidth The width of the target to render to
  13672. * @param requiredHeight The height of the target to render to
  13673. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13674. * @param depthStencilTexture The depth stencil texture to use to render
  13675. * @param lodLevel defines le lod level to bind to the frame buffer
  13676. */
  13677. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13678. if (lodLevel === void 0) { lodLevel = 0; }
  13679. if (this._currentRenderTarget) {
  13680. this.unBindFramebuffer(this._currentRenderTarget);
  13681. }
  13682. this._currentRenderTarget = texture;
  13683. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13684. var gl = this._gl;
  13685. if (texture.isCube) {
  13686. if (faceIndex === undefined) {
  13687. faceIndex = 0;
  13688. }
  13689. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13690. if (depthStencilTexture) {
  13691. if (depthStencilTexture._generateStencilBuffer) {
  13692. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13693. }
  13694. else {
  13695. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13696. }
  13697. }
  13698. }
  13699. if (this._cachedViewport && !forceFullscreenViewport) {
  13700. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13701. }
  13702. else {
  13703. if (!requiredWidth) {
  13704. requiredWidth = texture.width;
  13705. if (lodLevel) {
  13706. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13707. }
  13708. }
  13709. if (!requiredHeight) {
  13710. requiredHeight = texture.height;
  13711. if (lodLevel) {
  13712. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13713. }
  13714. }
  13715. this._viewport(0, 0, requiredWidth, requiredHeight);
  13716. }
  13717. this.wipeCaches();
  13718. };
  13719. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13720. if (this._currentFramebuffer !== framebuffer) {
  13721. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13722. this._currentFramebuffer = framebuffer;
  13723. }
  13724. };
  13725. /**
  13726. * Unbind the current render target texture from the webGL context
  13727. * @param texture defines the render target texture to unbind
  13728. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13729. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13730. */
  13731. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13732. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13733. this._currentRenderTarget = null;
  13734. // If MSAA, we need to bitblt back to main texture
  13735. var gl = this._gl;
  13736. if (texture._MSAAFramebuffer) {
  13737. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13738. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13739. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13740. }
  13741. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13742. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13743. gl.generateMipmap(gl.TEXTURE_2D);
  13744. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13745. }
  13746. if (onBeforeUnbind) {
  13747. if (texture._MSAAFramebuffer) {
  13748. // Bind the correct framebuffer
  13749. this.bindUnboundFramebuffer(texture._framebuffer);
  13750. }
  13751. onBeforeUnbind();
  13752. }
  13753. this.bindUnboundFramebuffer(null);
  13754. };
  13755. /**
  13756. * Unbind a list of render target textures from the webGL context
  13757. * This is used only when drawBuffer extension or webGL2 are active
  13758. * @param textures defines the render target textures to unbind
  13759. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13760. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13761. */
  13762. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13763. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13764. this._currentRenderTarget = null;
  13765. // If MSAA, we need to bitblt back to main texture
  13766. var gl = this._gl;
  13767. if (textures[0]._MSAAFramebuffer) {
  13768. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13769. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13770. var attachments = textures[0]._attachments;
  13771. if (!attachments) {
  13772. attachments = new Array(textures.length);
  13773. textures[0]._attachments = attachments;
  13774. }
  13775. for (var i = 0; i < textures.length; i++) {
  13776. var texture = textures[i];
  13777. for (var j = 0; j < attachments.length; j++) {
  13778. attachments[j] = gl.NONE;
  13779. }
  13780. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13781. gl.readBuffer(attachments[i]);
  13782. gl.drawBuffers(attachments);
  13783. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13784. }
  13785. for (var i = 0; i < attachments.length; i++) {
  13786. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13787. }
  13788. gl.drawBuffers(attachments);
  13789. }
  13790. for (var i = 0; i < textures.length; i++) {
  13791. var texture = textures[i];
  13792. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13793. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13794. gl.generateMipmap(gl.TEXTURE_2D);
  13795. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13796. }
  13797. }
  13798. if (onBeforeUnbind) {
  13799. if (textures[0]._MSAAFramebuffer) {
  13800. // Bind the correct framebuffer
  13801. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13802. }
  13803. onBeforeUnbind();
  13804. }
  13805. this.bindUnboundFramebuffer(null);
  13806. };
  13807. /**
  13808. * Force the mipmap generation for the given render target texture
  13809. * @param texture defines the render target texture to use
  13810. */
  13811. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13812. if (texture.generateMipMaps) {
  13813. var gl = this._gl;
  13814. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13815. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13816. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13817. }
  13818. };
  13819. /**
  13820. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13821. */
  13822. Engine.prototype.flushFramebuffer = function () {
  13823. this._gl.flush();
  13824. };
  13825. /**
  13826. * Unbind the current render target and bind the default framebuffer
  13827. */
  13828. Engine.prototype.restoreDefaultFramebuffer = function () {
  13829. if (this._currentRenderTarget) {
  13830. this.unBindFramebuffer(this._currentRenderTarget);
  13831. }
  13832. else {
  13833. this.bindUnboundFramebuffer(null);
  13834. }
  13835. if (this._cachedViewport) {
  13836. this.setViewport(this._cachedViewport);
  13837. }
  13838. this.wipeCaches();
  13839. };
  13840. // UBOs
  13841. /**
  13842. * Create an uniform buffer
  13843. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13844. * @param elements defines the content of the uniform buffer
  13845. * @returns the webGL uniform buffer
  13846. */
  13847. Engine.prototype.createUniformBuffer = function (elements) {
  13848. var ubo = this._gl.createBuffer();
  13849. if (!ubo) {
  13850. throw new Error("Unable to create uniform buffer");
  13851. }
  13852. this.bindUniformBuffer(ubo);
  13853. if (elements instanceof Float32Array) {
  13854. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13855. }
  13856. else {
  13857. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13858. }
  13859. this.bindUniformBuffer(null);
  13860. ubo.references = 1;
  13861. return ubo;
  13862. };
  13863. /**
  13864. * Create a dynamic uniform buffer
  13865. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13866. * @param elements defines the content of the uniform buffer
  13867. * @returns the webGL uniform buffer
  13868. */
  13869. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13870. var ubo = this._gl.createBuffer();
  13871. if (!ubo) {
  13872. throw new Error("Unable to create dynamic uniform buffer");
  13873. }
  13874. this.bindUniformBuffer(ubo);
  13875. if (elements instanceof Float32Array) {
  13876. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13877. }
  13878. else {
  13879. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13880. }
  13881. this.bindUniformBuffer(null);
  13882. ubo.references = 1;
  13883. return ubo;
  13884. };
  13885. /**
  13886. * Update an existing uniform buffer
  13887. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13888. * @param uniformBuffer defines the target uniform buffer
  13889. * @param elements defines the content to update
  13890. * @param offset defines the offset in the uniform buffer where update should start
  13891. * @param count defines the size of the data to update
  13892. */
  13893. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13894. this.bindUniformBuffer(uniformBuffer);
  13895. if (offset === undefined) {
  13896. offset = 0;
  13897. }
  13898. if (count === undefined) {
  13899. if (elements instanceof Float32Array) {
  13900. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13901. }
  13902. else {
  13903. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13904. }
  13905. }
  13906. else {
  13907. if (elements instanceof Float32Array) {
  13908. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13909. }
  13910. else {
  13911. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13912. }
  13913. }
  13914. this.bindUniformBuffer(null);
  13915. };
  13916. // VBOs
  13917. Engine.prototype._resetVertexBufferBinding = function () {
  13918. this.bindArrayBuffer(null);
  13919. this._cachedVertexBuffers = null;
  13920. };
  13921. /**
  13922. * Creates a vertex buffer
  13923. * @param data the data for the vertex buffer
  13924. * @returns the new WebGL static buffer
  13925. */
  13926. Engine.prototype.createVertexBuffer = function (data) {
  13927. var vbo = this._gl.createBuffer();
  13928. if (!vbo) {
  13929. throw new Error("Unable to create vertex buffer");
  13930. }
  13931. this.bindArrayBuffer(vbo);
  13932. if (data instanceof Array) {
  13933. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13934. }
  13935. else {
  13936. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13937. }
  13938. this._resetVertexBufferBinding();
  13939. vbo.references = 1;
  13940. return vbo;
  13941. };
  13942. /**
  13943. * Creates a dynamic vertex buffer
  13944. * @param data the data for the dynamic vertex buffer
  13945. * @returns the new WebGL dynamic buffer
  13946. */
  13947. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13948. var vbo = this._gl.createBuffer();
  13949. if (!vbo) {
  13950. throw new Error("Unable to create dynamic vertex buffer");
  13951. }
  13952. this.bindArrayBuffer(vbo);
  13953. if (data instanceof Array) {
  13954. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13955. }
  13956. else {
  13957. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13958. }
  13959. this._resetVertexBufferBinding();
  13960. vbo.references = 1;
  13961. return vbo;
  13962. };
  13963. /**
  13964. * Update a dynamic index buffer
  13965. * @param indexBuffer defines the target index buffer
  13966. * @param indices defines the data to update
  13967. * @param offset defines the offset in the target index buffer where update should start
  13968. */
  13969. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13970. if (offset === void 0) { offset = 0; }
  13971. // Force cache update
  13972. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13973. this.bindIndexBuffer(indexBuffer);
  13974. var arrayBuffer;
  13975. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13976. arrayBuffer = indices;
  13977. }
  13978. else {
  13979. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13980. }
  13981. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13982. this._resetIndexBufferBinding();
  13983. };
  13984. /**
  13985. * Updates a dynamic vertex buffer.
  13986. * @param vertexBuffer the vertex buffer to update
  13987. * @param data the data used to update the vertex buffer
  13988. * @param byteOffset the byte offset of the data
  13989. * @param byteLength the byte length of the data
  13990. */
  13991. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13992. this.bindArrayBuffer(vertexBuffer);
  13993. if (byteOffset === undefined) {
  13994. byteOffset = 0;
  13995. }
  13996. if (byteLength === undefined) {
  13997. if (data instanceof Array) {
  13998. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13999. }
  14000. else {
  14001. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14002. }
  14003. }
  14004. else {
  14005. if (data instanceof Array) {
  14006. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14007. }
  14008. else {
  14009. if (data instanceof ArrayBuffer) {
  14010. data = new Uint8Array(data, byteOffset, byteLength);
  14011. }
  14012. else {
  14013. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14014. }
  14015. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14016. }
  14017. }
  14018. this._resetVertexBufferBinding();
  14019. };
  14020. Engine.prototype._resetIndexBufferBinding = function () {
  14021. this.bindIndexBuffer(null);
  14022. this._cachedIndexBuffer = null;
  14023. };
  14024. /**
  14025. * Creates a new index buffer
  14026. * @param indices defines the content of the index buffer
  14027. * @param updatable defines if the index buffer must be updatable
  14028. * @returns a new webGL buffer
  14029. */
  14030. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14031. var vbo = this._gl.createBuffer();
  14032. if (!vbo) {
  14033. throw new Error("Unable to create index buffer");
  14034. }
  14035. this.bindIndexBuffer(vbo);
  14036. // Check for 32 bits indices
  14037. var arrayBuffer;
  14038. var need32Bits = false;
  14039. if (indices instanceof Uint16Array) {
  14040. arrayBuffer = indices;
  14041. }
  14042. else {
  14043. //check 32 bit support
  14044. if (this._caps.uintIndices) {
  14045. if (indices instanceof Uint32Array) {
  14046. arrayBuffer = indices;
  14047. need32Bits = true;
  14048. }
  14049. else {
  14050. //number[] or Int32Array, check if 32 bit is necessary
  14051. for (var index = 0; index < indices.length; index++) {
  14052. if (indices[index] > 65535) {
  14053. need32Bits = true;
  14054. break;
  14055. }
  14056. }
  14057. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14058. }
  14059. }
  14060. else {
  14061. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14062. arrayBuffer = new Uint16Array(indices);
  14063. }
  14064. }
  14065. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14066. this._resetIndexBufferBinding();
  14067. vbo.references = 1;
  14068. vbo.is32Bits = need32Bits;
  14069. return vbo;
  14070. };
  14071. /**
  14072. * Bind a webGL buffer to the webGL context
  14073. * @param buffer defines the buffer to bind
  14074. */
  14075. Engine.prototype.bindArrayBuffer = function (buffer) {
  14076. if (!this._vaoRecordInProgress) {
  14077. this._unbindVertexArrayObject();
  14078. }
  14079. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14080. };
  14081. /**
  14082. * Bind an uniform buffer to the current webGL context
  14083. * @param buffer defines the buffer to bind
  14084. */
  14085. Engine.prototype.bindUniformBuffer = function (buffer) {
  14086. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14087. };
  14088. /**
  14089. * Bind a buffer to the current webGL context at a given location
  14090. * @param buffer defines the buffer to bind
  14091. * @param location defines the index where to bind the buffer
  14092. */
  14093. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14094. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14095. };
  14096. /**
  14097. * Bind a specific block at a given index in a specific shader program
  14098. * @param shaderProgram defines the shader program
  14099. * @param blockName defines the block name
  14100. * @param index defines the index where to bind the block
  14101. */
  14102. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14103. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14104. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14105. };
  14106. Engine.prototype.bindIndexBuffer = function (buffer) {
  14107. if (!this._vaoRecordInProgress) {
  14108. this._unbindVertexArrayObject();
  14109. }
  14110. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14111. };
  14112. Engine.prototype.bindBuffer = function (buffer, target) {
  14113. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14114. this._gl.bindBuffer(target, buffer);
  14115. this._currentBoundBuffer[target] = buffer;
  14116. }
  14117. };
  14118. /**
  14119. * update the bound buffer with the given data
  14120. * @param data defines the data to update
  14121. */
  14122. Engine.prototype.updateArrayBuffer = function (data) {
  14123. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14124. };
  14125. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14126. var pointer = this._currentBufferPointers[indx];
  14127. var changed = false;
  14128. if (!pointer.active) {
  14129. changed = true;
  14130. pointer.active = true;
  14131. pointer.index = indx;
  14132. pointer.size = size;
  14133. pointer.type = type;
  14134. pointer.normalized = normalized;
  14135. pointer.stride = stride;
  14136. pointer.offset = offset;
  14137. pointer.buffer = buffer;
  14138. }
  14139. else {
  14140. if (pointer.buffer !== buffer) {
  14141. pointer.buffer = buffer;
  14142. changed = true;
  14143. }
  14144. if (pointer.size !== size) {
  14145. pointer.size = size;
  14146. changed = true;
  14147. }
  14148. if (pointer.type !== type) {
  14149. pointer.type = type;
  14150. changed = true;
  14151. }
  14152. if (pointer.normalized !== normalized) {
  14153. pointer.normalized = normalized;
  14154. changed = true;
  14155. }
  14156. if (pointer.stride !== stride) {
  14157. pointer.stride = stride;
  14158. changed = true;
  14159. }
  14160. if (pointer.offset !== offset) {
  14161. pointer.offset = offset;
  14162. changed = true;
  14163. }
  14164. }
  14165. if (changed || this._vaoRecordInProgress) {
  14166. this.bindArrayBuffer(buffer);
  14167. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14168. }
  14169. };
  14170. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14171. if (indexBuffer == null) {
  14172. return;
  14173. }
  14174. if (this._cachedIndexBuffer !== indexBuffer) {
  14175. this._cachedIndexBuffer = indexBuffer;
  14176. this.bindIndexBuffer(indexBuffer);
  14177. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14178. }
  14179. };
  14180. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14181. var attributes = effect.getAttributesNames();
  14182. if (!this._vaoRecordInProgress) {
  14183. this._unbindVertexArrayObject();
  14184. }
  14185. this.unbindAllAttributes();
  14186. for (var index = 0; index < attributes.length; index++) {
  14187. var order = effect.getAttributeLocation(index);
  14188. if (order >= 0) {
  14189. var vertexBuffer = vertexBuffers[attributes[index]];
  14190. if (!vertexBuffer) {
  14191. continue;
  14192. }
  14193. this._gl.enableVertexAttribArray(order);
  14194. if (!this._vaoRecordInProgress) {
  14195. this._vertexAttribArraysEnabled[order] = true;
  14196. }
  14197. var buffer = vertexBuffer.getBuffer();
  14198. if (buffer) {
  14199. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14200. if (vertexBuffer.getIsInstanced()) {
  14201. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14202. if (!this._vaoRecordInProgress) {
  14203. this._currentInstanceLocations.push(order);
  14204. this._currentInstanceBuffers.push(buffer);
  14205. }
  14206. }
  14207. }
  14208. }
  14209. }
  14210. };
  14211. /**
  14212. * Records a vertex array object
  14213. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14214. * @param vertexBuffers defines the list of vertex buffers to store
  14215. * @param indexBuffer defines the index buffer to store
  14216. * @param effect defines the effect to store
  14217. * @returns the new vertex array object
  14218. */
  14219. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14220. var vao = this._gl.createVertexArray();
  14221. this._vaoRecordInProgress = true;
  14222. this._gl.bindVertexArray(vao);
  14223. this._mustWipeVertexAttributes = true;
  14224. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14225. this.bindIndexBuffer(indexBuffer);
  14226. this._vaoRecordInProgress = false;
  14227. this._gl.bindVertexArray(null);
  14228. return vao;
  14229. };
  14230. /**
  14231. * Bind a specific vertex array object
  14232. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14233. * @param vertexArrayObject defines the vertex array object to bind
  14234. * @param indexBuffer defines the index buffer to bind
  14235. */
  14236. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14237. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14238. this._cachedVertexArrayObject = vertexArrayObject;
  14239. this._gl.bindVertexArray(vertexArrayObject);
  14240. this._cachedVertexBuffers = null;
  14241. this._cachedIndexBuffer = null;
  14242. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14243. this._mustWipeVertexAttributes = true;
  14244. }
  14245. };
  14246. /**
  14247. * Bind webGl buffers directly to the webGL context
  14248. * @param vertexBuffer defines the vertex buffer to bind
  14249. * @param indexBuffer defines the index buffer to bind
  14250. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14251. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14252. * @param effect defines the effect associated with the vertex buffer
  14253. */
  14254. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14255. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14256. this._cachedVertexBuffers = vertexBuffer;
  14257. this._cachedEffectForVertexBuffers = effect;
  14258. var attributesCount = effect.getAttributesCount();
  14259. this._unbindVertexArrayObject();
  14260. this.unbindAllAttributes();
  14261. var offset = 0;
  14262. for (var index = 0; index < attributesCount; index++) {
  14263. if (index < vertexDeclaration.length) {
  14264. var order = effect.getAttributeLocation(index);
  14265. if (order >= 0) {
  14266. this._gl.enableVertexAttribArray(order);
  14267. this._vertexAttribArraysEnabled[order] = true;
  14268. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14269. }
  14270. offset += vertexDeclaration[index] * 4;
  14271. }
  14272. }
  14273. }
  14274. this._bindIndexBufferWithCache(indexBuffer);
  14275. };
  14276. Engine.prototype._unbindVertexArrayObject = function () {
  14277. if (!this._cachedVertexArrayObject) {
  14278. return;
  14279. }
  14280. this._cachedVertexArrayObject = null;
  14281. this._gl.bindVertexArray(null);
  14282. };
  14283. /**
  14284. * Bind a list of vertex buffers to the webGL context
  14285. * @param vertexBuffers defines the list of vertex buffers to bind
  14286. * @param indexBuffer defines the index buffer to bind
  14287. * @param effect defines the effect associated with the vertex buffers
  14288. */
  14289. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14290. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14291. this._cachedVertexBuffers = vertexBuffers;
  14292. this._cachedEffectForVertexBuffers = effect;
  14293. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14294. }
  14295. this._bindIndexBufferWithCache(indexBuffer);
  14296. };
  14297. /**
  14298. * Unbind all instance attributes
  14299. */
  14300. Engine.prototype.unbindInstanceAttributes = function () {
  14301. var boundBuffer;
  14302. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14303. var instancesBuffer = this._currentInstanceBuffers[i];
  14304. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14305. boundBuffer = instancesBuffer;
  14306. this.bindArrayBuffer(instancesBuffer);
  14307. }
  14308. var offsetLocation = this._currentInstanceLocations[i];
  14309. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14310. }
  14311. this._currentInstanceBuffers.length = 0;
  14312. this._currentInstanceLocations.length = 0;
  14313. };
  14314. /**
  14315. * Release and free the memory of a vertex array object
  14316. * @param vao defines the vertex array object to delete
  14317. */
  14318. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14319. this._gl.deleteVertexArray(vao);
  14320. };
  14321. /** @hidden */
  14322. Engine.prototype._releaseBuffer = function (buffer) {
  14323. buffer.references--;
  14324. if (buffer.references === 0) {
  14325. this._gl.deleteBuffer(buffer);
  14326. return true;
  14327. }
  14328. return false;
  14329. };
  14330. /**
  14331. * Creates a webGL buffer to use with instanciation
  14332. * @param capacity defines the size of the buffer
  14333. * @returns the webGL buffer
  14334. */
  14335. Engine.prototype.createInstancesBuffer = function (capacity) {
  14336. var buffer = this._gl.createBuffer();
  14337. if (!buffer) {
  14338. throw new Error("Unable to create instance buffer");
  14339. }
  14340. buffer.capacity = capacity;
  14341. this.bindArrayBuffer(buffer);
  14342. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14343. return buffer;
  14344. };
  14345. /**
  14346. * Delete a webGL buffer used with instanciation
  14347. * @param buffer defines the webGL buffer to delete
  14348. */
  14349. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14350. this._gl.deleteBuffer(buffer);
  14351. };
  14352. /**
  14353. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14354. * @param instancesBuffer defines the webGL buffer to update and bind
  14355. * @param data defines the data to store in the buffer
  14356. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14357. */
  14358. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14359. this.bindArrayBuffer(instancesBuffer);
  14360. if (data) {
  14361. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14362. }
  14363. if (offsetLocations[0].index !== undefined) {
  14364. var stride = 0;
  14365. for (var i = 0; i < offsetLocations.length; i++) {
  14366. var ai = offsetLocations[i];
  14367. stride += ai.attributeSize * 4;
  14368. }
  14369. for (var i = 0; i < offsetLocations.length; i++) {
  14370. var ai = offsetLocations[i];
  14371. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14372. this._gl.enableVertexAttribArray(ai.index);
  14373. this._vertexAttribArraysEnabled[ai.index] = true;
  14374. }
  14375. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14376. this._gl.vertexAttribDivisor(ai.index, 1);
  14377. this._currentInstanceLocations.push(ai.index);
  14378. this._currentInstanceBuffers.push(instancesBuffer);
  14379. }
  14380. }
  14381. else {
  14382. for (var index = 0; index < 4; index++) {
  14383. var offsetLocation = offsetLocations[index];
  14384. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14385. this._gl.enableVertexAttribArray(offsetLocation);
  14386. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14387. }
  14388. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14389. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14390. this._currentInstanceLocations.push(offsetLocation);
  14391. this._currentInstanceBuffers.push(instancesBuffer);
  14392. }
  14393. }
  14394. };
  14395. /**
  14396. * Apply all cached states (depth, culling, stencil and alpha)
  14397. */
  14398. Engine.prototype.applyStates = function () {
  14399. this._depthCullingState.apply(this._gl);
  14400. this._stencilState.apply(this._gl);
  14401. this._alphaState.apply(this._gl);
  14402. };
  14403. /**
  14404. * Send a draw order
  14405. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14406. * @param indexStart defines the starting index
  14407. * @param indexCount defines the number of index to draw
  14408. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14409. */
  14410. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14411. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14412. };
  14413. /**
  14414. * Draw a list of points
  14415. * @param verticesStart defines the index of first vertex to draw
  14416. * @param verticesCount defines the count of vertices to draw
  14417. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14418. */
  14419. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14420. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14421. };
  14422. /**
  14423. * Draw a list of unindexed primitives
  14424. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14425. * @param verticesStart defines the index of first vertex to draw
  14426. * @param verticesCount defines the count of vertices to draw
  14427. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14428. */
  14429. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14430. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14431. };
  14432. /**
  14433. * Draw a list of indexed primitives
  14434. * @param fillMode defines the primitive to use
  14435. * @param indexStart defines the starting index
  14436. * @param indexCount defines the number of index to draw
  14437. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14438. */
  14439. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14440. // Apply states
  14441. this.applyStates();
  14442. this._drawCalls.addCount(1, false);
  14443. // Render
  14444. var drawMode = this._drawMode(fillMode);
  14445. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14446. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14447. if (instancesCount) {
  14448. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14449. }
  14450. else {
  14451. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14452. }
  14453. };
  14454. /**
  14455. * Draw a list of unindexed primitives
  14456. * @param fillMode defines the primitive to use
  14457. * @param verticesStart defines the index of first vertex to draw
  14458. * @param verticesCount defines the count of vertices to draw
  14459. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14460. */
  14461. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14462. // Apply states
  14463. this.applyStates();
  14464. this._drawCalls.addCount(1, false);
  14465. var drawMode = this._drawMode(fillMode);
  14466. if (instancesCount) {
  14467. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14468. }
  14469. else {
  14470. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14471. }
  14472. };
  14473. Engine.prototype._drawMode = function (fillMode) {
  14474. switch (fillMode) {
  14475. // Triangle views
  14476. case BABYLON.Material.TriangleFillMode:
  14477. return this._gl.TRIANGLES;
  14478. case BABYLON.Material.PointFillMode:
  14479. return this._gl.POINTS;
  14480. case BABYLON.Material.WireFrameFillMode:
  14481. return this._gl.LINES;
  14482. // Draw modes
  14483. case BABYLON.Material.PointListDrawMode:
  14484. return this._gl.POINTS;
  14485. case BABYLON.Material.LineListDrawMode:
  14486. return this._gl.LINES;
  14487. case BABYLON.Material.LineLoopDrawMode:
  14488. return this._gl.LINE_LOOP;
  14489. case BABYLON.Material.LineStripDrawMode:
  14490. return this._gl.LINE_STRIP;
  14491. case BABYLON.Material.TriangleStripDrawMode:
  14492. return this._gl.TRIANGLE_STRIP;
  14493. case BABYLON.Material.TriangleFanDrawMode:
  14494. return this._gl.TRIANGLE_FAN;
  14495. default:
  14496. return this._gl.TRIANGLES;
  14497. }
  14498. };
  14499. // Shaders
  14500. /** @hidden */
  14501. Engine.prototype._releaseEffect = function (effect) {
  14502. if (this._compiledEffects[effect._key]) {
  14503. delete this._compiledEffects[effect._key];
  14504. this._deleteProgram(effect.getProgram());
  14505. }
  14506. };
  14507. /** @hidden */
  14508. Engine.prototype._deleteProgram = function (program) {
  14509. if (program) {
  14510. program.__SPECTOR_rebuildProgram = null;
  14511. if (program.transformFeedback) {
  14512. this.deleteTransformFeedback(program.transformFeedback);
  14513. program.transformFeedback = null;
  14514. }
  14515. this._gl.deleteProgram(program);
  14516. }
  14517. };
  14518. /**
  14519. * Create a new effect (used to store vertex/fragment shaders)
  14520. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14521. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14522. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14523. * @param samplers defines an array of string used to represent textures
  14524. * @param defines defines the string containing the defines to use to compile the shaders
  14525. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14526. * @param onCompiled defines a function to call when the effect creation is successful
  14527. * @param onError defines a function to call when the effect creation has failed
  14528. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14529. * @returns the new Effect
  14530. */
  14531. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14532. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14533. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14534. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14535. if (this._compiledEffects[name]) {
  14536. var compiledEffect = this._compiledEffects[name];
  14537. if (onCompiled && compiledEffect.isReady()) {
  14538. onCompiled(compiledEffect);
  14539. }
  14540. return compiledEffect;
  14541. }
  14542. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14543. effect._key = name;
  14544. this._compiledEffects[name] = effect;
  14545. return effect;
  14546. };
  14547. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14548. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14549. };
  14550. Engine.prototype._compileRawShader = function (source, type) {
  14551. var gl = this._gl;
  14552. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14553. gl.shaderSource(shader, source);
  14554. gl.compileShader(shader);
  14555. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14556. var log = gl.getShaderInfoLog(shader);
  14557. if (log) {
  14558. throw new Error(log);
  14559. }
  14560. }
  14561. if (!shader) {
  14562. throw new Error("Something went wrong while compile the shader.");
  14563. }
  14564. return shader;
  14565. };
  14566. /**
  14567. * Directly creates a webGL program
  14568. * @param vertexCode defines the vertex shader code to use
  14569. * @param fragmentCode defines the fragment shader code to use
  14570. * @param context defines the webGL context to use (if not set, the current one will be used)
  14571. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14572. * @returns the new webGL program
  14573. */
  14574. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14575. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14576. context = context || this._gl;
  14577. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14578. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14579. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14580. };
  14581. /**
  14582. * Creates a webGL program
  14583. * @param vertexCode defines the vertex shader code to use
  14584. * @param fragmentCode defines the fragment shader code to use
  14585. * @param defines defines the string containing the defines to use to compile the shaders
  14586. * @param context defines the webGL context to use (if not set, the current one will be used)
  14587. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14588. * @returns the new webGL program
  14589. */
  14590. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14591. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14592. context = context || this._gl;
  14593. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14594. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14595. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14596. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14597. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14598. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14599. return program;
  14600. };
  14601. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14602. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14603. var shaderProgram = context.createProgram();
  14604. if (!shaderProgram) {
  14605. throw new Error("Unable to create program");
  14606. }
  14607. context.attachShader(shaderProgram, vertexShader);
  14608. context.attachShader(shaderProgram, fragmentShader);
  14609. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14610. var transformFeedback = this.createTransformFeedback();
  14611. this.bindTransformFeedback(transformFeedback);
  14612. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14613. shaderProgram.transformFeedback = transformFeedback;
  14614. }
  14615. context.linkProgram(shaderProgram);
  14616. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14617. this.bindTransformFeedback(null);
  14618. }
  14619. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14620. if (!linked) {
  14621. var error = context.getProgramInfoLog(shaderProgram);
  14622. if (error) {
  14623. throw new Error(error);
  14624. }
  14625. }
  14626. if (this.validateShaderPrograms) {
  14627. context.validateProgram(shaderProgram);
  14628. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14629. if (!validated) {
  14630. var error = context.getProgramInfoLog(shaderProgram);
  14631. if (error) {
  14632. throw new Error(error);
  14633. }
  14634. }
  14635. }
  14636. context.deleteShader(vertexShader);
  14637. context.deleteShader(fragmentShader);
  14638. return shaderProgram;
  14639. };
  14640. /**
  14641. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14642. * @param shaderProgram defines the webGL program to use
  14643. * @param uniformsNames defines the list of uniform names
  14644. * @returns an array of webGL uniform locations
  14645. */
  14646. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14647. var results = new Array();
  14648. for (var index = 0; index < uniformsNames.length; index++) {
  14649. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14650. }
  14651. return results;
  14652. };
  14653. /**
  14654. * Gets the lsit of active attributes for a given webGL program
  14655. * @param shaderProgram defines the webGL program to use
  14656. * @param attributesNames defines the list of attribute names to get
  14657. * @returns an array of indices indicating the offset of each attribute
  14658. */
  14659. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14660. var results = [];
  14661. for (var index = 0; index < attributesNames.length; index++) {
  14662. try {
  14663. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14664. }
  14665. catch (e) {
  14666. results.push(-1);
  14667. }
  14668. }
  14669. return results;
  14670. };
  14671. /**
  14672. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14673. * @param effect defines the effect to activate
  14674. */
  14675. Engine.prototype.enableEffect = function (effect) {
  14676. if (!effect || effect === this._currentEffect) {
  14677. return;
  14678. }
  14679. // Use program
  14680. this.bindSamplers(effect);
  14681. this._currentEffect = effect;
  14682. if (effect.onBind) {
  14683. effect.onBind(effect);
  14684. }
  14685. if (effect._onBindObservable) {
  14686. effect._onBindObservable.notifyObservers(effect);
  14687. }
  14688. };
  14689. /**
  14690. * Set the value of an uniform to an array of int32
  14691. * @param uniform defines the webGL uniform location where to store the value
  14692. * @param array defines the array of int32 to store
  14693. */
  14694. Engine.prototype.setIntArray = function (uniform, array) {
  14695. if (!uniform) {
  14696. return;
  14697. }
  14698. this._gl.uniform1iv(uniform, array);
  14699. };
  14700. /**
  14701. * Set the value of an uniform to an array of int32 (stored as vec2)
  14702. * @param uniform defines the webGL uniform location where to store the value
  14703. * @param array defines the array of int32 to store
  14704. */
  14705. Engine.prototype.setIntArray2 = function (uniform, array) {
  14706. if (!uniform || array.length % 2 !== 0) {
  14707. return;
  14708. }
  14709. this._gl.uniform2iv(uniform, array);
  14710. };
  14711. /**
  14712. * Set the value of an uniform to an array of int32 (stored as vec3)
  14713. * @param uniform defines the webGL uniform location where to store the value
  14714. * @param array defines the array of int32 to store
  14715. */
  14716. Engine.prototype.setIntArray3 = function (uniform, array) {
  14717. if (!uniform || array.length % 3 !== 0) {
  14718. return;
  14719. }
  14720. this._gl.uniform3iv(uniform, array);
  14721. };
  14722. /**
  14723. * Set the value of an uniform to an array of int32 (stored as vec4)
  14724. * @param uniform defines the webGL uniform location where to store the value
  14725. * @param array defines the array of int32 to store
  14726. */
  14727. Engine.prototype.setIntArray4 = function (uniform, array) {
  14728. if (!uniform || array.length % 4 !== 0) {
  14729. return;
  14730. }
  14731. this._gl.uniform4iv(uniform, array);
  14732. };
  14733. /**
  14734. * Set the value of an uniform to an array of float32
  14735. * @param uniform defines the webGL uniform location where to store the value
  14736. * @param array defines the array of float32 to store
  14737. */
  14738. Engine.prototype.setFloatArray = function (uniform, array) {
  14739. if (!uniform) {
  14740. return;
  14741. }
  14742. this._gl.uniform1fv(uniform, array);
  14743. };
  14744. /**
  14745. * Set the value of an uniform to an array of float32 (stored as vec2)
  14746. * @param uniform defines the webGL uniform location where to store the value
  14747. * @param array defines the array of float32 to store
  14748. */
  14749. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14750. if (!uniform || array.length % 2 !== 0) {
  14751. return;
  14752. }
  14753. this._gl.uniform2fv(uniform, array);
  14754. };
  14755. /**
  14756. * Set the value of an uniform to an array of float32 (stored as vec3)
  14757. * @param uniform defines the webGL uniform location where to store the value
  14758. * @param array defines the array of float32 to store
  14759. */
  14760. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14761. if (!uniform || array.length % 3 !== 0) {
  14762. return;
  14763. }
  14764. this._gl.uniform3fv(uniform, array);
  14765. };
  14766. /**
  14767. * Set the value of an uniform to an array of float32 (stored as vec4)
  14768. * @param uniform defines the webGL uniform location where to store the value
  14769. * @param array defines the array of float32 to store
  14770. */
  14771. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14772. if (!uniform || array.length % 4 !== 0) {
  14773. return;
  14774. }
  14775. this._gl.uniform4fv(uniform, array);
  14776. };
  14777. /**
  14778. * Set the value of an uniform to an array of number
  14779. * @param uniform defines the webGL uniform location where to store the value
  14780. * @param array defines the array of number to store
  14781. */
  14782. Engine.prototype.setArray = function (uniform, array) {
  14783. if (!uniform) {
  14784. return;
  14785. }
  14786. this._gl.uniform1fv(uniform, array);
  14787. };
  14788. /**
  14789. * Set the value of an uniform to an array of number (stored as vec2)
  14790. * @param uniform defines the webGL uniform location where to store the value
  14791. * @param array defines the array of number to store
  14792. */
  14793. Engine.prototype.setArray2 = function (uniform, array) {
  14794. if (!uniform || array.length % 2 !== 0) {
  14795. return;
  14796. }
  14797. this._gl.uniform2fv(uniform, array);
  14798. };
  14799. /**
  14800. * Set the value of an uniform to an array of number (stored as vec3)
  14801. * @param uniform defines the webGL uniform location where to store the value
  14802. * @param array defines the array of number to store
  14803. */
  14804. Engine.prototype.setArray3 = function (uniform, array) {
  14805. if (!uniform || array.length % 3 !== 0) {
  14806. return;
  14807. }
  14808. this._gl.uniform3fv(uniform, array);
  14809. };
  14810. /**
  14811. * Set the value of an uniform to an array of number (stored as vec4)
  14812. * @param uniform defines the webGL uniform location where to store the value
  14813. * @param array defines the array of number to store
  14814. */
  14815. Engine.prototype.setArray4 = function (uniform, array) {
  14816. if (!uniform || array.length % 4 !== 0) {
  14817. return;
  14818. }
  14819. this._gl.uniform4fv(uniform, array);
  14820. };
  14821. /**
  14822. * Set the value of an uniform to an array of float32 (stored as matrices)
  14823. * @param uniform defines the webGL uniform location where to store the value
  14824. * @param matrices defines the array of float32 to store
  14825. */
  14826. Engine.prototype.setMatrices = function (uniform, matrices) {
  14827. if (!uniform) {
  14828. return;
  14829. }
  14830. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14831. };
  14832. /**
  14833. * Set the value of an uniform to a matrix
  14834. * @param uniform defines the webGL uniform location where to store the value
  14835. * @param matrix defines the matrix to store
  14836. */
  14837. Engine.prototype.setMatrix = function (uniform, matrix) {
  14838. if (!uniform) {
  14839. return;
  14840. }
  14841. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14842. };
  14843. /**
  14844. * Set the value of an uniform to a matrix (3x3)
  14845. * @param uniform defines the webGL uniform location where to store the value
  14846. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14847. */
  14848. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14849. if (!uniform) {
  14850. return;
  14851. }
  14852. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14853. };
  14854. /**
  14855. * Set the value of an uniform to a matrix (2x2)
  14856. * @param uniform defines the webGL uniform location where to store the value
  14857. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14858. */
  14859. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14860. if (!uniform) {
  14861. return;
  14862. }
  14863. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14864. };
  14865. /**
  14866. * Set the value of an uniform to a number (int)
  14867. * @param uniform defines the webGL uniform location where to store the value
  14868. * @param value defines the int number to store
  14869. */
  14870. Engine.prototype.setInt = function (uniform, value) {
  14871. if (!uniform) {
  14872. return;
  14873. }
  14874. this._gl.uniform1i(uniform, value);
  14875. };
  14876. /**
  14877. * Set the value of an uniform to a number (float)
  14878. * @param uniform defines the webGL uniform location where to store the value
  14879. * @param value defines the float number to store
  14880. */
  14881. Engine.prototype.setFloat = function (uniform, value) {
  14882. if (!uniform) {
  14883. return;
  14884. }
  14885. this._gl.uniform1f(uniform, value);
  14886. };
  14887. /**
  14888. * Set the value of an uniform to a vec2
  14889. * @param uniform defines the webGL uniform location where to store the value
  14890. * @param x defines the 1st component of the value
  14891. * @param y defines the 2nd component of the value
  14892. */
  14893. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14894. if (!uniform) {
  14895. return;
  14896. }
  14897. this._gl.uniform2f(uniform, x, y);
  14898. };
  14899. /**
  14900. * Set the value of an uniform to a vec3
  14901. * @param uniform defines the webGL uniform location where to store the value
  14902. * @param x defines the 1st component of the value
  14903. * @param y defines the 2nd component of the value
  14904. * @param z defines the 3rd component of the value
  14905. */
  14906. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14907. if (!uniform) {
  14908. return;
  14909. }
  14910. this._gl.uniform3f(uniform, x, y, z);
  14911. };
  14912. /**
  14913. * Set the value of an uniform to a boolean
  14914. * @param uniform defines the webGL uniform location where to store the value
  14915. * @param bool defines the boolean to store
  14916. */
  14917. Engine.prototype.setBool = function (uniform, bool) {
  14918. if (!uniform) {
  14919. return;
  14920. }
  14921. this._gl.uniform1i(uniform, bool);
  14922. };
  14923. /**
  14924. * Set the value of an uniform to a vec4
  14925. * @param uniform defines the webGL uniform location where to store the value
  14926. * @param x defines the 1st component of the value
  14927. * @param y defines the 2nd component of the value
  14928. * @param z defines the 3rd component of the value
  14929. * @param w defines the 4th component of the value
  14930. */
  14931. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14932. if (!uniform) {
  14933. return;
  14934. }
  14935. this._gl.uniform4f(uniform, x, y, z, w);
  14936. };
  14937. /**
  14938. * Set the value of an uniform to a Color3
  14939. * @param uniform defines the webGL uniform location where to store the value
  14940. * @param color3 defines the color to store
  14941. */
  14942. Engine.prototype.setColor3 = function (uniform, color3) {
  14943. if (!uniform) {
  14944. return;
  14945. }
  14946. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14947. };
  14948. /**
  14949. * Set the value of an uniform to a Color3 and an alpha value
  14950. * @param uniform defines the webGL uniform location where to store the value
  14951. * @param color3 defines the color to store
  14952. * @param alpha defines the alpha component to store
  14953. */
  14954. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14955. if (!uniform) {
  14956. return;
  14957. }
  14958. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14959. };
  14960. /**
  14961. * Sets a Color4 on a uniform variable
  14962. * @param uniform defines the uniform location
  14963. * @param color4 defines the value to be set
  14964. */
  14965. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14966. if (!uniform) {
  14967. return;
  14968. }
  14969. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14970. };
  14971. // States
  14972. /**
  14973. * Set various states to the webGL context
  14974. * @param culling defines backface culling state
  14975. * @param zOffset defines the value to apply to zOffset (0 by default)
  14976. * @param force defines if states must be applied even if cache is up to date
  14977. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14978. */
  14979. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14980. if (zOffset === void 0) { zOffset = 0; }
  14981. if (reverseSide === void 0) { reverseSide = false; }
  14982. // Culling
  14983. if (this._depthCullingState.cull !== culling || force) {
  14984. this._depthCullingState.cull = culling;
  14985. }
  14986. // Cull face
  14987. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14988. if (this._depthCullingState.cullFace !== cullFace || force) {
  14989. this._depthCullingState.cullFace = cullFace;
  14990. }
  14991. // Z offset
  14992. this.setZOffset(zOffset);
  14993. // Front face
  14994. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14995. if (this._depthCullingState.frontFace !== frontFace || force) {
  14996. this._depthCullingState.frontFace = frontFace;
  14997. }
  14998. };
  14999. /**
  15000. * Set the z offset to apply to current rendering
  15001. * @param value defines the offset to apply
  15002. */
  15003. Engine.prototype.setZOffset = function (value) {
  15004. this._depthCullingState.zOffset = value;
  15005. };
  15006. /**
  15007. * Gets the current value of the zOffset
  15008. * @returns the current zOffset state
  15009. */
  15010. Engine.prototype.getZOffset = function () {
  15011. return this._depthCullingState.zOffset;
  15012. };
  15013. /**
  15014. * Enable or disable depth buffering
  15015. * @param enable defines the state to set
  15016. */
  15017. Engine.prototype.setDepthBuffer = function (enable) {
  15018. this._depthCullingState.depthTest = enable;
  15019. };
  15020. /**
  15021. * Gets a boolean indicating if depth writing is enabled
  15022. * @returns the current depth writing state
  15023. */
  15024. Engine.prototype.getDepthWrite = function () {
  15025. return this._depthCullingState.depthMask;
  15026. };
  15027. /**
  15028. * Enable or disable depth writing
  15029. * @param enable defines the state to set
  15030. */
  15031. Engine.prototype.setDepthWrite = function (enable) {
  15032. this._depthCullingState.depthMask = enable;
  15033. };
  15034. /**
  15035. * Enable or disable color writing
  15036. * @param enable defines the state to set
  15037. */
  15038. Engine.prototype.setColorWrite = function (enable) {
  15039. this._gl.colorMask(enable, enable, enable, enable);
  15040. this._colorWrite = enable;
  15041. };
  15042. /**
  15043. * Gets a boolean indicating if color writing is enabled
  15044. * @returns the current color writing state
  15045. */
  15046. Engine.prototype.getColorWrite = function () {
  15047. return this._colorWrite;
  15048. };
  15049. /**
  15050. * Sets alpha constants used by some alpha blending modes
  15051. * @param r defines the red component
  15052. * @param g defines the green component
  15053. * @param b defines the blue component
  15054. * @param a defines the alpha component
  15055. */
  15056. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15057. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15058. };
  15059. /**
  15060. * Sets the current alpha mode
  15061. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15062. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15063. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15064. */
  15065. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15066. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15067. if (this._alphaMode === mode) {
  15068. return;
  15069. }
  15070. switch (mode) {
  15071. case Engine.ALPHA_DISABLE:
  15072. this._alphaState.alphaBlend = false;
  15073. break;
  15074. case Engine.ALPHA_PREMULTIPLIED:
  15075. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15076. this._alphaState.alphaBlend = true;
  15077. break;
  15078. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15079. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15080. this._alphaState.alphaBlend = true;
  15081. break;
  15082. case Engine.ALPHA_COMBINE:
  15083. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15084. this._alphaState.alphaBlend = true;
  15085. break;
  15086. case Engine.ALPHA_ONEONE:
  15087. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15088. this._alphaState.alphaBlend = true;
  15089. break;
  15090. case Engine.ALPHA_ADD:
  15091. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15092. this._alphaState.alphaBlend = true;
  15093. break;
  15094. case Engine.ALPHA_SUBTRACT:
  15095. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15096. this._alphaState.alphaBlend = true;
  15097. break;
  15098. case Engine.ALPHA_MULTIPLY:
  15099. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15100. this._alphaState.alphaBlend = true;
  15101. break;
  15102. case Engine.ALPHA_MAXIMIZED:
  15103. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15104. this._alphaState.alphaBlend = true;
  15105. break;
  15106. case Engine.ALPHA_INTERPOLATE:
  15107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15108. this._alphaState.alphaBlend = true;
  15109. break;
  15110. case Engine.ALPHA_SCREENMODE:
  15111. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15112. this._alphaState.alphaBlend = true;
  15113. break;
  15114. }
  15115. if (!noDepthWriteChange) {
  15116. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15117. }
  15118. this._alphaMode = mode;
  15119. };
  15120. /**
  15121. * Gets the current alpha mode
  15122. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15123. * @returns the current alpha mode
  15124. */
  15125. Engine.prototype.getAlphaMode = function () {
  15126. return this._alphaMode;
  15127. };
  15128. // Textures
  15129. /**
  15130. * Clears the list of texture accessible through engine.
  15131. * This can help preventing texture load conflict due to name collision.
  15132. */
  15133. Engine.prototype.clearInternalTexturesCache = function () {
  15134. this._internalTexturesCache = [];
  15135. };
  15136. /**
  15137. * Force the entire cache to be cleared
  15138. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15139. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15140. */
  15141. Engine.prototype.wipeCaches = function (bruteForce) {
  15142. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15143. return;
  15144. }
  15145. this._currentEffect = null;
  15146. this._viewportCached.x = 0;
  15147. this._viewportCached.y = 0;
  15148. this._viewportCached.z = 0;
  15149. this._viewportCached.w = 0;
  15150. if (bruteForce) {
  15151. this.resetTextureCache();
  15152. this._currentProgram = null;
  15153. this._stencilState.reset();
  15154. this._depthCullingState.reset();
  15155. this.setDepthFunctionToLessOrEqual();
  15156. this._alphaState.reset();
  15157. this._unpackFlipYCached = null;
  15158. }
  15159. this._resetVertexBufferBinding();
  15160. this._cachedIndexBuffer = null;
  15161. this._cachedEffectForVertexBuffers = null;
  15162. this._unbindVertexArrayObject();
  15163. this.bindIndexBuffer(null);
  15164. };
  15165. /**
  15166. * Set the compressed texture format to use, based on the formats you have, and the formats
  15167. * supported by the hardware / browser.
  15168. *
  15169. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15170. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15171. * to API arguments needed to compressed textures. This puts the burden on the container
  15172. * generator to house the arcane code for determining these for current & future formats.
  15173. *
  15174. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15175. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15176. *
  15177. * Note: The result of this call is not taken into account when a texture is base64.
  15178. *
  15179. * @param formatsAvailable defines the list of those format families you have created
  15180. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15181. *
  15182. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15183. * @returns The extension selected.
  15184. */
  15185. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15186. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15187. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15188. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15189. return this._textureFormatInUse = this._texturesSupported[i];
  15190. }
  15191. }
  15192. }
  15193. // actively set format to nothing, to allow this to be called more than once
  15194. // and possibly fail the 2nd time
  15195. this._textureFormatInUse = null;
  15196. return null;
  15197. };
  15198. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15199. var gl = this._gl;
  15200. var magFilter = gl.NEAREST;
  15201. var minFilter = gl.NEAREST;
  15202. switch (samplingMode) {
  15203. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15204. magFilter = gl.LINEAR;
  15205. if (generateMipMaps) {
  15206. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15207. }
  15208. else {
  15209. minFilter = gl.LINEAR;
  15210. }
  15211. break;
  15212. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15213. magFilter = gl.LINEAR;
  15214. if (generateMipMaps) {
  15215. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15216. }
  15217. else {
  15218. minFilter = gl.LINEAR;
  15219. }
  15220. break;
  15221. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15222. magFilter = gl.NEAREST;
  15223. if (generateMipMaps) {
  15224. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15225. }
  15226. else {
  15227. minFilter = gl.NEAREST;
  15228. }
  15229. break;
  15230. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15231. magFilter = gl.NEAREST;
  15232. if (generateMipMaps) {
  15233. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15234. }
  15235. else {
  15236. minFilter = gl.NEAREST;
  15237. }
  15238. break;
  15239. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15240. magFilter = gl.NEAREST;
  15241. if (generateMipMaps) {
  15242. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15243. }
  15244. else {
  15245. minFilter = gl.LINEAR;
  15246. }
  15247. break;
  15248. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15249. magFilter = gl.NEAREST;
  15250. if (generateMipMaps) {
  15251. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15252. }
  15253. else {
  15254. minFilter = gl.LINEAR;
  15255. }
  15256. break;
  15257. case Engine.TEXTURE_NEAREST_LINEAR:
  15258. magFilter = gl.NEAREST;
  15259. minFilter = gl.LINEAR;
  15260. break;
  15261. case Engine.TEXTURE_NEAREST_NEAREST:
  15262. magFilter = gl.NEAREST;
  15263. minFilter = gl.NEAREST;
  15264. break;
  15265. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15266. magFilter = gl.LINEAR;
  15267. if (generateMipMaps) {
  15268. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15269. }
  15270. else {
  15271. minFilter = gl.NEAREST;
  15272. }
  15273. break;
  15274. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15275. magFilter = gl.LINEAR;
  15276. if (generateMipMaps) {
  15277. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15278. }
  15279. else {
  15280. minFilter = gl.NEAREST;
  15281. }
  15282. break;
  15283. case Engine.TEXTURE_LINEAR_LINEAR:
  15284. magFilter = gl.LINEAR;
  15285. minFilter = gl.LINEAR;
  15286. break;
  15287. case Engine.TEXTURE_LINEAR_NEAREST:
  15288. magFilter = gl.LINEAR;
  15289. minFilter = gl.NEAREST;
  15290. break;
  15291. }
  15292. return {
  15293. min: minFilter,
  15294. mag: magFilter
  15295. };
  15296. };
  15297. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15298. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15299. var img;
  15300. var onload = function () {
  15301. loadedImages[index] = img;
  15302. loadedImages._internalCount++;
  15303. if (scene) {
  15304. scene._removePendingData(img);
  15305. }
  15306. if (loadedImages._internalCount === 6) {
  15307. onfinish(loadedImages);
  15308. }
  15309. };
  15310. var onerror = function (message, exception) {
  15311. if (scene) {
  15312. scene._removePendingData(img);
  15313. }
  15314. if (onErrorCallBack) {
  15315. onErrorCallBack(message, exception);
  15316. }
  15317. };
  15318. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15319. if (scene) {
  15320. scene._addPendingData(img);
  15321. }
  15322. };
  15323. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15324. if (onError === void 0) { onError = null; }
  15325. var loadedImages = [];
  15326. loadedImages._internalCount = 0;
  15327. for (var index = 0; index < 6; index++) {
  15328. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15329. }
  15330. };
  15331. /** @hidden */
  15332. Engine.prototype._createTexture = function () {
  15333. var texture = this._gl.createTexture();
  15334. if (!texture) {
  15335. throw new Error("Unable to create texture");
  15336. }
  15337. return texture;
  15338. };
  15339. /**
  15340. * Usually called from BABYLON.Texture.ts.
  15341. * Passed information to create a WebGLTexture
  15342. * @param urlArg defines a value which contains one of the following:
  15343. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15344. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15345. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15346. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15347. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15348. * @param scene needed for loading to the correct scene
  15349. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15350. * @param onLoad optional callback to be called upon successful completion
  15351. * @param onError optional callback to be called upon failure
  15352. * @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
  15353. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15354. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15355. * @param forcedExtension defines the extension to use to pick the right loader
  15356. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15357. */
  15358. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15359. var _this = this;
  15360. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15361. if (onLoad === void 0) { onLoad = null; }
  15362. if (onError === void 0) { onError = null; }
  15363. if (buffer === void 0) { buffer = null; }
  15364. if (fallback === void 0) { fallback = null; }
  15365. if (format === void 0) { format = null; }
  15366. if (forcedExtension === void 0) { forcedExtension = null; }
  15367. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15368. var fromData = url.substr(0, 5) === "data:";
  15369. var fromBlob = url.substr(0, 5) === "blob:";
  15370. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15371. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15372. // establish the file extension, if possible
  15373. var lastDot = url.lastIndexOf('.');
  15374. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15375. var loader = null;
  15376. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15377. var availableLoader = _a[_i];
  15378. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15379. loader = availableLoader;
  15380. break;
  15381. }
  15382. }
  15383. if (loader) {
  15384. url = loader.transformUrl(url, this._textureFormatInUse);
  15385. }
  15386. if (scene) {
  15387. scene._addPendingData(texture);
  15388. }
  15389. texture.url = url;
  15390. texture.generateMipMaps = !noMipmap;
  15391. texture.samplingMode = samplingMode;
  15392. texture.invertY = invertY;
  15393. if (!this._doNotHandleContextLost) {
  15394. // Keep a link to the buffer only if we plan to handle context lost
  15395. texture._buffer = buffer;
  15396. }
  15397. var onLoadObserver = null;
  15398. if (onLoad && !fallback) {
  15399. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15400. }
  15401. if (!fallback) {
  15402. this._internalTexturesCache.push(texture);
  15403. }
  15404. var onInternalError = function (message, exception) {
  15405. if (scene) {
  15406. scene._removePendingData(texture);
  15407. }
  15408. var customFallback = false;
  15409. if (loader) {
  15410. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15411. if (fallbackUrl) {
  15412. // Add Back
  15413. customFallback = true;
  15414. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15415. }
  15416. }
  15417. if (!customFallback) {
  15418. if (onLoadObserver) {
  15419. texture.onLoadedObservable.remove(onLoadObserver);
  15420. }
  15421. if (BABYLON.Tools.UseFallbackTexture) {
  15422. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15423. }
  15424. }
  15425. if (onError) {
  15426. onError(message || "Unknown error", exception);
  15427. }
  15428. };
  15429. // processing for non-image formats
  15430. if (loader) {
  15431. var callback = function (data) {
  15432. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15433. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15434. done();
  15435. return false;
  15436. }, samplingMode);
  15437. });
  15438. };
  15439. if (!buffer) {
  15440. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15441. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15442. });
  15443. }
  15444. else {
  15445. callback(buffer);
  15446. }
  15447. }
  15448. else {
  15449. var onload = function (img) {
  15450. if (fromBlob && !_this._doNotHandleContextLost) {
  15451. // We need to store the image if we need to rebuild the texture
  15452. // in case of a webgl context lost
  15453. texture._buffer = img;
  15454. }
  15455. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15456. var gl = _this._gl;
  15457. var isPot = (img.width === potWidth && img.height === potHeight);
  15458. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15459. if (isPot) {
  15460. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15461. return false;
  15462. }
  15463. var maxTextureSize = _this._caps.maxTextureSize;
  15464. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15465. _this._prepareWorkingCanvas();
  15466. if (!_this._workingCanvas || !_this._workingContext) {
  15467. return false;
  15468. }
  15469. _this._workingCanvas.width = potWidth;
  15470. _this._workingCanvas.height = potHeight;
  15471. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15472. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15473. texture.width = potWidth;
  15474. texture.height = potHeight;
  15475. return false;
  15476. }
  15477. else {
  15478. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15479. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15480. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15481. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15484. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15486. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15487. _this._releaseTexture(source_1);
  15488. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15489. continuationCallback();
  15490. });
  15491. }
  15492. return true;
  15493. }, samplingMode);
  15494. };
  15495. if (!fromData || isBase64) {
  15496. if (buffer instanceof HTMLImageElement) {
  15497. onload(buffer);
  15498. }
  15499. else {
  15500. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15501. }
  15502. }
  15503. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15504. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15505. }
  15506. else {
  15507. onload(buffer);
  15508. }
  15509. }
  15510. return texture;
  15511. };
  15512. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15513. var _this = this;
  15514. var rtt = this.createRenderTargetTexture({
  15515. width: destination.width,
  15516. height: destination.height,
  15517. }, {
  15518. generateMipMaps: false,
  15519. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15520. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15521. generateDepthBuffer: false,
  15522. generateStencilBuffer: false
  15523. });
  15524. if (!this._rescalePostProcess) {
  15525. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15526. }
  15527. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15528. _this._rescalePostProcess.onApply = function (effect) {
  15529. effect._bindTexture("textureSampler", source);
  15530. };
  15531. var hostingScene = scene;
  15532. if (!hostingScene) {
  15533. hostingScene = _this.scenes[_this.scenes.length - 1];
  15534. }
  15535. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15536. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15537. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15538. _this.unBindFramebuffer(rtt);
  15539. _this._releaseTexture(rtt);
  15540. if (onComplete) {
  15541. onComplete();
  15542. }
  15543. });
  15544. };
  15545. /**
  15546. * Update a raw texture
  15547. * @param texture defines the texture to update
  15548. * @param data defines the data to store in the texture
  15549. * @param format defines the format of the data
  15550. * @param invertY defines if data must be stored with Y axis inverted
  15551. * @param compression defines the compression used (null by default)
  15552. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15553. */
  15554. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15555. if (compression === void 0) { compression = null; }
  15556. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15557. if (!texture) {
  15558. return;
  15559. }
  15560. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15561. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15562. // babylon's internalFormat but gl's texImage2D format
  15563. var internalFormat = this._getInternalFormat(format);
  15564. var textureType = this._getWebGLTextureType(type);
  15565. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15566. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15567. if (!this._doNotHandleContextLost) {
  15568. texture._bufferView = data;
  15569. texture.format = format;
  15570. texture.type = type;
  15571. texture.invertY = invertY;
  15572. texture._compression = compression;
  15573. }
  15574. if (texture.width % 4 !== 0) {
  15575. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15576. }
  15577. if (compression && data) {
  15578. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15579. }
  15580. else {
  15581. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15582. }
  15583. if (texture.generateMipMaps) {
  15584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15585. }
  15586. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15587. // this.resetTextureCache();
  15588. texture.isReady = true;
  15589. };
  15590. /**
  15591. * Creates a raw texture
  15592. * @param data defines the data to store in the texture
  15593. * @param width defines the width of the texture
  15594. * @param height defines the height of the texture
  15595. * @param format defines the format of the data
  15596. * @param generateMipMaps defines if the engine should generate the mip levels
  15597. * @param invertY defines if data must be stored with Y axis inverted
  15598. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15599. * @param compression defines the compression used (null by default)
  15600. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15601. * @returns the raw texture inside an InternalTexture
  15602. */
  15603. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15604. if (compression === void 0) { compression = null; }
  15605. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15606. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15607. texture.baseWidth = width;
  15608. texture.baseHeight = height;
  15609. texture.width = width;
  15610. texture.height = height;
  15611. texture.format = format;
  15612. texture.generateMipMaps = generateMipMaps;
  15613. texture.samplingMode = samplingMode;
  15614. texture.invertY = invertY;
  15615. texture._compression = compression;
  15616. texture.type = type;
  15617. if (!this._doNotHandleContextLost) {
  15618. texture._bufferView = data;
  15619. }
  15620. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15621. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15622. // Filters
  15623. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15626. if (generateMipMaps) {
  15627. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15628. }
  15629. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15630. this._internalTexturesCache.push(texture);
  15631. return texture;
  15632. };
  15633. /** @hidden */
  15634. Engine.prototype._unpackFlipY = function (value) {
  15635. if (this._unpackFlipYCached !== value) {
  15636. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15637. if (this.enableUnpackFlipYCached) {
  15638. this._unpackFlipYCached = value;
  15639. }
  15640. }
  15641. };
  15642. /** @hidden */
  15643. Engine.prototype._getUnpackAlignement = function () {
  15644. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15645. };
  15646. /**
  15647. * Creates a dynamic texture
  15648. * @param width defines the width of the texture
  15649. * @param height defines the height of the texture
  15650. * @param generateMipMaps defines if the engine should generate the mip levels
  15651. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15652. * @returns the dynamic texture inside an InternalTexture
  15653. */
  15654. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15655. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15656. texture.baseWidth = width;
  15657. texture.baseHeight = height;
  15658. if (generateMipMaps) {
  15659. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15660. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15661. }
  15662. // this.resetTextureCache();
  15663. texture.width = width;
  15664. texture.height = height;
  15665. texture.isReady = false;
  15666. texture.generateMipMaps = generateMipMaps;
  15667. texture.samplingMode = samplingMode;
  15668. this.updateTextureSamplingMode(samplingMode, texture);
  15669. this._internalTexturesCache.push(texture);
  15670. return texture;
  15671. };
  15672. /**
  15673. * Update the sampling mode of a given texture
  15674. * @param samplingMode defines the required sampling mode
  15675. * @param texture defines the texture to update
  15676. */
  15677. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15678. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15679. if (texture.isCube) {
  15680. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15681. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15683. }
  15684. else if (texture.is3D) {
  15685. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15686. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15687. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15688. }
  15689. else {
  15690. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15691. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15692. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15693. }
  15694. texture.samplingMode = samplingMode;
  15695. };
  15696. /**
  15697. * Update the content of a dynamic texture
  15698. * @param texture defines the texture to update
  15699. * @param canvas defines the canvas containing the source
  15700. * @param invertY defines if data must be stored with Y axis inverted
  15701. * @param premulAlpha defines if alpha is stored as premultiplied
  15702. * @param format defines the format of the data
  15703. */
  15704. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15705. if (premulAlpha === void 0) { premulAlpha = false; }
  15706. if (!texture) {
  15707. return;
  15708. }
  15709. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15710. this._unpackFlipY(invertY);
  15711. if (premulAlpha) {
  15712. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15713. }
  15714. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15715. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15716. if (texture.generateMipMaps) {
  15717. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15718. }
  15719. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15720. if (premulAlpha) {
  15721. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15722. }
  15723. texture.isReady = true;
  15724. };
  15725. /**
  15726. * Update a video texture
  15727. * @param texture defines the texture to update
  15728. * @param video defines the video element to use
  15729. * @param invertY defines if data must be stored with Y axis inverted
  15730. */
  15731. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15732. if (!texture || texture._isDisabled) {
  15733. return;
  15734. }
  15735. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15736. this._unpackFlipY(!invertY); // Video are upside down by default
  15737. try {
  15738. // Testing video texture support
  15739. if (this._videoTextureSupported === undefined) {
  15740. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15741. if (this._gl.getError() !== 0) {
  15742. this._videoTextureSupported = false;
  15743. }
  15744. else {
  15745. this._videoTextureSupported = true;
  15746. }
  15747. }
  15748. // Copy video through the current working canvas if video texture is not supported
  15749. if (!this._videoTextureSupported) {
  15750. if (!texture._workingCanvas) {
  15751. texture._workingCanvas = document.createElement("canvas");
  15752. var context = texture._workingCanvas.getContext("2d");
  15753. if (!context) {
  15754. throw new Error("Unable to get 2d context");
  15755. }
  15756. texture._workingContext = context;
  15757. texture._workingCanvas.width = texture.width;
  15758. texture._workingCanvas.height = texture.height;
  15759. }
  15760. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15761. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15762. }
  15763. else {
  15764. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15765. }
  15766. if (texture.generateMipMaps) {
  15767. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15768. }
  15769. if (!wasPreviouslyBound) {
  15770. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15771. }
  15772. // this.resetTextureCache();
  15773. texture.isReady = true;
  15774. }
  15775. catch (ex) {
  15776. // Something unexpected
  15777. // Let's disable the texture
  15778. texture._isDisabled = true;
  15779. }
  15780. };
  15781. /**
  15782. * Updates a depth texture Comparison Mode and Function.
  15783. * If the comparison Function is equal to 0, the mode will be set to none.
  15784. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15785. * @param texture The texture to set the comparison function for
  15786. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15787. */
  15788. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15789. if (this.webGLVersion === 1) {
  15790. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15791. return;
  15792. }
  15793. var gl = this._gl;
  15794. if (texture.isCube) {
  15795. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15796. if (comparisonFunction === 0) {
  15797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15799. }
  15800. else {
  15801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15803. }
  15804. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15805. }
  15806. else {
  15807. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15808. if (comparisonFunction === 0) {
  15809. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15810. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15811. }
  15812. else {
  15813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15814. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15815. }
  15816. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15817. }
  15818. texture._comparisonFunction = comparisonFunction;
  15819. };
  15820. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15821. var width = size.width || size;
  15822. var height = size.height || size;
  15823. internalTexture.baseWidth = width;
  15824. internalTexture.baseHeight = height;
  15825. internalTexture.width = width;
  15826. internalTexture.height = height;
  15827. internalTexture.isReady = true;
  15828. internalTexture.samples = 1;
  15829. internalTexture.generateMipMaps = false;
  15830. internalTexture._generateDepthBuffer = true;
  15831. internalTexture._generateStencilBuffer = generateStencil;
  15832. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15833. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15834. internalTexture._comparisonFunction = comparisonFunction;
  15835. var gl = this._gl;
  15836. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15837. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15838. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15839. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15840. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15841. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15842. if (comparisonFunction === 0) {
  15843. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15844. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15845. }
  15846. else {
  15847. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15848. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15849. }
  15850. };
  15851. /**
  15852. * Creates a depth stencil texture.
  15853. * This is only available in WebGL 2 or with the depth texture extension available.
  15854. * @param size The size of face edge in the texture.
  15855. * @param options The options defining the texture.
  15856. * @returns The texture
  15857. */
  15858. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15859. if (options.isCube) {
  15860. var width = size.width || size;
  15861. return this._createDepthStencilCubeTexture(width, options);
  15862. }
  15863. else {
  15864. return this._createDepthStencilTexture(size, options);
  15865. }
  15866. };
  15867. /**
  15868. * Creates a depth stencil texture.
  15869. * This is only available in WebGL 2 or with the depth texture extension available.
  15870. * @param size The size of face edge in the texture.
  15871. * @param options The options defining the texture.
  15872. * @returns The texture
  15873. */
  15874. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15875. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15876. if (!this._caps.depthTextureExtension) {
  15877. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15878. return internalTexture;
  15879. }
  15880. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15881. var gl = this._gl;
  15882. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15883. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15884. if (this.webGLVersion > 1) {
  15885. if (internalOptions.generateStencil) {
  15886. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15887. }
  15888. else {
  15889. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15890. }
  15891. }
  15892. else {
  15893. if (internalOptions.generateStencil) {
  15894. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15895. }
  15896. else {
  15897. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15898. }
  15899. }
  15900. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15901. return internalTexture;
  15902. };
  15903. /**
  15904. * Creates a depth stencil cube texture.
  15905. * This is only available in WebGL 2.
  15906. * @param size The size of face edge in the cube texture.
  15907. * @param options The options defining the cube texture.
  15908. * @returns The cube texture
  15909. */
  15910. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15911. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15912. internalTexture.isCube = true;
  15913. if (this.webGLVersion === 1) {
  15914. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15915. return internalTexture;
  15916. }
  15917. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15918. var gl = this._gl;
  15919. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15920. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15921. // Create the depth/stencil buffer
  15922. for (var face = 0; face < 6; face++) {
  15923. if (internalOptions.generateStencil) {
  15924. 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);
  15925. }
  15926. else {
  15927. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15928. }
  15929. }
  15930. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15931. return internalTexture;
  15932. };
  15933. /**
  15934. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15935. * @param renderTarget The render target to set the frame buffer for
  15936. */
  15937. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15938. // Create the framebuffer
  15939. var internalTexture = renderTarget.getInternalTexture();
  15940. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15941. return;
  15942. }
  15943. var gl = this._gl;
  15944. var depthStencilTexture = renderTarget.depthStencilTexture;
  15945. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15946. if (depthStencilTexture.isCube) {
  15947. if (depthStencilTexture._generateStencilBuffer) {
  15948. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15949. }
  15950. else {
  15951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15952. }
  15953. }
  15954. else {
  15955. if (depthStencilTexture._generateStencilBuffer) {
  15956. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15957. }
  15958. else {
  15959. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15960. }
  15961. }
  15962. this.bindUnboundFramebuffer(null);
  15963. };
  15964. /**
  15965. * Creates a new render target texture
  15966. * @param size defines the size of the texture
  15967. * @param options defines the options used to create the texture
  15968. * @returns a new render target texture stored in an InternalTexture
  15969. */
  15970. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15971. var fullOptions = new RenderTargetCreationOptions();
  15972. if (options !== undefined && typeof options === "object") {
  15973. fullOptions.generateMipMaps = options.generateMipMaps;
  15974. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15975. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15976. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15977. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15978. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15979. }
  15980. else {
  15981. fullOptions.generateMipMaps = options;
  15982. fullOptions.generateDepthBuffer = true;
  15983. fullOptions.generateStencilBuffer = false;
  15984. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15985. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15986. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15987. }
  15988. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15989. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15990. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15991. }
  15992. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15993. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15994. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15995. }
  15996. var gl = this._gl;
  15997. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15998. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15999. var width = size.width || size;
  16000. var height = size.height || size;
  16001. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16002. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16003. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16004. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16005. }
  16006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16010. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16011. // Create the framebuffer
  16012. var currentFrameBuffer = this._currentFramebuffer;
  16013. var framebuffer = gl.createFramebuffer();
  16014. this.bindUnboundFramebuffer(framebuffer);
  16015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16016. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16017. if (fullOptions.generateMipMaps) {
  16018. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16019. }
  16020. // Unbind
  16021. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16022. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16023. this.bindUnboundFramebuffer(currentFrameBuffer);
  16024. texture._framebuffer = framebuffer;
  16025. texture.baseWidth = width;
  16026. texture.baseHeight = height;
  16027. texture.width = width;
  16028. texture.height = height;
  16029. texture.isReady = true;
  16030. texture.samples = 1;
  16031. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16032. texture.samplingMode = fullOptions.samplingMode;
  16033. texture.type = fullOptions.type;
  16034. texture.format = fullOptions.format;
  16035. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16036. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16037. // this.resetTextureCache();
  16038. this._internalTexturesCache.push(texture);
  16039. return texture;
  16040. };
  16041. /**
  16042. * Create a multi render target texture
  16043. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16044. * @param size defines the size of the texture
  16045. * @param options defines the creation options
  16046. * @returns the cube texture as an InternalTexture
  16047. */
  16048. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16049. var generateMipMaps = false;
  16050. var generateDepthBuffer = true;
  16051. var generateStencilBuffer = false;
  16052. var generateDepthTexture = false;
  16053. var textureCount = 1;
  16054. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16055. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16056. var types = new Array();
  16057. var samplingModes = new Array();
  16058. if (options !== undefined) {
  16059. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16060. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16061. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16062. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16063. textureCount = options.textureCount || 1;
  16064. if (options.types) {
  16065. types = options.types;
  16066. }
  16067. if (options.samplingModes) {
  16068. samplingModes = options.samplingModes;
  16069. }
  16070. }
  16071. var gl = this._gl;
  16072. // Create the framebuffer
  16073. var framebuffer = gl.createFramebuffer();
  16074. this.bindUnboundFramebuffer(framebuffer);
  16075. var width = size.width || size;
  16076. var height = size.height || size;
  16077. var textures = [];
  16078. var attachments = [];
  16079. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16080. for (var i = 0; i < textureCount; i++) {
  16081. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16082. var type = types[i] || defaultType;
  16083. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16084. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16085. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16086. }
  16087. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16088. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16089. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16090. }
  16091. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16092. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16093. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16094. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16095. }
  16096. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16097. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16098. textures.push(texture);
  16099. attachments.push(attachment);
  16100. gl.activeTexture(gl["TEXTURE" + i]);
  16101. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16103. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16104. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16105. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16106. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16107. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16108. if (generateMipMaps) {
  16109. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16110. }
  16111. // Unbind
  16112. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16113. texture._framebuffer = framebuffer;
  16114. texture._depthStencilBuffer = depthStencilBuffer;
  16115. texture.baseWidth = width;
  16116. texture.baseHeight = height;
  16117. texture.width = width;
  16118. texture.height = height;
  16119. texture.isReady = true;
  16120. texture.samples = 1;
  16121. texture.generateMipMaps = generateMipMaps;
  16122. texture.samplingMode = samplingMode;
  16123. texture.type = type;
  16124. texture._generateDepthBuffer = generateDepthBuffer;
  16125. texture._generateStencilBuffer = generateStencilBuffer;
  16126. texture._attachments = attachments;
  16127. this._internalTexturesCache.push(texture);
  16128. }
  16129. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16130. // Depth texture
  16131. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16132. gl.activeTexture(gl.TEXTURE0);
  16133. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16138. 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);
  16139. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16140. depthTexture._framebuffer = framebuffer;
  16141. depthTexture.baseWidth = width;
  16142. depthTexture.baseHeight = height;
  16143. depthTexture.width = width;
  16144. depthTexture.height = height;
  16145. depthTexture.isReady = true;
  16146. depthTexture.samples = 1;
  16147. depthTexture.generateMipMaps = generateMipMaps;
  16148. depthTexture.samplingMode = gl.NEAREST;
  16149. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16150. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16151. textures.push(depthTexture);
  16152. this._internalTexturesCache.push(depthTexture);
  16153. }
  16154. gl.drawBuffers(attachments);
  16155. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16156. this.bindUnboundFramebuffer(null);
  16157. this.resetTextureCache();
  16158. return textures;
  16159. };
  16160. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16161. if (samples === void 0) { samples = 1; }
  16162. var depthStencilBuffer = null;
  16163. var gl = this._gl;
  16164. // Create the depth/stencil buffer
  16165. if (generateStencilBuffer) {
  16166. depthStencilBuffer = gl.createRenderbuffer();
  16167. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16168. if (samples > 1) {
  16169. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16170. }
  16171. else {
  16172. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16173. }
  16174. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16175. }
  16176. else if (generateDepthBuffer) {
  16177. depthStencilBuffer = gl.createRenderbuffer();
  16178. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16179. if (samples > 1) {
  16180. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16181. }
  16182. else {
  16183. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16184. }
  16185. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16186. }
  16187. return depthStencilBuffer;
  16188. };
  16189. /**
  16190. * Updates the sample count of a render target texture
  16191. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16192. * @param texture defines the texture to update
  16193. * @param samples defines the sample count to set
  16194. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16195. */
  16196. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16197. if (this.webGLVersion < 2 || !texture) {
  16198. return 1;
  16199. }
  16200. if (texture.samples === samples) {
  16201. return samples;
  16202. }
  16203. var gl = this._gl;
  16204. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16205. // Dispose previous render buffers
  16206. if (texture._depthStencilBuffer) {
  16207. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16208. texture._depthStencilBuffer = null;
  16209. }
  16210. if (texture._MSAAFramebuffer) {
  16211. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16212. texture._MSAAFramebuffer = null;
  16213. }
  16214. if (texture._MSAARenderBuffer) {
  16215. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16216. texture._MSAARenderBuffer = null;
  16217. }
  16218. if (samples > 1) {
  16219. var framebuffer = gl.createFramebuffer();
  16220. if (!framebuffer) {
  16221. throw new Error("Unable to create multi sampled framebuffer");
  16222. }
  16223. texture._MSAAFramebuffer = framebuffer;
  16224. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16225. var colorRenderbuffer = gl.createRenderbuffer();
  16226. if (!colorRenderbuffer) {
  16227. throw new Error("Unable to create multi sampled framebuffer");
  16228. }
  16229. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16230. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16231. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16232. texture._MSAARenderBuffer = colorRenderbuffer;
  16233. }
  16234. else {
  16235. this.bindUnboundFramebuffer(texture._framebuffer);
  16236. }
  16237. texture.samples = samples;
  16238. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16239. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16240. this.bindUnboundFramebuffer(null);
  16241. return samples;
  16242. };
  16243. /**
  16244. * Update the sample count for a given multiple render target texture
  16245. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16246. * @param textures defines the textures to update
  16247. * @param samples defines the sample count to set
  16248. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16249. */
  16250. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16251. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16252. return 1;
  16253. }
  16254. if (textures[0].samples === samples) {
  16255. return samples;
  16256. }
  16257. var gl = this._gl;
  16258. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16259. // Dispose previous render buffers
  16260. if (textures[0]._depthStencilBuffer) {
  16261. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16262. textures[0]._depthStencilBuffer = null;
  16263. }
  16264. if (textures[0]._MSAAFramebuffer) {
  16265. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16266. textures[0]._MSAAFramebuffer = null;
  16267. }
  16268. for (var i = 0; i < textures.length; i++) {
  16269. if (textures[i]._MSAARenderBuffer) {
  16270. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16271. textures[i]._MSAARenderBuffer = null;
  16272. }
  16273. }
  16274. if (samples > 1) {
  16275. var framebuffer = gl.createFramebuffer();
  16276. if (!framebuffer) {
  16277. throw new Error("Unable to create multi sampled framebuffer");
  16278. }
  16279. this.bindUnboundFramebuffer(framebuffer);
  16280. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16281. var attachments = [];
  16282. for (var i = 0; i < textures.length; i++) {
  16283. var texture = textures[i];
  16284. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16285. var colorRenderbuffer = gl.createRenderbuffer();
  16286. if (!colorRenderbuffer) {
  16287. throw new Error("Unable to create multi sampled framebuffer");
  16288. }
  16289. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16290. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16291. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16292. texture._MSAAFramebuffer = framebuffer;
  16293. texture._MSAARenderBuffer = colorRenderbuffer;
  16294. texture.samples = samples;
  16295. texture._depthStencilBuffer = depthStencilBuffer;
  16296. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16297. attachments.push(attachment);
  16298. }
  16299. gl.drawBuffers(attachments);
  16300. }
  16301. else {
  16302. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16303. }
  16304. this.bindUnboundFramebuffer(null);
  16305. return samples;
  16306. };
  16307. /** @hidden */
  16308. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16309. if (faceIndex === void 0) { faceIndex = 0; }
  16310. if (lod === void 0) { lod = 0; }
  16311. var gl = this._gl;
  16312. var target = gl.TEXTURE_2D;
  16313. if (texture.isCube) {
  16314. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16315. }
  16316. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16317. };
  16318. /** @hidden */
  16319. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16320. if (faceIndex === void 0) { faceIndex = 0; }
  16321. if (lod === void 0) { lod = 0; }
  16322. var gl = this._gl;
  16323. var textureType = this._getWebGLTextureType(texture.type);
  16324. var format = this._getInternalFormat(texture.format);
  16325. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16326. this._unpackFlipY(texture.invertY);
  16327. var target = gl.TEXTURE_2D;
  16328. if (texture.isCube) {
  16329. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16330. }
  16331. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16332. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16333. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16334. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16335. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16336. };
  16337. /** @hidden */
  16338. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16339. if (faceIndex === void 0) { faceIndex = 0; }
  16340. if (lod === void 0) { lod = 0; }
  16341. var gl = this._gl;
  16342. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16343. this._bindTextureDirectly(bindTarget, texture, true);
  16344. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16345. this._bindTextureDirectly(bindTarget, null, true);
  16346. };
  16347. /** @hidden */
  16348. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16349. if (faceIndex === void 0) { faceIndex = 0; }
  16350. if (lod === void 0) { lod = 0; }
  16351. var gl = this._gl;
  16352. var textureType = this._getWebGLTextureType(texture.type);
  16353. var format = this._getInternalFormat(texture.format);
  16354. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16355. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16356. this._bindTextureDirectly(bindTarget, texture, true);
  16357. this._unpackFlipY(texture.invertY);
  16358. var target = gl.TEXTURE_2D;
  16359. if (texture.isCube) {
  16360. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16361. }
  16362. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16363. this._bindTextureDirectly(bindTarget, null, true);
  16364. };
  16365. /**
  16366. * Creates a new render target cube texture
  16367. * @param size defines the size of the texture
  16368. * @param options defines the options used to create the texture
  16369. * @returns a new render target cube texture stored in an InternalTexture
  16370. */
  16371. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16372. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16373. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16374. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16375. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16376. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16377. }
  16378. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16379. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16380. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16381. }
  16382. var gl = this._gl;
  16383. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16384. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16385. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16386. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16387. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16388. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16389. }
  16390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16391. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16394. for (var face = 0; face < 6; face++) {
  16395. 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);
  16396. }
  16397. // Create the framebuffer
  16398. var framebuffer = gl.createFramebuffer();
  16399. this.bindUnboundFramebuffer(framebuffer);
  16400. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16401. // MipMaps
  16402. if (fullOptions.generateMipMaps) {
  16403. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16404. }
  16405. // Unbind
  16406. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16407. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16408. this.bindUnboundFramebuffer(null);
  16409. texture._framebuffer = framebuffer;
  16410. texture.width = size;
  16411. texture.height = size;
  16412. texture.isReady = true;
  16413. texture.isCube = true;
  16414. texture.samples = 1;
  16415. texture.generateMipMaps = fullOptions.generateMipMaps;
  16416. texture.samplingMode = fullOptions.samplingMode;
  16417. texture.type = fullOptions.type;
  16418. texture.format = fullOptions.format;
  16419. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16420. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16421. this._internalTexturesCache.push(texture);
  16422. return texture;
  16423. };
  16424. /**
  16425. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16426. * @param rootUrl defines the url where the file to load is located
  16427. * @param scene defines the current scene
  16428. * @param lodScale defines scale to apply to the mip map selection
  16429. * @param lodOffset defines offset to apply to the mip map selection
  16430. * @param onLoad defines an optional callback raised when the texture is loaded
  16431. * @param onError defines an optional callback raised if there is an issue to load the texture
  16432. * @param format defines the format of the data
  16433. * @param forcedExtension defines the extension to use to pick the right loader
  16434. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16435. * @returns the cube texture as an InternalTexture
  16436. */
  16437. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16438. var _this = this;
  16439. if (onLoad === void 0) { onLoad = null; }
  16440. if (onError === void 0) { onError = null; }
  16441. if (forcedExtension === void 0) { forcedExtension = null; }
  16442. if (createPolynomials === void 0) { createPolynomials = true; }
  16443. var callback = function (loadData) {
  16444. if (!loadData) {
  16445. if (onLoad) {
  16446. onLoad(null);
  16447. }
  16448. return;
  16449. }
  16450. var texture = loadData.texture;
  16451. if (!createPolynomials) {
  16452. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16453. }
  16454. else if (loadData.info.sphericalPolynomial) {
  16455. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16456. }
  16457. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16458. if (_this._caps.textureLOD) {
  16459. // Do not add extra process if texture lod is supported.
  16460. if (onLoad) {
  16461. onLoad(texture);
  16462. }
  16463. return;
  16464. }
  16465. var mipSlices = 3;
  16466. var gl = _this._gl;
  16467. var width = loadData.width;
  16468. if (!width) {
  16469. return;
  16470. }
  16471. var textures = [];
  16472. for (var i = 0; i < mipSlices; i++) {
  16473. //compute LOD from even spacing in smoothness (matching shader calculation)
  16474. var smoothness = i / (mipSlices - 1);
  16475. var roughness = 1 - smoothness;
  16476. var minLODIndex = lodOffset; // roughness = 0
  16477. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16478. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16479. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16480. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16481. glTextureFromLod.type = texture.type;
  16482. glTextureFromLod.format = texture.format;
  16483. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16484. glTextureFromLod.height = glTextureFromLod.width;
  16485. glTextureFromLod.isCube = true;
  16486. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16491. if (loadData.isDDS) {
  16492. var info = loadData.info;
  16493. var data = loadData.data;
  16494. _this._unpackFlipY(info.isCompressed);
  16495. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16496. }
  16497. else {
  16498. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16499. }
  16500. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16501. // Wrap in a base texture for easy binding.
  16502. var lodTexture = new BABYLON.BaseTexture(scene);
  16503. lodTexture.isCube = true;
  16504. lodTexture._texture = glTextureFromLod;
  16505. glTextureFromLod.isReady = true;
  16506. textures.push(lodTexture);
  16507. }
  16508. texture._lodTextureHigh = textures[2];
  16509. texture._lodTextureMid = textures[1];
  16510. texture._lodTextureLow = textures[0];
  16511. if (onLoad) {
  16512. onLoad(texture);
  16513. }
  16514. };
  16515. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16516. };
  16517. /**
  16518. * Creates a cube texture
  16519. * @param rootUrl defines the url where the files to load is located
  16520. * @param scene defines the current scene
  16521. * @param files defines the list of files to load (1 per face)
  16522. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16523. * @param onLoad defines an optional callback raised when the texture is loaded
  16524. * @param onError defines an optional callback raised if there is an issue to load the texture
  16525. * @param format defines the format of the data
  16526. * @param forcedExtension defines the extension to use to pick the right loader
  16527. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16528. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16529. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16530. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16531. * @returns the cube texture as an InternalTexture
  16532. */
  16533. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16534. var _this = this;
  16535. if (onLoad === void 0) { onLoad = null; }
  16536. if (onError === void 0) { onError = null; }
  16537. if (forcedExtension === void 0) { forcedExtension = null; }
  16538. if (createPolynomials === void 0) { createPolynomials = false; }
  16539. if (lodScale === void 0) { lodScale = 0; }
  16540. if (lodOffset === void 0) { lodOffset = 0; }
  16541. if (fallback === void 0) { fallback = null; }
  16542. var gl = this._gl;
  16543. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16544. texture.isCube = true;
  16545. texture.url = rootUrl;
  16546. texture.generateMipMaps = !noMipmap;
  16547. texture._lodGenerationScale = lodScale;
  16548. texture._lodGenerationOffset = lodOffset;
  16549. if (!this._doNotHandleContextLost) {
  16550. texture._extension = forcedExtension;
  16551. texture._files = files;
  16552. }
  16553. var lastDot = rootUrl.lastIndexOf('.');
  16554. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16555. var loader = null;
  16556. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16557. var availableLoader = _a[_i];
  16558. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16559. loader = availableLoader;
  16560. break;
  16561. }
  16562. }
  16563. var onInternalError = function (request, exception) {
  16564. if (loader) {
  16565. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16566. if (fallbackUrl) {
  16567. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16568. }
  16569. }
  16570. if (onError && request) {
  16571. onError(request.status + " " + request.statusText, exception);
  16572. }
  16573. };
  16574. if (loader) {
  16575. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16576. var onloaddata = function (data) {
  16577. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16578. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16579. };
  16580. if (files && files.length === 6) {
  16581. if (loader.supportCascades) {
  16582. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16583. }
  16584. else if (onError) {
  16585. onError("Textures type does not support cascades.");
  16586. }
  16587. }
  16588. else {
  16589. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16590. }
  16591. }
  16592. else {
  16593. if (!files) {
  16594. throw new Error("Cannot load cubemap because files were not defined");
  16595. }
  16596. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16597. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16598. var height = width;
  16599. _this._prepareWorkingCanvas();
  16600. if (!_this._workingCanvas || !_this._workingContext) {
  16601. return;
  16602. }
  16603. _this._workingCanvas.width = width;
  16604. _this._workingCanvas.height = height;
  16605. var faces = [
  16606. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16607. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16608. ];
  16609. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16610. _this._unpackFlipY(false);
  16611. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16612. for (var index = 0; index < faces.length; index++) {
  16613. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16614. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16615. }
  16616. if (!noMipmap) {
  16617. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16618. }
  16619. _this._setCubeMapTextureParams(!noMipmap);
  16620. texture.width = width;
  16621. texture.height = height;
  16622. texture.isReady = true;
  16623. if (format) {
  16624. texture.format = format;
  16625. }
  16626. texture.onLoadedObservable.notifyObservers(texture);
  16627. texture.onLoadedObservable.clear();
  16628. if (onLoad) {
  16629. onLoad();
  16630. }
  16631. }, files, onError);
  16632. }
  16633. this._internalTexturesCache.push(texture);
  16634. return texture;
  16635. };
  16636. /**
  16637. * @hidden
  16638. */
  16639. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16640. var gl = this._gl;
  16641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16643. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16645. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16646. // this.resetTextureCache();
  16647. };
  16648. /**
  16649. * Update a raw cube texture
  16650. * @param texture defines the texture to udpdate
  16651. * @param data defines the data to store
  16652. * @param format defines the data format
  16653. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16654. * @param invertY defines if data must be stored with Y axis inverted
  16655. * @param compression defines the compression used (null by default)
  16656. * @param level defines which level of the texture to update
  16657. */
  16658. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16659. if (compression === void 0) { compression = null; }
  16660. if (level === void 0) { level = 0; }
  16661. texture._bufferViewArray = data;
  16662. texture.format = format;
  16663. texture.type = type;
  16664. texture.invertY = invertY;
  16665. texture._compression = compression;
  16666. var gl = this._gl;
  16667. var textureType = this._getWebGLTextureType(type);
  16668. var internalFormat = this._getInternalFormat(format);
  16669. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16670. var needConversion = false;
  16671. if (internalFormat === gl.RGB) {
  16672. internalFormat = gl.RGBA;
  16673. needConversion = true;
  16674. }
  16675. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16676. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16677. if (texture.width % 4 !== 0) {
  16678. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16679. }
  16680. // Data are known to be in +X +Y +Z -X -Y -Z
  16681. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16682. var faceData = data[faceIndex];
  16683. if (compression) {
  16684. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16685. }
  16686. else {
  16687. if (needConversion) {
  16688. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16689. }
  16690. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16691. }
  16692. }
  16693. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16694. if (isPot && texture.generateMipMaps && level === 0) {
  16695. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16696. }
  16697. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16698. // this.resetTextureCache();
  16699. texture.isReady = true;
  16700. };
  16701. /**
  16702. * Creates a new raw cube texture
  16703. * @param data defines the array of data to use to create each face
  16704. * @param size defines the size of the textures
  16705. * @param format defines the format of the data
  16706. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16707. * @param generateMipMaps defines if the engine should generate the mip levels
  16708. * @param invertY defines if data must be stored with Y axis inverted
  16709. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16710. * @param compression defines the compression used (null by default)
  16711. * @returns the cube texture as an InternalTexture
  16712. */
  16713. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16714. if (compression === void 0) { compression = null; }
  16715. var gl = this._gl;
  16716. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16717. texture.isCube = true;
  16718. texture.format = format;
  16719. texture.type = type;
  16720. if (!this._doNotHandleContextLost) {
  16721. texture._bufferViewArray = data;
  16722. }
  16723. var textureType = this._getWebGLTextureType(type);
  16724. var internalFormat = this._getInternalFormat(format);
  16725. if (internalFormat === gl.RGB) {
  16726. internalFormat = gl.RGBA;
  16727. }
  16728. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16729. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16730. generateMipMaps = false;
  16731. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16732. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16733. }
  16734. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16735. generateMipMaps = false;
  16736. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16737. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16738. }
  16739. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16740. generateMipMaps = false;
  16741. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16742. }
  16743. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16744. generateMipMaps = false;
  16745. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16746. }
  16747. var width = size;
  16748. var height = width;
  16749. texture.width = width;
  16750. texture.height = height;
  16751. // Double check on POT to generate Mips.
  16752. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16753. if (!isPot) {
  16754. generateMipMaps = false;
  16755. }
  16756. // Upload data if needed. The texture won't be ready until then.
  16757. if (data) {
  16758. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16759. }
  16760. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16761. // Filters
  16762. if (data && generateMipMaps) {
  16763. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16764. }
  16765. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16770. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16771. texture.generateMipMaps = generateMipMaps;
  16772. return texture;
  16773. };
  16774. /**
  16775. * Creates a new raw cube texture from a specified url
  16776. * @param url defines the url where the data is located
  16777. * @param scene defines the current scene
  16778. * @param size defines the size of the textures
  16779. * @param format defines the format of the data
  16780. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16781. * @param noMipmap defines if the engine should avoid generating the mip levels
  16782. * @param callback defines a callback used to extract texture data from loaded data
  16783. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16784. * @param onLoad defines a callback called when texture is loaded
  16785. * @param onError defines a callback called if there is an error
  16786. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16787. * @param invertY defines if data must be stored with Y axis inverted
  16788. * @returns the cube texture as an InternalTexture
  16789. */
  16790. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16791. var _this = this;
  16792. if (onLoad === void 0) { onLoad = null; }
  16793. if (onError === void 0) { onError = null; }
  16794. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16795. if (invertY === void 0) { invertY = false; }
  16796. var gl = this._gl;
  16797. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16798. scene._addPendingData(texture);
  16799. texture.url = url;
  16800. this._internalTexturesCache.push(texture);
  16801. var onerror = function (request, exception) {
  16802. scene._removePendingData(texture);
  16803. if (onError && request) {
  16804. onError(request.status + " " + request.statusText, exception);
  16805. }
  16806. };
  16807. var internalCallback = function (data) {
  16808. var width = texture.width;
  16809. var faceDataArrays = callback(data);
  16810. if (!faceDataArrays) {
  16811. return;
  16812. }
  16813. if (mipmapGenerator) {
  16814. var textureType = _this._getWebGLTextureType(type);
  16815. var internalFormat = _this._getInternalFormat(format);
  16816. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16817. var needConversion = false;
  16818. if (internalFormat === gl.RGB) {
  16819. internalFormat = gl.RGBA;
  16820. needConversion = true;
  16821. }
  16822. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16823. _this._unpackFlipY(false);
  16824. var mipData = mipmapGenerator(faceDataArrays);
  16825. for (var level = 0; level < mipData.length; level++) {
  16826. var mipSize = width >> level;
  16827. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16828. var mipFaceData = mipData[level][faceIndex];
  16829. if (needConversion) {
  16830. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16831. }
  16832. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16833. }
  16834. }
  16835. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16836. }
  16837. else {
  16838. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16839. }
  16840. texture.isReady = true;
  16841. // this.resetTextureCache();
  16842. scene._removePendingData(texture);
  16843. if (onLoad) {
  16844. onLoad();
  16845. }
  16846. };
  16847. this._loadFile(url, function (data) {
  16848. internalCallback(data);
  16849. }, undefined, scene.database, true, onerror);
  16850. return texture;
  16851. };
  16852. /**
  16853. * Update a raw 3D texture
  16854. * @param texture defines the texture to update
  16855. * @param data defines the data to store
  16856. * @param format defines the data format
  16857. * @param invertY defines if data must be stored with Y axis inverted
  16858. * @param compression defines the used compression (can be null)
  16859. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16860. */
  16861. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16862. if (compression === void 0) { compression = null; }
  16863. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16864. var internalType = this._getWebGLTextureType(textureType);
  16865. var internalFormat = this._getInternalFormat(format);
  16866. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16867. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16868. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16869. if (!this._doNotHandleContextLost) {
  16870. texture._bufferView = data;
  16871. texture.format = format;
  16872. texture.invertY = invertY;
  16873. texture._compression = compression;
  16874. }
  16875. if (texture.width % 4 !== 0) {
  16876. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16877. }
  16878. if (compression && data) {
  16879. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16880. }
  16881. else {
  16882. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16883. }
  16884. if (texture.generateMipMaps) {
  16885. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16886. }
  16887. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16888. // this.resetTextureCache();
  16889. texture.isReady = true;
  16890. };
  16891. /**
  16892. * Creates a new raw 3D texture
  16893. * @param data defines the data used to create the texture
  16894. * @param width defines the width of the texture
  16895. * @param height defines the height of the texture
  16896. * @param depth defines the depth of the texture
  16897. * @param format defines the format of the texture
  16898. * @param generateMipMaps defines if the engine must generate mip levels
  16899. * @param invertY defines if data must be stored with Y axis inverted
  16900. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16901. * @param compression defines the compressed used (can be null)
  16902. * @param textureType defines the compressed used (can be null)
  16903. * @returns a new raw 3D texture (stored in an InternalTexture)
  16904. */
  16905. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16906. if (compression === void 0) { compression = null; }
  16907. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16908. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16909. texture.baseWidth = width;
  16910. texture.baseHeight = height;
  16911. texture.baseDepth = depth;
  16912. texture.width = width;
  16913. texture.height = height;
  16914. texture.depth = depth;
  16915. texture.format = format;
  16916. texture.type = textureType;
  16917. texture.generateMipMaps = generateMipMaps;
  16918. texture.samplingMode = samplingMode;
  16919. texture.is3D = true;
  16920. if (!this._doNotHandleContextLost) {
  16921. texture._bufferView = data;
  16922. }
  16923. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16924. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16925. // Filters
  16926. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16927. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16928. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16929. if (generateMipMaps) {
  16930. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16931. }
  16932. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16933. this._internalTexturesCache.push(texture);
  16934. return texture;
  16935. };
  16936. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16937. var gl = this._gl;
  16938. if (!gl) {
  16939. return;
  16940. }
  16941. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16942. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16943. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16944. if (!noMipmap && !isCompressed) {
  16945. gl.generateMipmap(gl.TEXTURE_2D);
  16946. }
  16947. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16948. // this.resetTextureCache();
  16949. if (scene) {
  16950. scene._removePendingData(texture);
  16951. }
  16952. texture.onLoadedObservable.notifyObservers(texture);
  16953. texture.onLoadedObservable.clear();
  16954. };
  16955. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16956. var _this = this;
  16957. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16958. var maxTextureSize = this.getCaps().maxTextureSize;
  16959. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16960. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16961. var gl = this._gl;
  16962. if (!gl) {
  16963. return;
  16964. }
  16965. if (!texture._webGLTexture) {
  16966. // this.resetTextureCache();
  16967. if (scene) {
  16968. scene._removePendingData(texture);
  16969. }
  16970. return;
  16971. }
  16972. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16973. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16974. texture.baseWidth = width;
  16975. texture.baseHeight = height;
  16976. texture.width = potWidth;
  16977. texture.height = potHeight;
  16978. texture.isReady = true;
  16979. if (processFunction(potWidth, potHeight, function () {
  16980. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16981. })) {
  16982. // Returning as texture needs extra async steps
  16983. return;
  16984. }
  16985. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16986. };
  16987. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16988. // Create new RGBA data container.
  16989. var rgbaData;
  16990. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16991. rgbaData = new Float32Array(width * height * 4);
  16992. }
  16993. else {
  16994. rgbaData = new Uint32Array(width * height * 4);
  16995. }
  16996. // Convert each pixel.
  16997. for (var x = 0; x < width; x++) {
  16998. for (var y = 0; y < height; y++) {
  16999. var index = (y * width + x) * 3;
  17000. var newIndex = (y * width + x) * 4;
  17001. // Map Old Value to new value.
  17002. rgbaData[newIndex + 0] = rgbData[index + 0];
  17003. rgbaData[newIndex + 1] = rgbData[index + 1];
  17004. rgbaData[newIndex + 2] = rgbData[index + 2];
  17005. // Add fully opaque alpha channel.
  17006. rgbaData[newIndex + 3] = 1;
  17007. }
  17008. }
  17009. return rgbaData;
  17010. };
  17011. /** @hidden */
  17012. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17013. var gl = this._gl;
  17014. if (texture._framebuffer) {
  17015. gl.deleteFramebuffer(texture._framebuffer);
  17016. texture._framebuffer = null;
  17017. }
  17018. if (texture._depthStencilBuffer) {
  17019. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17020. texture._depthStencilBuffer = null;
  17021. }
  17022. if (texture._MSAAFramebuffer) {
  17023. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17024. texture._MSAAFramebuffer = null;
  17025. }
  17026. if (texture._MSAARenderBuffer) {
  17027. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17028. texture._MSAARenderBuffer = null;
  17029. }
  17030. };
  17031. /** @hidden */
  17032. Engine.prototype._releaseTexture = function (texture) {
  17033. var gl = this._gl;
  17034. this._releaseFramebufferObjects(texture);
  17035. gl.deleteTexture(texture._webGLTexture);
  17036. // Unbind channels
  17037. this.unbindAllTextures();
  17038. var index = this._internalTexturesCache.indexOf(texture);
  17039. if (index !== -1) {
  17040. this._internalTexturesCache.splice(index, 1);
  17041. }
  17042. // Integrated fixed lod samplers.
  17043. if (texture._lodTextureHigh) {
  17044. texture._lodTextureHigh.dispose();
  17045. }
  17046. if (texture._lodTextureMid) {
  17047. texture._lodTextureMid.dispose();
  17048. }
  17049. if (texture._lodTextureLow) {
  17050. texture._lodTextureLow.dispose();
  17051. }
  17052. // Set output texture of post process to null if the texture has been released/disposed
  17053. this.scenes.forEach(function (scene) {
  17054. scene.postProcesses.forEach(function (postProcess) {
  17055. if (postProcess._outputTexture == texture) {
  17056. postProcess._outputTexture = null;
  17057. }
  17058. });
  17059. scene.cameras.forEach(function (camera) {
  17060. camera._postProcesses.forEach(function (postProcess) {
  17061. if (postProcess) {
  17062. if (postProcess._outputTexture == texture) {
  17063. postProcess._outputTexture = null;
  17064. }
  17065. }
  17066. });
  17067. });
  17068. });
  17069. };
  17070. Engine.prototype.setProgram = function (program) {
  17071. if (this._currentProgram !== program) {
  17072. this._gl.useProgram(program);
  17073. this._currentProgram = program;
  17074. }
  17075. };
  17076. /**
  17077. * Binds an effect to the webGL context
  17078. * @param effect defines the effect to bind
  17079. */
  17080. Engine.prototype.bindSamplers = function (effect) {
  17081. this.setProgram(effect.getProgram());
  17082. var samplers = effect.getSamplers();
  17083. for (var index = 0; index < samplers.length; index++) {
  17084. var uniform = effect.getUniform(samplers[index]);
  17085. if (uniform) {
  17086. this._boundUniforms[index] = uniform;
  17087. }
  17088. }
  17089. this._currentEffect = null;
  17090. };
  17091. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17092. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17093. return;
  17094. }
  17095. // Remove
  17096. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17097. // Bind last to it
  17098. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17099. // Bind to dummy
  17100. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17101. };
  17102. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17103. if (!internalTexture) {
  17104. return -1;
  17105. }
  17106. internalTexture._initialSlot = channel;
  17107. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17108. if (channel !== internalTexture._designatedSlot) {
  17109. this._textureCollisions.addCount(1, false);
  17110. }
  17111. }
  17112. else {
  17113. if (channel !== internalTexture._designatedSlot) {
  17114. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17115. return internalTexture._designatedSlot;
  17116. }
  17117. else {
  17118. // No slot for this texture, let's pick a new one (if we find a free slot)
  17119. if (this._nextFreeTextureSlots.length) {
  17120. return this._nextFreeTextureSlots[0];
  17121. }
  17122. // We need to recycle the oldest bound texture, sorry.
  17123. this._textureCollisions.addCount(1, false);
  17124. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17125. }
  17126. }
  17127. }
  17128. return channel;
  17129. };
  17130. Engine.prototype._linkTrackers = function (previous, next) {
  17131. previous.next = next;
  17132. next.previous = previous;
  17133. };
  17134. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17135. var currentSlot = internalTexture._designatedSlot;
  17136. if (currentSlot === -1) {
  17137. return -1;
  17138. }
  17139. internalTexture._designatedSlot = -1;
  17140. if (this.disableTextureBindingOptimization) {
  17141. return -1;
  17142. }
  17143. // Remove from bound list
  17144. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17145. // Free the slot
  17146. this._boundTexturesCache[currentSlot] = null;
  17147. this._nextFreeTextureSlots.push(currentSlot);
  17148. return currentSlot;
  17149. };
  17150. Engine.prototype._activateCurrentTexture = function () {
  17151. if (this._currentTextureChannel !== this._activeChannel) {
  17152. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17153. this._currentTextureChannel = this._activeChannel;
  17154. }
  17155. };
  17156. /** @hidden */
  17157. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17158. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17159. if (force === void 0) { force = false; }
  17160. var wasPreviouslyBound = false;
  17161. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17162. this._activeChannel = texture._designatedSlot;
  17163. }
  17164. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17165. var isTextureForRendering = texture && texture._initialSlot > -1;
  17166. if (currentTextureBound !== texture || force) {
  17167. if (currentTextureBound) {
  17168. this._removeDesignatedSlot(currentTextureBound);
  17169. }
  17170. this._activateCurrentTexture();
  17171. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17172. this._boundTexturesCache[this._activeChannel] = texture;
  17173. if (texture) {
  17174. if (!this.disableTextureBindingOptimization) {
  17175. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17176. if (slotIndex > -1) {
  17177. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17178. }
  17179. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17180. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17181. }
  17182. texture._designatedSlot = this._activeChannel;
  17183. }
  17184. }
  17185. else if (forTextureDataUpdate) {
  17186. wasPreviouslyBound = true;
  17187. this._activateCurrentTexture();
  17188. }
  17189. if (isTextureForRendering && !forTextureDataUpdate) {
  17190. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17191. }
  17192. return wasPreviouslyBound;
  17193. };
  17194. /** @hidden */
  17195. Engine.prototype._bindTexture = function (channel, texture) {
  17196. if (channel < 0) {
  17197. return;
  17198. }
  17199. if (texture) {
  17200. channel = this._getCorrectTextureChannel(channel, texture);
  17201. }
  17202. this._activeChannel = channel;
  17203. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17204. };
  17205. /**
  17206. * Sets a texture to the webGL context from a postprocess
  17207. * @param channel defines the channel to use
  17208. * @param postProcess defines the source postprocess
  17209. */
  17210. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17211. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17212. };
  17213. /**
  17214. * Binds the output of the passed in post process to the texture channel specified
  17215. * @param channel The channel the texture should be bound to
  17216. * @param postProcess The post process which's output should be bound
  17217. */
  17218. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17219. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17220. };
  17221. /**
  17222. * Unbind all textures from the webGL context
  17223. */
  17224. Engine.prototype.unbindAllTextures = function () {
  17225. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17226. this._activeChannel = channel;
  17227. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17228. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17229. if (this.webGLVersion > 1) {
  17230. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17231. }
  17232. }
  17233. };
  17234. /**
  17235. * Sets a texture to the according uniform.
  17236. * @param channel The texture channel
  17237. * @param uniform The uniform to set
  17238. * @param texture The texture to apply
  17239. */
  17240. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17241. if (channel < 0) {
  17242. return;
  17243. }
  17244. if (uniform) {
  17245. this._boundUniforms[channel] = uniform;
  17246. }
  17247. this._setTexture(channel, texture);
  17248. };
  17249. /**
  17250. * Sets a depth stencil texture from a render target to the according uniform.
  17251. * @param channel The texture channel
  17252. * @param uniform The uniform to set
  17253. * @param texture The render target texture containing the depth stencil texture to apply
  17254. */
  17255. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17256. if (channel < 0) {
  17257. return;
  17258. }
  17259. if (uniform) {
  17260. this._boundUniforms[channel] = uniform;
  17261. }
  17262. if (!texture || !texture.depthStencilTexture) {
  17263. this._setTexture(channel, null);
  17264. }
  17265. else {
  17266. this._setTexture(channel, texture, false, true);
  17267. }
  17268. };
  17269. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17270. var uniform = this._boundUniforms[sourceSlot];
  17271. if (uniform._currentState === destination) {
  17272. return;
  17273. }
  17274. this._gl.uniform1i(uniform, destination);
  17275. uniform._currentState = destination;
  17276. };
  17277. Engine.prototype._getTextureWrapMode = function (mode) {
  17278. switch (mode) {
  17279. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17280. return this._gl.REPEAT;
  17281. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17282. return this._gl.CLAMP_TO_EDGE;
  17283. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17284. return this._gl.MIRRORED_REPEAT;
  17285. }
  17286. return this._gl.REPEAT;
  17287. };
  17288. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17289. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17290. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17291. // Not ready?
  17292. if (!texture) {
  17293. if (this._boundTexturesCache[channel] != null) {
  17294. this._activeChannel = channel;
  17295. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17296. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17297. if (this.webGLVersion > 1) {
  17298. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17299. }
  17300. }
  17301. return false;
  17302. }
  17303. // Video
  17304. if (texture.video) {
  17305. this._activeChannel = channel;
  17306. texture.update();
  17307. }
  17308. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17309. texture.delayLoad();
  17310. return false;
  17311. }
  17312. var internalTexture;
  17313. if (depthStencilTexture) {
  17314. internalTexture = texture.depthStencilTexture;
  17315. }
  17316. else if (texture.isReady()) {
  17317. internalTexture = texture.getInternalTexture();
  17318. }
  17319. else if (texture.isCube) {
  17320. internalTexture = this.emptyCubeTexture;
  17321. }
  17322. else if (texture.is3D) {
  17323. internalTexture = this.emptyTexture3D;
  17324. }
  17325. else {
  17326. internalTexture = this.emptyTexture;
  17327. }
  17328. if (!isPartOfTextureArray) {
  17329. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17330. }
  17331. var needToBind = true;
  17332. if (this._boundTexturesCache[channel] === internalTexture) {
  17333. this._moveBoundTextureOnTop(internalTexture);
  17334. if (!isPartOfTextureArray) {
  17335. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17336. }
  17337. needToBind = false;
  17338. }
  17339. this._activeChannel = channel;
  17340. if (internalTexture && internalTexture.is3D) {
  17341. if (needToBind) {
  17342. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17343. }
  17344. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17345. internalTexture._cachedWrapU = texture.wrapU;
  17346. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17347. }
  17348. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17349. internalTexture._cachedWrapV = texture.wrapV;
  17350. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17351. }
  17352. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17353. internalTexture._cachedWrapR = texture.wrapR;
  17354. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17355. }
  17356. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17357. }
  17358. else if (internalTexture && internalTexture.isCube) {
  17359. if (needToBind) {
  17360. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17361. }
  17362. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17363. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17364. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17365. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17366. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17367. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17368. }
  17369. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17370. }
  17371. else {
  17372. if (needToBind) {
  17373. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17374. }
  17375. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17376. internalTexture._cachedWrapU = texture.wrapU;
  17377. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17378. }
  17379. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17380. internalTexture._cachedWrapV = texture.wrapV;
  17381. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17382. }
  17383. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17384. }
  17385. return true;
  17386. };
  17387. /**
  17388. * Sets an array of texture to the webGL context
  17389. * @param channel defines the channel where the texture array must be set
  17390. * @param uniform defines the associated uniform location
  17391. * @param textures defines the array of textures to bind
  17392. */
  17393. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17394. if (channel < 0 || !uniform) {
  17395. return;
  17396. }
  17397. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17398. this._textureUnits = new Int32Array(textures.length);
  17399. }
  17400. for (var i = 0; i < textures.length; i++) {
  17401. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17402. }
  17403. this._gl.uniform1iv(uniform, this._textureUnits);
  17404. for (var index = 0; index < textures.length; index++) {
  17405. this._setTexture(this._textureUnits[index], textures[index], true);
  17406. }
  17407. };
  17408. /** @hidden */
  17409. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17410. var internalTexture = texture.getInternalTexture();
  17411. if (!internalTexture) {
  17412. return;
  17413. }
  17414. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17415. var value = texture.anisotropicFilteringLevel;
  17416. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17417. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17418. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17419. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17420. }
  17421. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17422. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17423. internalTexture._cachedAnisotropicFilteringLevel = value;
  17424. }
  17425. };
  17426. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17427. this._bindTextureDirectly(target, texture, true, true);
  17428. this._gl.texParameterf(target, parameter, value);
  17429. };
  17430. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17431. if (texture) {
  17432. this._bindTextureDirectly(target, texture, true, true);
  17433. }
  17434. this._gl.texParameteri(target, parameter, value);
  17435. };
  17436. /**
  17437. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17438. * @param x defines the x coordinate of the rectangle where pixels must be read
  17439. * @param y defines the y coordinate of the rectangle where pixels must be read
  17440. * @param width defines the width of the rectangle where pixels must be read
  17441. * @param height defines the height of the rectangle where pixels must be read
  17442. * @returns a Uint8Array containing RGBA colors
  17443. */
  17444. Engine.prototype.readPixels = function (x, y, width, height) {
  17445. var data = new Uint8Array(height * width * 4);
  17446. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17447. return data;
  17448. };
  17449. /**
  17450. * Add an externaly attached data from its key.
  17451. * This method call will fail and return false, if such key already exists.
  17452. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17453. * @param key the unique key that identifies the data
  17454. * @param data the data object to associate to the key for this Engine instance
  17455. * @return true if no such key were already present and the data was added successfully, false otherwise
  17456. */
  17457. Engine.prototype.addExternalData = function (key, data) {
  17458. if (!this._externalData) {
  17459. this._externalData = new BABYLON.StringDictionary();
  17460. }
  17461. return this._externalData.add(key, data);
  17462. };
  17463. /**
  17464. * Get an externaly attached data from its key
  17465. * @param key the unique key that identifies the data
  17466. * @return the associated data, if present (can be null), or undefined if not present
  17467. */
  17468. Engine.prototype.getExternalData = function (key) {
  17469. if (!this._externalData) {
  17470. this._externalData = new BABYLON.StringDictionary();
  17471. }
  17472. return this._externalData.get(key);
  17473. };
  17474. /**
  17475. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17476. * @param key the unique key that identifies the data
  17477. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17478. * @return the associated data, can be null if the factory returned null.
  17479. */
  17480. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17481. if (!this._externalData) {
  17482. this._externalData = new BABYLON.StringDictionary();
  17483. }
  17484. return this._externalData.getOrAddWithFactory(key, factory);
  17485. };
  17486. /**
  17487. * Remove an externaly attached data from the Engine instance
  17488. * @param key the unique key that identifies the data
  17489. * @return true if the data was successfully removed, false if it doesn't exist
  17490. */
  17491. Engine.prototype.removeExternalData = function (key) {
  17492. if (!this._externalData) {
  17493. this._externalData = new BABYLON.StringDictionary();
  17494. }
  17495. return this._externalData.remove(key);
  17496. };
  17497. /**
  17498. * Unbind all vertex attributes from the webGL context
  17499. */
  17500. Engine.prototype.unbindAllAttributes = function () {
  17501. if (this._mustWipeVertexAttributes) {
  17502. this._mustWipeVertexAttributes = false;
  17503. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17504. this._gl.disableVertexAttribArray(i);
  17505. this._vertexAttribArraysEnabled[i] = false;
  17506. this._currentBufferPointers[i].active = false;
  17507. }
  17508. return;
  17509. }
  17510. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17511. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17512. continue;
  17513. }
  17514. this._gl.disableVertexAttribArray(i);
  17515. this._vertexAttribArraysEnabled[i] = false;
  17516. this._currentBufferPointers[i].active = false;
  17517. }
  17518. };
  17519. /**
  17520. * 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
  17521. */
  17522. Engine.prototype.releaseEffects = function () {
  17523. for (var name in this._compiledEffects) {
  17524. this._deleteProgram(this._compiledEffects[name]._program);
  17525. }
  17526. this._compiledEffects = {};
  17527. };
  17528. /**
  17529. * Dispose and release all associated resources
  17530. */
  17531. Engine.prototype.dispose = function () {
  17532. this.hideLoadingUI();
  17533. this.stopRenderLoop();
  17534. // Release postProcesses
  17535. while (this.postProcesses.length) {
  17536. this.postProcesses[0].dispose();
  17537. }
  17538. // Empty texture
  17539. if (this._emptyTexture) {
  17540. this._releaseTexture(this._emptyTexture);
  17541. this._emptyTexture = null;
  17542. }
  17543. if (this._emptyCubeTexture) {
  17544. this._releaseTexture(this._emptyCubeTexture);
  17545. this._emptyCubeTexture = null;
  17546. }
  17547. // Rescale PP
  17548. if (this._rescalePostProcess) {
  17549. this._rescalePostProcess.dispose();
  17550. }
  17551. // Release scenes
  17552. while (this.scenes.length) {
  17553. this.scenes[0].dispose();
  17554. }
  17555. // Release audio engine
  17556. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17557. Engine.audioEngine.dispose();
  17558. }
  17559. // Release effects
  17560. this.releaseEffects();
  17561. // Unbind
  17562. this.unbindAllAttributes();
  17563. this._boundUniforms = [];
  17564. if (this._dummyFramebuffer) {
  17565. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17566. }
  17567. //WebVR
  17568. this.disableVR();
  17569. // Events
  17570. if (BABYLON.Tools.IsWindowObjectExist()) {
  17571. window.removeEventListener("blur", this._onBlur);
  17572. window.removeEventListener("focus", this._onFocus);
  17573. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17574. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17575. if (this._renderingCanvas) {
  17576. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17577. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17578. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17579. if (!this._doNotHandleContextLost) {
  17580. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17581. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17582. }
  17583. }
  17584. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17585. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17586. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17587. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17588. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17589. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17590. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17591. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17592. if (this._onVrDisplayConnect) {
  17593. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17594. if (this._onVrDisplayDisconnect) {
  17595. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17596. }
  17597. if (this._onVrDisplayPresentChange) {
  17598. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17599. }
  17600. this._onVrDisplayConnect = null;
  17601. this._onVrDisplayDisconnect = null;
  17602. }
  17603. }
  17604. // Remove from Instances
  17605. var index = Engine.Instances.indexOf(this);
  17606. if (index >= 0) {
  17607. Engine.Instances.splice(index, 1);
  17608. }
  17609. this._workingCanvas = null;
  17610. this._workingContext = null;
  17611. this._currentBufferPointers = [];
  17612. this._renderingCanvas = null;
  17613. this._currentProgram = null;
  17614. this._bindedRenderFunction = null;
  17615. this.onResizeObservable.clear();
  17616. this.onCanvasBlurObservable.clear();
  17617. this.onCanvasFocusObservable.clear();
  17618. this.onCanvasPointerOutObservable.clear();
  17619. this.onBeginFrameObservable.clear();
  17620. this.onEndFrameObservable.clear();
  17621. BABYLON.Effect.ResetCache();
  17622. // Abort active requests
  17623. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17624. var request = _a[_i];
  17625. request.abort();
  17626. }
  17627. };
  17628. // Loading screen
  17629. /**
  17630. * Display the loading screen
  17631. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17632. */
  17633. Engine.prototype.displayLoadingUI = function () {
  17634. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17635. return;
  17636. }
  17637. var loadingScreen = this.loadingScreen;
  17638. if (loadingScreen) {
  17639. loadingScreen.displayLoadingUI();
  17640. }
  17641. };
  17642. /**
  17643. * Hide the loading screen
  17644. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17645. */
  17646. Engine.prototype.hideLoadingUI = function () {
  17647. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17648. return;
  17649. }
  17650. var loadingScreen = this.loadingScreen;
  17651. if (loadingScreen) {
  17652. loadingScreen.hideLoadingUI();
  17653. }
  17654. };
  17655. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17656. /**
  17657. * Gets the current loading screen object
  17658. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17659. */
  17660. get: function () {
  17661. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17662. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17663. }
  17664. return this._loadingScreen;
  17665. },
  17666. /**
  17667. * Sets the current loading screen object
  17668. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17669. */
  17670. set: function (loadingScreen) {
  17671. this._loadingScreen = loadingScreen;
  17672. },
  17673. enumerable: true,
  17674. configurable: true
  17675. });
  17676. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17677. /**
  17678. * Sets the current loading screen text
  17679. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17680. */
  17681. set: function (text) {
  17682. this.loadingScreen.loadingUIText = text;
  17683. },
  17684. enumerable: true,
  17685. configurable: true
  17686. });
  17687. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17688. /**
  17689. * Sets the current loading screen background color
  17690. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17691. */
  17692. set: function (color) {
  17693. this.loadingScreen.loadingUIBackgroundColor = color;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. /**
  17699. * Attach a new callback raised when context lost event is fired
  17700. * @param callback defines the callback to call
  17701. */
  17702. Engine.prototype.attachContextLostEvent = function (callback) {
  17703. if (this._renderingCanvas) {
  17704. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17705. }
  17706. };
  17707. /**
  17708. * Attach a new callback raised when context restored event is fired
  17709. * @param callback defines the callback to call
  17710. */
  17711. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17712. if (this._renderingCanvas) {
  17713. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17714. }
  17715. };
  17716. /**
  17717. * Gets the source code of the vertex shader associated with a specific webGL program
  17718. * @param program defines the program to use
  17719. * @returns a string containing the source code of the vertex shader associated with the program
  17720. */
  17721. Engine.prototype.getVertexShaderSource = function (program) {
  17722. var shaders = this._gl.getAttachedShaders(program);
  17723. if (!shaders) {
  17724. return null;
  17725. }
  17726. return this._gl.getShaderSource(shaders[0]);
  17727. };
  17728. /**
  17729. * Gets the source code of the fragment shader associated with a specific webGL program
  17730. * @param program defines the program to use
  17731. * @returns a string containing the source code of the fragment shader associated with the program
  17732. */
  17733. Engine.prototype.getFragmentShaderSource = function (program) {
  17734. var shaders = this._gl.getAttachedShaders(program);
  17735. if (!shaders) {
  17736. return null;
  17737. }
  17738. return this._gl.getShaderSource(shaders[1]);
  17739. };
  17740. /**
  17741. * Get the current error code of the webGL context
  17742. * @returns the error code
  17743. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17744. */
  17745. Engine.prototype.getError = function () {
  17746. return this._gl.getError();
  17747. };
  17748. // FPS
  17749. /**
  17750. * Gets the current framerate
  17751. * @returns a number representing the framerate
  17752. */
  17753. Engine.prototype.getFps = function () {
  17754. return this._fps;
  17755. };
  17756. /**
  17757. * Gets the time spent between current and previous frame
  17758. * @returns a number representing the delta time in ms
  17759. */
  17760. Engine.prototype.getDeltaTime = function () {
  17761. return this._deltaTime;
  17762. };
  17763. Engine.prototype._measureFps = function () {
  17764. this._performanceMonitor.sampleFrame();
  17765. this._fps = this._performanceMonitor.averageFPS;
  17766. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17767. };
  17768. /** @hidden */
  17769. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17770. if (faceIndex === void 0) { faceIndex = -1; }
  17771. if (level === void 0) { level = 0; }
  17772. if (buffer === void 0) { buffer = null; }
  17773. var gl = this._gl;
  17774. if (!this._dummyFramebuffer) {
  17775. var dummy = gl.createFramebuffer();
  17776. if (!dummy) {
  17777. throw new Error("Unable to create dummy framebuffer");
  17778. }
  17779. this._dummyFramebuffer = dummy;
  17780. }
  17781. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17782. if (faceIndex > -1) {
  17783. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17784. }
  17785. else {
  17786. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17787. }
  17788. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17789. switch (readType) {
  17790. case gl.UNSIGNED_BYTE:
  17791. if (!buffer) {
  17792. buffer = new Uint8Array(4 * width * height);
  17793. }
  17794. readType = gl.UNSIGNED_BYTE;
  17795. break;
  17796. default:
  17797. if (!buffer) {
  17798. buffer = new Float32Array(4 * width * height);
  17799. }
  17800. readType = gl.FLOAT;
  17801. break;
  17802. }
  17803. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17804. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17805. return buffer;
  17806. };
  17807. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17808. if (this._webGLVersion > 1) {
  17809. return this._caps.colorBufferFloat;
  17810. }
  17811. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17812. };
  17813. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17814. if (this._webGLVersion > 1) {
  17815. return this._caps.colorBufferFloat;
  17816. }
  17817. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17818. };
  17819. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17820. Engine.prototype._canRenderToFramebuffer = function (type) {
  17821. var gl = this._gl;
  17822. //clear existing errors
  17823. while (gl.getError() !== gl.NO_ERROR) { }
  17824. var successful = true;
  17825. var texture = gl.createTexture();
  17826. gl.bindTexture(gl.TEXTURE_2D, texture);
  17827. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17828. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17829. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17830. var fb = gl.createFramebuffer();
  17831. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17832. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17833. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17834. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17835. successful = successful && (gl.getError() === gl.NO_ERROR);
  17836. //try render by clearing frame buffer's color buffer
  17837. if (successful) {
  17838. gl.clear(gl.COLOR_BUFFER_BIT);
  17839. successful = successful && (gl.getError() === gl.NO_ERROR);
  17840. }
  17841. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17842. if (successful) {
  17843. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17844. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17845. var readFormat = gl.RGBA;
  17846. var readType = gl.UNSIGNED_BYTE;
  17847. var buffer = new Uint8Array(4);
  17848. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17849. successful = successful && (gl.getError() === gl.NO_ERROR);
  17850. }
  17851. //clean up
  17852. gl.deleteTexture(texture);
  17853. gl.deleteFramebuffer(fb);
  17854. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17855. //clear accumulated errors
  17856. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17857. return successful;
  17858. };
  17859. /** @hidden */
  17860. Engine.prototype._getWebGLTextureType = function (type) {
  17861. if (this._webGLVersion === 1) {
  17862. switch (type) {
  17863. case Engine.TEXTURETYPE_FLOAT:
  17864. return this._gl.FLOAT;
  17865. case Engine.TEXTURETYPE_HALF_FLOAT:
  17866. return this._gl.HALF_FLOAT_OES;
  17867. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17868. return this._gl.UNSIGNED_BYTE;
  17869. }
  17870. return this._gl.UNSIGNED_BYTE;
  17871. }
  17872. switch (type) {
  17873. case Engine.TEXTURETYPE_BYTE:
  17874. return this._gl.BYTE;
  17875. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17876. return this._gl.UNSIGNED_BYTE;
  17877. case Engine.TEXTURETYPE_SHORT:
  17878. return this._gl.SHORT;
  17879. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17880. return this._gl.UNSIGNED_SHORT;
  17881. case Engine.TEXTURETYPE_INT:
  17882. return this._gl.INT;
  17883. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17884. return this._gl.UNSIGNED_INT;
  17885. case Engine.TEXTURETYPE_FLOAT:
  17886. return this._gl.FLOAT;
  17887. case Engine.TEXTURETYPE_HALF_FLOAT:
  17888. return this._gl.HALF_FLOAT;
  17889. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17890. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17891. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17892. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17893. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17894. return this._gl.UNSIGNED_SHORT_5_6_5;
  17895. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17896. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17897. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17898. return this._gl.UNSIGNED_INT_24_8;
  17899. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17900. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17901. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17902. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17903. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17904. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17905. }
  17906. return this._gl.UNSIGNED_BYTE;
  17907. };
  17908. Engine.prototype._getInternalFormat = function (format) {
  17909. var internalFormat = this._gl.RGBA;
  17910. switch (format) {
  17911. case Engine.TEXTUREFORMAT_ALPHA:
  17912. internalFormat = this._gl.ALPHA;
  17913. break;
  17914. case Engine.TEXTUREFORMAT_LUMINANCE:
  17915. internalFormat = this._gl.LUMINANCE;
  17916. break;
  17917. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17918. internalFormat = this._gl.LUMINANCE_ALPHA;
  17919. break;
  17920. case Engine.TEXTUREFORMAT_RED:
  17921. internalFormat = this._gl.RED;
  17922. break;
  17923. case Engine.TEXTUREFORMAT_RG:
  17924. internalFormat = this._gl.RG;
  17925. break;
  17926. case Engine.TEXTUREFORMAT_RGB:
  17927. internalFormat = this._gl.RGB;
  17928. break;
  17929. case Engine.TEXTUREFORMAT_RGBA:
  17930. internalFormat = this._gl.RGBA;
  17931. break;
  17932. }
  17933. if (this._webGLVersion > 1) {
  17934. switch (format) {
  17935. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17936. internalFormat = this._gl.RED_INTEGER;
  17937. break;
  17938. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17939. internalFormat = this._gl.RG_INTEGER;
  17940. break;
  17941. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17942. internalFormat = this._gl.RGB_INTEGER;
  17943. break;
  17944. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17945. internalFormat = this._gl.RGBA_INTEGER;
  17946. break;
  17947. }
  17948. }
  17949. return internalFormat;
  17950. };
  17951. /** @hidden */
  17952. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17953. if (this._webGLVersion === 1) {
  17954. if (format !== undefined) {
  17955. switch (format) {
  17956. case Engine.TEXTUREFORMAT_ALPHA:
  17957. return this._gl.ALPHA;
  17958. case Engine.TEXTUREFORMAT_LUMINANCE:
  17959. return this._gl.LUMINANCE;
  17960. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17961. return this._gl.LUMINANCE_ALPHA;
  17962. }
  17963. }
  17964. return this._gl.RGBA;
  17965. }
  17966. switch (type) {
  17967. case Engine.TEXTURETYPE_BYTE:
  17968. switch (format) {
  17969. case Engine.TEXTUREFORMAT_RED:
  17970. return this._gl.R8_SNORM;
  17971. case Engine.TEXTUREFORMAT_RG:
  17972. return this._gl.RG8_SNORM;
  17973. case Engine.TEXTUREFORMAT_RGB:
  17974. return this._gl.RGB8_SNORM;
  17975. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17976. return this._gl.R8I;
  17977. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17978. return this._gl.RG8I;
  17979. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17980. return this._gl.RGB8I;
  17981. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17982. return this._gl.RGBA8I;
  17983. default:
  17984. return this._gl.RGBA8_SNORM;
  17985. }
  17986. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17987. switch (format) {
  17988. case Engine.TEXTUREFORMAT_RED:
  17989. return this._gl.R8;
  17990. case Engine.TEXTUREFORMAT_RG:
  17991. return this._gl.RG8;
  17992. case Engine.TEXTUREFORMAT_RGB:
  17993. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17994. case Engine.TEXTUREFORMAT_RGBA:
  17995. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17996. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17997. return this._gl.R8UI;
  17998. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17999. return this._gl.RG8UI;
  18000. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18001. return this._gl.RGB8UI;
  18002. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18003. return this._gl.RGBA8UI;
  18004. default:
  18005. return this._gl.RGBA8;
  18006. }
  18007. case Engine.TEXTURETYPE_SHORT:
  18008. switch (format) {
  18009. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18010. return this._gl.R16I;
  18011. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18012. return this._gl.RG16I;
  18013. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18014. return this._gl.RGB16I;
  18015. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18016. return this._gl.RGBA16I;
  18017. default:
  18018. return this._gl.RGBA16I;
  18019. }
  18020. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18021. switch (format) {
  18022. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18023. return this._gl.R16UI;
  18024. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18025. return this._gl.RG16UI;
  18026. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18027. return this._gl.RGB16UI;
  18028. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18029. return this._gl.RGBA16UI;
  18030. default:
  18031. return this._gl.RGBA16UI;
  18032. }
  18033. case Engine.TEXTURETYPE_INT:
  18034. switch (format) {
  18035. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18036. return this._gl.R32I;
  18037. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18038. return this._gl.RG32I;
  18039. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18040. return this._gl.RGB32I;
  18041. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18042. return this._gl.RGBA32I;
  18043. default:
  18044. return this._gl.RGBA32I;
  18045. }
  18046. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18047. switch (format) {
  18048. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18049. return this._gl.R32UI;
  18050. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18051. return this._gl.RG32UI;
  18052. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18053. return this._gl.RGB32UI;
  18054. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18055. return this._gl.RGBA32UI;
  18056. default:
  18057. return this._gl.RGBA32UI;
  18058. }
  18059. case Engine.TEXTURETYPE_FLOAT:
  18060. switch (format) {
  18061. case Engine.TEXTUREFORMAT_RED:
  18062. return this._gl.R32F; // By default. Other possibility is R16F.
  18063. case Engine.TEXTUREFORMAT_RG:
  18064. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18065. case Engine.TEXTUREFORMAT_RGB:
  18066. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18067. case Engine.TEXTUREFORMAT_RGBA:
  18068. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18069. default:
  18070. return this._gl.RGBA32F;
  18071. }
  18072. case Engine.TEXTURETYPE_HALF_FLOAT:
  18073. switch (format) {
  18074. case Engine.TEXTUREFORMAT_RED:
  18075. return this._gl.R16F;
  18076. case Engine.TEXTUREFORMAT_RG:
  18077. return this._gl.RG16F;
  18078. case Engine.TEXTUREFORMAT_RGB:
  18079. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18080. case Engine.TEXTUREFORMAT_RGBA:
  18081. return this._gl.RGBA16F;
  18082. default:
  18083. return this._gl.RGBA16F;
  18084. }
  18085. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18086. return this._gl.RGB565;
  18087. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18088. return this._gl.R11F_G11F_B10F;
  18089. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18090. return this._gl.RGB9_E5;
  18091. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18092. return this._gl.RGBA4;
  18093. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18094. return this._gl.RGB5_A1;
  18095. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18096. switch (format) {
  18097. case Engine.TEXTUREFORMAT_RGBA:
  18098. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18099. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18100. return this._gl.RGB10_A2UI;
  18101. default:
  18102. return this._gl.RGB10_A2;
  18103. }
  18104. }
  18105. return this._gl.RGBA8;
  18106. };
  18107. /** @hidden */
  18108. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18109. if (type === Engine.TEXTURETYPE_FLOAT) {
  18110. return this._gl.RGBA32F;
  18111. }
  18112. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18113. return this._gl.RGBA16F;
  18114. }
  18115. return this._gl.RGBA8;
  18116. };
  18117. /** @hidden */
  18118. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  18119. var _this = this;
  18120. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  18121. this._activeRequests.push(request);
  18122. request.onCompleteObservable.add(function (request) {
  18123. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18124. });
  18125. return request;
  18126. };
  18127. /** @hidden */
  18128. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  18129. var _this = this;
  18130. return new Promise(function (resolve, reject) {
  18131. _this._loadFile(url, function (data) {
  18132. resolve(data);
  18133. }, undefined, database, useArrayBuffer, function (request, exception) {
  18134. reject(exception);
  18135. });
  18136. });
  18137. };
  18138. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18139. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18140. var onload = function (data) {
  18141. loadedFiles[index] = data;
  18142. loadedFiles._internalCount++;
  18143. if (loadedFiles._internalCount === 6) {
  18144. onfinish(loadedFiles);
  18145. }
  18146. };
  18147. var onerror = function (request, exception) {
  18148. if (onErrorCallBack && request) {
  18149. onErrorCallBack(request.status + " " + request.statusText, exception);
  18150. }
  18151. };
  18152. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18153. };
  18154. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18155. if (onError === void 0) { onError = null; }
  18156. var loadedFiles = [];
  18157. loadedFiles._internalCount = 0;
  18158. for (var index = 0; index < 6; index++) {
  18159. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18160. }
  18161. };
  18162. // Statics
  18163. /**
  18164. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18165. * @returns true if the engine can be created
  18166. * @ignorenaming
  18167. */
  18168. Engine.isSupported = function () {
  18169. try {
  18170. var tempcanvas = document.createElement("canvas");
  18171. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18172. return gl != null && !!window.WebGLRenderingContext;
  18173. }
  18174. catch (e) {
  18175. return false;
  18176. }
  18177. };
  18178. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18179. Engine.ExceptionList = [
  18180. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18181. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18182. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18183. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18184. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18185. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18186. ];
  18187. /** Gets the list of created engines */
  18188. Engine.Instances = new Array();
  18189. /**
  18190. * Hidden
  18191. */
  18192. Engine._TextureLoaders = [];
  18193. // Const statics
  18194. /** Defines that alpha blending is disabled */
  18195. Engine.ALPHA_DISABLE = 0;
  18196. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18197. Engine.ALPHA_ADD = 1;
  18198. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18199. Engine.ALPHA_COMBINE = 2;
  18200. /** Defines that alpha blending to DEST - SRC * DEST */
  18201. Engine.ALPHA_SUBTRACT = 3;
  18202. /** Defines that alpha blending to SRC * DEST */
  18203. Engine.ALPHA_MULTIPLY = 4;
  18204. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18205. Engine.ALPHA_MAXIMIZED = 5;
  18206. /** Defines that alpha blending to SRC + DEST */
  18207. Engine.ALPHA_ONEONE = 6;
  18208. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18209. Engine.ALPHA_PREMULTIPLIED = 7;
  18210. /**
  18211. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18212. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18213. */
  18214. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18215. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18216. Engine.ALPHA_INTERPOLATE = 9;
  18217. /**
  18218. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18219. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18220. */
  18221. Engine.ALPHA_SCREENMODE = 10;
  18222. /** Defines that the ressource is not delayed*/
  18223. Engine.DELAYLOADSTATE_NONE = 0;
  18224. /** Defines that the ressource was successfully delay loaded */
  18225. Engine.DELAYLOADSTATE_LOADED = 1;
  18226. /** Defines that the ressource is currently delay loading */
  18227. Engine.DELAYLOADSTATE_LOADING = 2;
  18228. /** Defines that the ressource is delayed and has not started loading */
  18229. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18230. // Depht or Stencil test Constants.
  18231. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18232. Engine.NEVER = 0x0200;
  18233. /** 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 */
  18234. Engine.ALWAYS = 0x0207;
  18235. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18236. Engine.LESS = 0x0201;
  18237. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18238. Engine.EQUAL = 0x0202;
  18239. /** 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 */
  18240. Engine.LEQUAL = 0x0203;
  18241. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18242. Engine.GREATER = 0x0204;
  18243. /** 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 */
  18244. Engine.GEQUAL = 0x0206;
  18245. /** 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 */
  18246. Engine.NOTEQUAL = 0x0205;
  18247. // Stencil Actions Constants.
  18248. /** Passed to stencilOperation to specify that stencil value must be kept */
  18249. Engine.KEEP = 0x1E00;
  18250. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18251. Engine.REPLACE = 0x1E01;
  18252. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18253. Engine.INCR = 0x1E02;
  18254. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18255. Engine.DECR = 0x1E03;
  18256. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18257. Engine.INVERT = 0x150A;
  18258. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18259. Engine.INCR_WRAP = 0x8507;
  18260. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18261. Engine.DECR_WRAP = 0x8508;
  18262. /** Texture is not repeating outside of 0..1 UVs */
  18263. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18264. /** Texture is repeating outside of 0..1 UVs */
  18265. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18266. /** Texture is repeating and mirrored */
  18267. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18268. /** ALPHA */
  18269. Engine.TEXTUREFORMAT_ALPHA = 0;
  18270. /** LUMINANCE */
  18271. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18272. /** LUMINANCE_ALPHA */
  18273. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18274. /** RGB */
  18275. Engine.TEXTUREFORMAT_RGB = 4;
  18276. /** RGBA */
  18277. Engine.TEXTUREFORMAT_RGBA = 5;
  18278. /** RED */
  18279. Engine.TEXTUREFORMAT_RED = 6;
  18280. /** RED (2nd reference) */
  18281. Engine.TEXTUREFORMAT_R = 6;
  18282. /** RG */
  18283. Engine.TEXTUREFORMAT_RG = 7;
  18284. /** RED_INTEGER */
  18285. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18286. /** RED_INTEGER (2nd reference) */
  18287. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18288. /** RG_INTEGER */
  18289. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18290. /** RGB_INTEGER */
  18291. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18292. /** RGBA_INTEGER */
  18293. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18294. /** UNSIGNED_BYTE */
  18295. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18296. /** UNSIGNED_BYTE (2nd reference) */
  18297. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18298. /** FLOAT */
  18299. Engine.TEXTURETYPE_FLOAT = 1;
  18300. /** HALF_FLOAT */
  18301. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18302. /** BYTE */
  18303. Engine.TEXTURETYPE_BYTE = 3;
  18304. /** SHORT */
  18305. Engine.TEXTURETYPE_SHORT = 4;
  18306. /** UNSIGNED_SHORT */
  18307. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18308. /** INT */
  18309. Engine.TEXTURETYPE_INT = 6;
  18310. /** UNSIGNED_INT */
  18311. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18312. /** UNSIGNED_SHORT_4_4_4_4 */
  18313. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18314. /** UNSIGNED_SHORT_5_5_5_1 */
  18315. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18316. /** UNSIGNED_SHORT_5_6_5 */
  18317. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18318. /** UNSIGNED_INT_2_10_10_10_REV */
  18319. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18320. /** UNSIGNED_INT_24_8 */
  18321. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18322. /** UNSIGNED_INT_10F_11F_11F_REV */
  18323. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18324. /** UNSIGNED_INT_5_9_9_9_REV */
  18325. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18326. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18327. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18328. /** nearest is mag = nearest and min = nearest and mip = linear */
  18329. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18330. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18331. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18332. /** Trilinear is mag = linear and min = linear and mip = linear */
  18333. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18334. /** nearest is mag = nearest and min = nearest and mip = linear */
  18335. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18336. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18337. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18338. /** Trilinear is mag = linear and min = linear and mip = linear */
  18339. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18340. /** mag = nearest and min = nearest and mip = nearest */
  18341. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18342. /** mag = nearest and min = linear and mip = nearest */
  18343. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18344. /** mag = nearest and min = linear and mip = linear */
  18345. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18346. /** mag = nearest and min = linear and mip = none */
  18347. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18348. /** mag = nearest and min = nearest and mip = none */
  18349. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18350. /** mag = linear and min = nearest and mip = nearest */
  18351. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18352. /** mag = linear and min = nearest and mip = linear */
  18353. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18354. /** mag = linear and min = linear and mip = none */
  18355. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18356. /** mag = linear and min = nearest and mip = none */
  18357. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18358. /** Explicit coordinates mode */
  18359. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18360. /** Spherical coordinates mode */
  18361. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18362. /** Planar coordinates mode */
  18363. Engine.TEXTURE_PLANAR_MODE = 2;
  18364. /** Cubic coordinates mode */
  18365. Engine.TEXTURE_CUBIC_MODE = 3;
  18366. /** Projection coordinates mode */
  18367. Engine.TEXTURE_PROJECTION_MODE = 4;
  18368. /** Skybox coordinates mode */
  18369. Engine.TEXTURE_SKYBOX_MODE = 5;
  18370. /** Inverse Cubic coordinates mode */
  18371. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18372. /** Equirectangular coordinates mode */
  18373. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18374. /** Equirectangular Fixed coordinates mode */
  18375. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18376. /** Equirectangular Fixed Mirrored coordinates mode */
  18377. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18378. // Texture rescaling mode
  18379. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18380. Engine.SCALEMODE_FLOOR = 1;
  18381. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18382. Engine.SCALEMODE_NEAREST = 2;
  18383. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18384. Engine.SCALEMODE_CEILING = 3;
  18385. // Updatable statics so stick with vars here
  18386. /**
  18387. * Gets or sets the epsilon value used by collision engine
  18388. */
  18389. Engine.CollisionsEpsilon = 0.001;
  18390. /**
  18391. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18392. */
  18393. Engine.CodeRepository = "src/";
  18394. /**
  18395. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18396. */
  18397. Engine.ShadersRepository = "src/Shaders/";
  18398. return Engine;
  18399. }());
  18400. BABYLON.Engine = Engine;
  18401. })(BABYLON || (BABYLON = {}));
  18402. //# sourceMappingURL=babylon.engine.js.map
  18403. var BABYLON;
  18404. (function (BABYLON) {
  18405. /**
  18406. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18407. */
  18408. var Node = /** @class */ (function () {
  18409. /**
  18410. * Creates a new Node
  18411. * @param name the name and id to be given to this node
  18412. * @param scene the scene this node will be added to
  18413. */
  18414. function Node(name, scene) {
  18415. if (scene === void 0) { scene = null; }
  18416. /**
  18417. * Gets or sets a string used to store user defined state for the node
  18418. */
  18419. this.state = "";
  18420. /**
  18421. * Gets or sets an object used to store user defined information for the node
  18422. */
  18423. this.metadata = null;
  18424. /**
  18425. * Gets or sets a boolean used to define if the node must be serialized
  18426. */
  18427. this.doNotSerialize = false;
  18428. /** @hidden */
  18429. this._isDisposed = false;
  18430. /**
  18431. * Gets a list of Animations associated with the node
  18432. */
  18433. this.animations = new Array();
  18434. this._ranges = {};
  18435. this._isEnabled = true;
  18436. this._isParentEnabled = true;
  18437. this._isReady = true;
  18438. /** @hidden */
  18439. this._currentRenderId = -1;
  18440. this._parentRenderId = -1;
  18441. this._childRenderId = -1;
  18442. /** @hidden */
  18443. this._worldMatrix = BABYLON.Matrix.Identity();
  18444. /** @hidden */
  18445. this._worldMatrixDeterminant = 0;
  18446. /** @hidden */
  18447. this._sceneRootNodesIndex = -1;
  18448. this._animationPropertiesOverride = null;
  18449. /**
  18450. * An event triggered when the mesh is disposed
  18451. */
  18452. this.onDisposeObservable = new BABYLON.Observable();
  18453. // Behaviors
  18454. this._behaviors = new Array();
  18455. this.name = name;
  18456. this.id = name;
  18457. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18458. this.uniqueId = this._scene.getUniqueId();
  18459. this._initCache();
  18460. this.addToSceneRootNodes();
  18461. }
  18462. /**
  18463. * Add a new node constructor
  18464. * @param type defines the type name of the node to construct
  18465. * @param constructorFunc defines the constructor function
  18466. */
  18467. Node.AddNodeConstructor = function (type, constructorFunc) {
  18468. this._NodeConstructors[type] = constructorFunc;
  18469. };
  18470. /**
  18471. * Returns a node constructor based on type name
  18472. * @param type defines the type name
  18473. * @param name defines the new node name
  18474. * @param scene defines the hosting scene
  18475. * @param options defines optional options to transmit to constructors
  18476. * @returns the new constructor or null
  18477. */
  18478. Node.Construct = function (type, name, scene, options) {
  18479. var constructorFunc = this._NodeConstructors[type];
  18480. if (!constructorFunc) {
  18481. return null;
  18482. }
  18483. return constructorFunc(name, scene, options);
  18484. };
  18485. /**
  18486. * Gets a boolean indicating if the node has been disposed
  18487. * @returns true if the node was disposed
  18488. */
  18489. Node.prototype.isDisposed = function () {
  18490. return this._isDisposed;
  18491. };
  18492. Object.defineProperty(Node.prototype, "parent", {
  18493. get: function () {
  18494. return this._parentNode;
  18495. },
  18496. /**
  18497. * Gets or sets the parent of the node
  18498. */
  18499. set: function (parent) {
  18500. if (this._parentNode === parent) {
  18501. return;
  18502. }
  18503. var previousParentNode = this._parentNode;
  18504. // Remove self from list of children of parent
  18505. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18506. var index = this._parentNode._children.indexOf(this);
  18507. if (index !== -1) {
  18508. this._parentNode._children.splice(index, 1);
  18509. }
  18510. if (!parent) {
  18511. this.addToSceneRootNodes();
  18512. }
  18513. }
  18514. // Store new parent
  18515. this._parentNode = parent;
  18516. // Add as child to new parent
  18517. if (this._parentNode) {
  18518. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18519. this._parentNode._children = new Array();
  18520. }
  18521. this._parentNode._children.push(this);
  18522. if (!previousParentNode) {
  18523. this.removeFromSceneRootNodes();
  18524. }
  18525. }
  18526. // Enabled state
  18527. this._syncParentEnabledState();
  18528. },
  18529. enumerable: true,
  18530. configurable: true
  18531. });
  18532. Node.prototype.addToSceneRootNodes = function () {
  18533. if (this._sceneRootNodesIndex === -1) {
  18534. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18535. this._scene.rootNodes.push(this);
  18536. }
  18537. };
  18538. Node.prototype.removeFromSceneRootNodes = function () {
  18539. if (this._sceneRootNodesIndex !== -1) {
  18540. var rootNodes = this._scene.rootNodes;
  18541. var lastIdx = rootNodes.length - 1;
  18542. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18543. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18544. this._scene.rootNodes.pop();
  18545. this._sceneRootNodesIndex = -1;
  18546. }
  18547. };
  18548. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18549. /**
  18550. * Gets or sets the animation properties override
  18551. */
  18552. get: function () {
  18553. if (!this._animationPropertiesOverride) {
  18554. return this._scene.animationPropertiesOverride;
  18555. }
  18556. return this._animationPropertiesOverride;
  18557. },
  18558. set: function (value) {
  18559. this._animationPropertiesOverride = value;
  18560. },
  18561. enumerable: true,
  18562. configurable: true
  18563. });
  18564. /**
  18565. * Gets a string idenfifying the name of the class
  18566. * @returns "Node" string
  18567. */
  18568. Node.prototype.getClassName = function () {
  18569. return "Node";
  18570. };
  18571. Object.defineProperty(Node.prototype, "onDispose", {
  18572. /**
  18573. * Sets a callback that will be raised when the node will be disposed
  18574. */
  18575. set: function (callback) {
  18576. if (this._onDisposeObserver) {
  18577. this.onDisposeObservable.remove(this._onDisposeObserver);
  18578. }
  18579. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18580. },
  18581. enumerable: true,
  18582. configurable: true
  18583. });
  18584. /**
  18585. * Gets the scene of the node
  18586. * @returns a scene
  18587. */
  18588. Node.prototype.getScene = function () {
  18589. return this._scene;
  18590. };
  18591. /**
  18592. * Gets the engine of the node
  18593. * @returns a Engine
  18594. */
  18595. Node.prototype.getEngine = function () {
  18596. return this._scene.getEngine();
  18597. };
  18598. /**
  18599. * Attach a behavior to the node
  18600. * @see http://doc.babylonjs.com/features/behaviour
  18601. * @param behavior defines the behavior to attach
  18602. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18603. * @returns the current Node
  18604. */
  18605. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18606. var _this = this;
  18607. if (attachImmediately === void 0) { attachImmediately = false; }
  18608. var index = this._behaviors.indexOf(behavior);
  18609. if (index !== -1) {
  18610. return this;
  18611. }
  18612. behavior.init();
  18613. if (this._scene.isLoading && !attachImmediately) {
  18614. // We defer the attach when the scene will be loaded
  18615. this._scene.onDataLoadedObservable.addOnce(function () {
  18616. behavior.attach(_this);
  18617. });
  18618. }
  18619. else {
  18620. behavior.attach(this);
  18621. }
  18622. this._behaviors.push(behavior);
  18623. return this;
  18624. };
  18625. /**
  18626. * Remove an attached behavior
  18627. * @see http://doc.babylonjs.com/features/behaviour
  18628. * @param behavior defines the behavior to attach
  18629. * @returns the current Node
  18630. */
  18631. Node.prototype.removeBehavior = function (behavior) {
  18632. var index = this._behaviors.indexOf(behavior);
  18633. if (index === -1) {
  18634. return this;
  18635. }
  18636. this._behaviors[index].detach();
  18637. this._behaviors.splice(index, 1);
  18638. return this;
  18639. };
  18640. Object.defineProperty(Node.prototype, "behaviors", {
  18641. /**
  18642. * Gets the list of attached behaviors
  18643. * @see http://doc.babylonjs.com/features/behaviour
  18644. */
  18645. get: function () {
  18646. return this._behaviors;
  18647. },
  18648. enumerable: true,
  18649. configurable: true
  18650. });
  18651. /**
  18652. * Gets an attached behavior by name
  18653. * @param name defines the name of the behavior to look for
  18654. * @see http://doc.babylonjs.com/features/behaviour
  18655. * @returns null if behavior was not found else the requested behavior
  18656. */
  18657. Node.prototype.getBehaviorByName = function (name) {
  18658. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18659. var behavior = _a[_i];
  18660. if (behavior.name === name) {
  18661. return behavior;
  18662. }
  18663. }
  18664. return null;
  18665. };
  18666. /**
  18667. * Returns the latest update of the World matrix
  18668. * @returns a Matrix
  18669. */
  18670. Node.prototype.getWorldMatrix = function () {
  18671. if (this._currentRenderId !== this._scene.getRenderId()) {
  18672. this.computeWorldMatrix();
  18673. }
  18674. return this._worldMatrix;
  18675. };
  18676. /** @hidden */
  18677. Node.prototype._getWorldMatrixDeterminant = function () {
  18678. return this._worldMatrixDeterminant;
  18679. };
  18680. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18681. /**
  18682. * Returns directly the latest state of the mesh World matrix.
  18683. * A Matrix is returned.
  18684. */
  18685. get: function () {
  18686. return this._worldMatrix;
  18687. },
  18688. enumerable: true,
  18689. configurable: true
  18690. });
  18691. // override it in derived class if you add new variables to the cache
  18692. // and call the parent class method
  18693. /** @hidden */
  18694. Node.prototype._initCache = function () {
  18695. this._cache = {};
  18696. this._cache.parent = undefined;
  18697. };
  18698. /** @hidden */
  18699. Node.prototype.updateCache = function (force) {
  18700. if (!force && this.isSynchronized()) {
  18701. return;
  18702. }
  18703. this._cache.parent = this.parent;
  18704. this._updateCache();
  18705. };
  18706. // override it in derived class if you add new variables to the cache
  18707. // and call the parent class method if !ignoreParentClass
  18708. /** @hidden */
  18709. Node.prototype._updateCache = function (ignoreParentClass) {
  18710. };
  18711. // override it in derived class if you add new variables to the cache
  18712. /** @hidden */
  18713. Node.prototype._isSynchronized = function () {
  18714. return true;
  18715. };
  18716. /** @hidden */
  18717. Node.prototype._markSyncedWithParent = function () {
  18718. if (this._parentNode) {
  18719. this._parentRenderId = this._parentNode._childRenderId;
  18720. }
  18721. };
  18722. /** @hidden */
  18723. Node.prototype.isSynchronizedWithParent = function () {
  18724. if (!this._parentNode) {
  18725. return true;
  18726. }
  18727. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18728. return false;
  18729. }
  18730. return this._parentNode.isSynchronized();
  18731. };
  18732. /** @hidden */
  18733. Node.prototype.isSynchronized = function () {
  18734. if (this._cache.parent != this._parentNode) {
  18735. this._cache.parent = this._parentNode;
  18736. return false;
  18737. }
  18738. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18739. return false;
  18740. }
  18741. return this._isSynchronized();
  18742. };
  18743. /**
  18744. * Is this node ready to be used/rendered
  18745. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18746. * @return true if the node is ready
  18747. */
  18748. Node.prototype.isReady = function (completeCheck) {
  18749. if (completeCheck === void 0) { completeCheck = false; }
  18750. return this._isReady;
  18751. };
  18752. /**
  18753. * Is this node enabled?
  18754. * 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
  18755. * @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
  18756. * @return whether this node (and its parent) is enabled
  18757. */
  18758. Node.prototype.isEnabled = function (checkAncestors) {
  18759. if (checkAncestors === void 0) { checkAncestors = true; }
  18760. if (checkAncestors === false) {
  18761. return this._isEnabled;
  18762. }
  18763. if (!this._isEnabled) {
  18764. return false;
  18765. }
  18766. return this._isParentEnabled;
  18767. };
  18768. /** @hidden */
  18769. Node.prototype._syncParentEnabledState = function () {
  18770. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18771. if (this._children) {
  18772. this._children.forEach(function (c) {
  18773. c._syncParentEnabledState(); // Force children to update accordingly
  18774. });
  18775. }
  18776. };
  18777. /**
  18778. * Set the enabled state of this node
  18779. * @param value defines the new enabled state
  18780. */
  18781. Node.prototype.setEnabled = function (value) {
  18782. this._isEnabled = value;
  18783. this._syncParentEnabledState();
  18784. };
  18785. /**
  18786. * Is this node a descendant of the given node?
  18787. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18788. * @param ancestor defines the parent node to inspect
  18789. * @returns a boolean indicating if this node is a descendant of the given node
  18790. */
  18791. Node.prototype.isDescendantOf = function (ancestor) {
  18792. if (this.parent) {
  18793. if (this.parent === ancestor) {
  18794. return true;
  18795. }
  18796. return this.parent.isDescendantOf(ancestor);
  18797. }
  18798. return false;
  18799. };
  18800. /** @hidden */
  18801. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18802. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18803. if (!this._children) {
  18804. return;
  18805. }
  18806. for (var index = 0; index < this._children.length; index++) {
  18807. var item = this._children[index];
  18808. if (!predicate || predicate(item)) {
  18809. results.push(item);
  18810. }
  18811. if (!directDescendantsOnly) {
  18812. item._getDescendants(results, false, predicate);
  18813. }
  18814. }
  18815. };
  18816. /**
  18817. * Will return all nodes that have this node as ascendant
  18818. * @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
  18819. * @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
  18820. * @return all children nodes of all types
  18821. */
  18822. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18823. var results = new Array();
  18824. this._getDescendants(results, directDescendantsOnly, predicate);
  18825. return results;
  18826. };
  18827. /**
  18828. * Get all child-meshes of this node
  18829. * @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
  18830. * @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
  18831. * @returns an array of AbstractMesh
  18832. */
  18833. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18834. var results = [];
  18835. this._getDescendants(results, directDescendantsOnly, function (node) {
  18836. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18837. });
  18838. return results;
  18839. };
  18840. /**
  18841. * Get all child-transformNodes of this node
  18842. * @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
  18843. * @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
  18844. * @returns an array of TransformNode
  18845. */
  18846. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18847. var results = [];
  18848. this._getDescendants(results, directDescendantsOnly, function (node) {
  18849. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18850. });
  18851. return results;
  18852. };
  18853. /**
  18854. * Get all direct children of this node
  18855. * @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
  18856. * @returns an array of Node
  18857. */
  18858. Node.prototype.getChildren = function (predicate) {
  18859. return this.getDescendants(true, predicate);
  18860. };
  18861. /** @hidden */
  18862. Node.prototype._setReady = function (state) {
  18863. if (state === this._isReady) {
  18864. return;
  18865. }
  18866. if (!state) {
  18867. this._isReady = false;
  18868. return;
  18869. }
  18870. if (this.onReady) {
  18871. this.onReady(this);
  18872. }
  18873. this._isReady = true;
  18874. };
  18875. /**
  18876. * Get an animation by name
  18877. * @param name defines the name of the animation to look for
  18878. * @returns null if not found else the requested animation
  18879. */
  18880. Node.prototype.getAnimationByName = function (name) {
  18881. for (var i = 0; i < this.animations.length; i++) {
  18882. var animation = this.animations[i];
  18883. if (animation.name === name) {
  18884. return animation;
  18885. }
  18886. }
  18887. return null;
  18888. };
  18889. /**
  18890. * Creates an animation range for this node
  18891. * @param name defines the name of the range
  18892. * @param from defines the starting key
  18893. * @param to defines the end key
  18894. */
  18895. Node.prototype.createAnimationRange = function (name, from, to) {
  18896. // check name not already in use
  18897. if (!this._ranges[name]) {
  18898. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18899. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18900. if (this.animations[i]) {
  18901. this.animations[i].createRange(name, from, to);
  18902. }
  18903. }
  18904. }
  18905. };
  18906. /**
  18907. * Delete a specific animation range
  18908. * @param name defines the name of the range to delete
  18909. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18910. */
  18911. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18912. if (deleteFrames === void 0) { deleteFrames = true; }
  18913. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18914. if (this.animations[i]) {
  18915. this.animations[i].deleteRange(name, deleteFrames);
  18916. }
  18917. }
  18918. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18919. };
  18920. /**
  18921. * Get an animation range by name
  18922. * @param name defines the name of the animation range to look for
  18923. * @returns null if not found else the requested animation range
  18924. */
  18925. Node.prototype.getAnimationRange = function (name) {
  18926. return this._ranges[name];
  18927. };
  18928. /**
  18929. * Will start the animation sequence
  18930. * @param name defines the range frames for animation sequence
  18931. * @param loop defines if the animation should loop (false by default)
  18932. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18933. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18934. * @returns the object created for this animation. If range does not exist, it will return null
  18935. */
  18936. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18937. var range = this.getAnimationRange(name);
  18938. if (!range) {
  18939. return null;
  18940. }
  18941. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18942. };
  18943. /**
  18944. * Serialize animation ranges into a JSON compatible object
  18945. * @returns serialization object
  18946. */
  18947. Node.prototype.serializeAnimationRanges = function () {
  18948. var serializationRanges = [];
  18949. for (var name in this._ranges) {
  18950. var localRange = this._ranges[name];
  18951. if (!localRange) {
  18952. continue;
  18953. }
  18954. var range = {};
  18955. range.name = name;
  18956. range.from = localRange.from;
  18957. range.to = localRange.to;
  18958. serializationRanges.push(range);
  18959. }
  18960. return serializationRanges;
  18961. };
  18962. /**
  18963. * Computes the world matrix of the node
  18964. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18965. * @returns the world matrix
  18966. */
  18967. Node.prototype.computeWorldMatrix = function (force) {
  18968. if (!this._worldMatrix) {
  18969. this._worldMatrix = BABYLON.Matrix.Identity();
  18970. }
  18971. return this._worldMatrix;
  18972. };
  18973. /**
  18974. * Releases resources associated with this node.
  18975. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18976. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18977. */
  18978. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18979. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18980. if (!doNotRecurse) {
  18981. var nodes = this.getDescendants(true);
  18982. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18983. var node = nodes_1[_i];
  18984. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18985. }
  18986. }
  18987. else {
  18988. var transformNodes = this.getChildTransformNodes(true);
  18989. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18990. var transformNode = transformNodes_1[_a];
  18991. transformNode.parent = null;
  18992. transformNode.computeWorldMatrix(true);
  18993. }
  18994. }
  18995. if (!this.parent) {
  18996. this.removeFromSceneRootNodes();
  18997. }
  18998. else {
  18999. this.parent = null;
  19000. }
  19001. // Callback
  19002. this.onDisposeObservable.notifyObservers(this);
  19003. this.onDisposeObservable.clear();
  19004. // Behaviors
  19005. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19006. var behavior = _c[_b];
  19007. behavior.detach();
  19008. }
  19009. this._behaviors = [];
  19010. this._isDisposed = true;
  19011. };
  19012. /**
  19013. * Parse animation range data from a serialization object and store them into a given node
  19014. * @param node defines where to store the animation ranges
  19015. * @param parsedNode defines the serialization object to read data from
  19016. * @param scene defines the hosting scene
  19017. */
  19018. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19019. if (parsedNode.ranges) {
  19020. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19021. var data = parsedNode.ranges[index];
  19022. node.createAnimationRange(data.name, data.from, data.to);
  19023. }
  19024. }
  19025. };
  19026. Node._NodeConstructors = {};
  19027. __decorate([
  19028. BABYLON.serialize()
  19029. ], Node.prototype, "name", void 0);
  19030. __decorate([
  19031. BABYLON.serialize()
  19032. ], Node.prototype, "id", void 0);
  19033. __decorate([
  19034. BABYLON.serialize()
  19035. ], Node.prototype, "uniqueId", void 0);
  19036. __decorate([
  19037. BABYLON.serialize()
  19038. ], Node.prototype, "state", void 0);
  19039. __decorate([
  19040. BABYLON.serialize()
  19041. ], Node.prototype, "metadata", void 0);
  19042. return Node;
  19043. }());
  19044. BABYLON.Node = Node;
  19045. })(BABYLON || (BABYLON = {}));
  19046. //# sourceMappingURL=babylon.node.js.map
  19047. var BABYLON;
  19048. (function (BABYLON) {
  19049. // This matrix is used as a value to reset the bounding box.
  19050. var _identityMatrix = BABYLON.Matrix.Identity();
  19051. /**
  19052. * Class used to store bounding sphere information
  19053. */
  19054. var BoundingSphere = /** @class */ (function () {
  19055. /**
  19056. * Creates a new bounding sphere
  19057. * @param min defines the minimum vector (in local space)
  19058. * @param max defines the maximum vector (in local space)
  19059. */
  19060. function BoundingSphere(min, max) {
  19061. /**
  19062. * Gets the center of the bounding sphere in local space
  19063. */
  19064. this.center = BABYLON.Vector3.Zero();
  19065. /**
  19066. * Gets the center of the bounding sphere in world space
  19067. */
  19068. this.centerWorld = BABYLON.Vector3.Zero();
  19069. /**
  19070. * Gets the minimum vector in local space
  19071. */
  19072. this.minimum = BABYLON.Vector3.Zero();
  19073. /**
  19074. * Gets the maximum vector in local space
  19075. */
  19076. this.maximum = BABYLON.Vector3.Zero();
  19077. this.reConstruct(min, max);
  19078. }
  19079. /**
  19080. * Recreates the entire bounding sphere from scratch
  19081. * @param min defines the new minimum vector (in local space)
  19082. * @param max defines the new maximum vector (in local space)
  19083. */
  19084. BoundingSphere.prototype.reConstruct = function (min, max) {
  19085. this.minimum.copyFrom(min);
  19086. this.maximum.copyFrom(max);
  19087. var distance = BABYLON.Vector3.Distance(min, max);
  19088. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  19089. this.radius = distance * 0.5;
  19090. this.centerWorld.set(0, 0, 0);
  19091. this._update(_identityMatrix);
  19092. };
  19093. /**
  19094. * Scale the current bounding sphere by applying a scale factor
  19095. * @param factor defines the scale factor to apply
  19096. * @returns the current bounding box
  19097. */
  19098. BoundingSphere.prototype.scale = function (factor) {
  19099. var newRadius = this.radius * factor;
  19100. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  19101. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  19102. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  19103. this.reConstruct(min, max);
  19104. return this;
  19105. };
  19106. // Methods
  19107. /** @hidden */
  19108. BoundingSphere.prototype._update = function (world) {
  19109. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19110. var tempVector = BABYLON.Tmp.Vector3[0];
  19111. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19112. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19113. };
  19114. /**
  19115. * Tests if the bounding sphere is intersecting the frustum planes
  19116. * @param frustumPlanes defines the frustum planes to test
  19117. * @returns true if there is an intersection
  19118. */
  19119. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19120. for (var i = 0; i < 6; i++) {
  19121. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19122. return false;
  19123. }
  19124. }
  19125. return true;
  19126. };
  19127. /**
  19128. * Tests if a point is inside the bounding sphere
  19129. * @param point defines the point to test
  19130. * @returns true if the point is inside the bounding sphere
  19131. */
  19132. BoundingSphere.prototype.intersectsPoint = function (point) {
  19133. var x = this.centerWorld.x - point.x;
  19134. var y = this.centerWorld.y - point.y;
  19135. var z = this.centerWorld.z - point.z;
  19136. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19137. if (this.radiusWorld < distance) {
  19138. return false;
  19139. }
  19140. return true;
  19141. };
  19142. // Statics
  19143. /**
  19144. * Checks if two sphere intersct
  19145. * @param sphere0 sphere 0
  19146. * @param sphere1 sphere 1
  19147. * @returns true if the speres intersect
  19148. */
  19149. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19150. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  19151. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  19152. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  19153. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19154. if (sphere0.radiusWorld + sphere1.radiusWorld < distance) {
  19155. return false;
  19156. }
  19157. return true;
  19158. };
  19159. return BoundingSphere;
  19160. }());
  19161. BABYLON.BoundingSphere = BoundingSphere;
  19162. })(BABYLON || (BABYLON = {}));
  19163. //# sourceMappingURL=babylon.boundingSphere.js.map
  19164. var BABYLON;
  19165. (function (BABYLON) {
  19166. /**
  19167. * Class used to store bounding box information
  19168. */
  19169. var BoundingBox = /** @class */ (function () {
  19170. /**
  19171. * Creates a new bounding box
  19172. * @param min defines the minimum vector (in local space)
  19173. * @param max defines the maximum vector (in local space)
  19174. */
  19175. function BoundingBox(min, max) {
  19176. /**
  19177. * Gets the 8 vectors representing the bounding box in local space
  19178. */
  19179. this.vectors = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19180. /**
  19181. * Gets the center of the bounding box in local space
  19182. */
  19183. this.center = BABYLON.Vector3.Zero();
  19184. /**
  19185. * Gets the center of the bounding box in world space
  19186. */
  19187. this.centerWorld = BABYLON.Vector3.Zero();
  19188. /**
  19189. * Gets the extend size in local space
  19190. */
  19191. this.extendSize = BABYLON.Vector3.Zero();
  19192. /**
  19193. * Gets the extend size in world space
  19194. */
  19195. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19196. /**
  19197. * Gets the OBB (object bounding box) directions
  19198. */
  19199. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19200. /**
  19201. * Gets the 8 vectors representing the bounding box in world space
  19202. */
  19203. this.vectorsWorld = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19204. /**
  19205. * Gets the minimum vector in world space
  19206. */
  19207. this.minimumWorld = BABYLON.Vector3.Zero();
  19208. /**
  19209. * Gets the maximum vector in world space
  19210. */
  19211. this.maximumWorld = BABYLON.Vector3.Zero();
  19212. /**
  19213. * Gets the minimum vector in local space
  19214. */
  19215. this.minimum = BABYLON.Vector3.Zero();
  19216. /**
  19217. * Gets the maximum vector in local space
  19218. */
  19219. this.maximum = BABYLON.Vector3.Zero();
  19220. this.reConstruct(min, max);
  19221. }
  19222. // Methods
  19223. /**
  19224. * Recreates the entire bounding box from scratch
  19225. * @param min defines the new minimum vector (in local space)
  19226. * @param max defines the new maximum vector (in local space)
  19227. */
  19228. BoundingBox.prototype.reConstruct = function (min, max) {
  19229. this.minimum.copyFrom(min);
  19230. this.maximum.copyFrom(max);
  19231. // Bounding vectors
  19232. this.vectors[0].copyFrom(this.minimum);
  19233. this.vectors[1].copyFrom(this.maximum);
  19234. this.vectors[2].copyFrom(this.minimum);
  19235. this.vectors[3].copyFrom(this.minimum);
  19236. this.vectors[4].copyFrom(this.minimum);
  19237. this.vectors[5].copyFrom(this.maximum);
  19238. this.vectors[6].copyFrom(this.maximum);
  19239. this.vectors[7].copyFrom(this.maximum);
  19240. this.vectors[2].x = this.maximum.x;
  19241. this.vectors[3].y = this.maximum.y;
  19242. this.vectors[4].z = this.maximum.z;
  19243. this.vectors[5].z = this.minimum.z;
  19244. this.vectors[6].x = this.minimum.x;
  19245. this.vectors[7].y = this.minimum.y;
  19246. // OBB
  19247. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19248. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19249. for (var index = 0; index < 3; index++) {
  19250. this.directions[index].copyFromFloats(0, 0, 0);
  19251. }
  19252. // World
  19253. for (var index = 0; index < 8; index++) {
  19254. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19255. }
  19256. this.minimumWorld.copyFromFloats(0, 0, 0);
  19257. this.maximumWorld.copyFromFloats(0, 0, 0);
  19258. this.centerWorld.copyFromFloats(0, 0, 0);
  19259. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19260. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19261. };
  19262. /**
  19263. * Scale the current bounding box by applying a scale factor
  19264. * @param factor defines the scale factor to apply
  19265. * @returns the current bounding box
  19266. */
  19267. BoundingBox.prototype.scale = function (factor) {
  19268. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19269. var distance = diff.length() * factor;
  19270. diff.normalize();
  19271. var newRadius = diff.scaleInPlace(distance * 0.5);
  19272. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19273. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19274. this.reConstruct(min, max);
  19275. return this;
  19276. };
  19277. /**
  19278. * Gets the world matrix of the bounding box
  19279. * @returns a matrix
  19280. */
  19281. BoundingBox.prototype.getWorldMatrix = function () {
  19282. return this._worldMatrix;
  19283. };
  19284. /**
  19285. * Sets the world matrix stored in the bounding box
  19286. * @param matrix defines the matrix to store
  19287. * @returns current bounding box
  19288. */
  19289. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19290. this._worldMatrix.copyFrom(matrix);
  19291. return this;
  19292. };
  19293. /** @hidden */
  19294. BoundingBox.prototype._update = function (world) {
  19295. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19296. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19297. for (var index = 0; index < 8; index++) {
  19298. var v = this.vectorsWorld[index];
  19299. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19300. this.minimumWorld.minimizeInPlace(v);
  19301. this.maximumWorld.maximizeInPlace(v);
  19302. }
  19303. // Extend
  19304. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19305. this.extendSizeWorld.scaleInPlace(0.5);
  19306. // OBB
  19307. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19308. this.centerWorld.scaleInPlace(0.5);
  19309. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19310. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19311. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19312. this._worldMatrix = world;
  19313. };
  19314. /**
  19315. * Tests if the bounding box is intersecting the frustum planes
  19316. * @param frustumPlanes defines the frustum planes to test
  19317. * @returns true if there is an intersection
  19318. */
  19319. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19320. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19321. };
  19322. /**
  19323. * Tests if the bounding box is entirely inside the frustum planes
  19324. * @param frustumPlanes defines the frustum planes to test
  19325. * @returns true if there is an inclusion
  19326. */
  19327. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19328. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19329. };
  19330. /**
  19331. * Tests if a point is inside the bounding box
  19332. * @param point defines the point to test
  19333. * @returns true if the point is inside the bounding box
  19334. */
  19335. BoundingBox.prototype.intersectsPoint = function (point) {
  19336. var delta = -BABYLON.Epsilon;
  19337. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x) {
  19338. return false;
  19339. }
  19340. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y) {
  19341. return false;
  19342. }
  19343. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z) {
  19344. return false;
  19345. }
  19346. return true;
  19347. };
  19348. /**
  19349. * Tests if the bounding box intersects with a bounding sphere
  19350. * @param sphere defines the sphere to test
  19351. * @returns true if there is an intersection
  19352. */
  19353. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19354. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19355. };
  19356. /**
  19357. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19358. * @param min defines the min vector to use
  19359. * @param max defines the max vector to use
  19360. * @returns true if there is an intersection
  19361. */
  19362. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19363. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x) {
  19364. return false;
  19365. }
  19366. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y) {
  19367. return false;
  19368. }
  19369. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z) {
  19370. return false;
  19371. }
  19372. return true;
  19373. };
  19374. // Statics
  19375. /**
  19376. * Tests if two bounding boxes are intersections
  19377. * @param box0 defines the first box to test
  19378. * @param box1 defines the second box to test
  19379. * @returns true if there is an intersection
  19380. */
  19381. BoundingBox.Intersects = function (box0, box1) {
  19382. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x) {
  19383. return false;
  19384. }
  19385. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y) {
  19386. return false;
  19387. }
  19388. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z) {
  19389. return false;
  19390. }
  19391. return true;
  19392. };
  19393. /**
  19394. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19395. * @param minPoint defines the minimum vector of the bounding box
  19396. * @param maxPoint defines the maximum vector of the bounding box
  19397. * @param sphereCenter defines the sphere center
  19398. * @param sphereRadius defines the sphere radius
  19399. * @returns true if there is an intersection
  19400. */
  19401. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19402. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19403. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19404. return (num <= (sphereRadius * sphereRadius));
  19405. };
  19406. /**
  19407. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19408. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19409. * @param frustumPlanes defines the frustum planes to test
  19410. * @return true if there is an inclusion
  19411. */
  19412. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19413. for (var p = 0; p < 6; p++) {
  19414. for (var i = 0; i < 8; i++) {
  19415. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19416. return false;
  19417. }
  19418. }
  19419. }
  19420. return true;
  19421. };
  19422. /**
  19423. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19424. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19425. * @param frustumPlanes defines the frustum planes to test
  19426. * @return true if there is an intersection
  19427. */
  19428. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19429. for (var p = 0; p < 6; p++) {
  19430. var inCount = 8;
  19431. for (var i = 0; i < 8; i++) {
  19432. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19433. --inCount;
  19434. }
  19435. else {
  19436. break;
  19437. }
  19438. }
  19439. if (inCount === 0) {
  19440. return false;
  19441. }
  19442. }
  19443. return true;
  19444. };
  19445. return BoundingBox;
  19446. }());
  19447. BABYLON.BoundingBox = BoundingBox;
  19448. })(BABYLON || (BABYLON = {}));
  19449. //# sourceMappingURL=babylon.boundingBox.js.map
  19450. var BABYLON;
  19451. (function (BABYLON) {
  19452. var computeBoxExtents = function (axis, box) {
  19453. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19454. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19455. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19456. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19457. var r = r0 + r1 + r2;
  19458. return {
  19459. min: p - r,
  19460. max: p + r
  19461. };
  19462. };
  19463. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19464. var axisOverlap = function (axis, box0, box1) {
  19465. var result0 = computeBoxExtents(axis, box0);
  19466. var result1 = computeBoxExtents(axis, box1);
  19467. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19468. };
  19469. /**
  19470. * Info for a bounding data of a mesh
  19471. */
  19472. var BoundingInfo = /** @class */ (function () {
  19473. /**
  19474. * Constructs bounding info
  19475. * @param minimum min vector of the bounding box/sphere
  19476. * @param maximum max vector of the bounding box/sphere
  19477. */
  19478. function BoundingInfo(minimum, maximum) {
  19479. this._isLocked = false;
  19480. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19481. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19482. }
  19483. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19484. /**
  19485. * min vector of the bounding box/sphere
  19486. */
  19487. get: function () {
  19488. return this.boundingBox.minimum;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19494. /**
  19495. * max vector of the bounding box/sphere
  19496. */
  19497. get: function () {
  19498. return this.boundingBox.maximum;
  19499. },
  19500. enumerable: true,
  19501. configurable: true
  19502. });
  19503. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19504. /**
  19505. * If the info is locked and won't be updated to avoid perf overhead
  19506. */
  19507. get: function () {
  19508. return this._isLocked;
  19509. },
  19510. set: function (value) {
  19511. this._isLocked = value;
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. // Methods
  19517. /**
  19518. * Updates the boudning sphere and box
  19519. * @param world world matrix to be used to update
  19520. */
  19521. BoundingInfo.prototype.update = function (world) {
  19522. if (this._isLocked) {
  19523. return;
  19524. }
  19525. this.boundingBox._update(world);
  19526. this.boundingSphere._update(world);
  19527. };
  19528. /**
  19529. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19530. * @param center New center of the bounding info
  19531. * @param extend New extend of the bounding info
  19532. * @returns the current bounding info
  19533. */
  19534. BoundingInfo.prototype.centerOn = function (center, extend) {
  19535. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19536. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19537. this.boundingBox.reConstruct(minimum, maximum);
  19538. this.boundingSphere.reConstruct(minimum, maximum);
  19539. return this;
  19540. };
  19541. /**
  19542. * Scale the current bounding info by applying a scale factor
  19543. * @param factor defines the scale factor to apply
  19544. * @returns the current bounding info
  19545. */
  19546. BoundingInfo.prototype.scale = function (factor) {
  19547. this.boundingBox.scale(factor);
  19548. this.boundingSphere.scale(factor);
  19549. return this;
  19550. };
  19551. /**
  19552. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19553. * @param frustumPlanes defines the frustum to test
  19554. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19555. * @returns true if the bounding info is in the frustum planes
  19556. */
  19557. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19558. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19559. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19560. return false;
  19561. }
  19562. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19563. return true;
  19564. }
  19565. return this.boundingBox.isInFrustum(frustumPlanes);
  19566. };
  19567. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19568. /**
  19569. * Gets the world distance between the min and max points of the bounding box
  19570. */
  19571. get: function () {
  19572. var boundingBox = this.boundingBox;
  19573. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19574. return size.length();
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. /**
  19580. * Checks if a cullable object (mesh...) is in the camera frustum
  19581. * Unlike isInFrustum this cheks the full bounding box
  19582. * @param frustumPlanes Camera near/planes
  19583. * @returns true if the object is in frustum otherwise false
  19584. */
  19585. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19586. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19587. };
  19588. /** @hidden */
  19589. BoundingInfo.prototype._checkCollision = function (collider) {
  19590. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19591. };
  19592. /**
  19593. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19594. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19595. * @param point the point to check intersection with
  19596. * @returns if the point intersects
  19597. */
  19598. BoundingInfo.prototype.intersectsPoint = function (point) {
  19599. if (!this.boundingSphere.centerWorld) {
  19600. return false;
  19601. }
  19602. if (!this.boundingSphere.intersectsPoint(point)) {
  19603. return false;
  19604. }
  19605. if (!this.boundingBox.intersectsPoint(point)) {
  19606. return false;
  19607. }
  19608. return true;
  19609. };
  19610. /**
  19611. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19612. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19613. * @param boundingInfo the bounding info to check intersection with
  19614. * @param precise if the intersection should be done using OBB
  19615. * @returns if the bounding info intersects
  19616. */
  19617. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19618. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19619. return false;
  19620. }
  19621. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19622. return false;
  19623. }
  19624. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19625. return false;
  19626. }
  19627. if (!precise) {
  19628. return true;
  19629. }
  19630. var box0 = this.boundingBox;
  19631. var box1 = boundingInfo.boundingBox;
  19632. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19633. return false;
  19634. }
  19635. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19636. return false;
  19637. }
  19638. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19639. return false;
  19640. }
  19641. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19642. return false;
  19643. }
  19644. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19645. return false;
  19646. }
  19647. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19648. return false;
  19649. }
  19650. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19651. return false;
  19652. }
  19653. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19654. return false;
  19655. }
  19656. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19657. return false;
  19658. }
  19659. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19660. return false;
  19661. }
  19662. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19663. return false;
  19664. }
  19665. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19666. return false;
  19667. }
  19668. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19669. return false;
  19670. }
  19671. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19672. return false;
  19673. }
  19674. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19675. return false;
  19676. }
  19677. return true;
  19678. };
  19679. return BoundingInfo;
  19680. }());
  19681. BABYLON.BoundingInfo = BoundingInfo;
  19682. })(BABYLON || (BABYLON = {}));
  19683. //# sourceMappingURL=babylon.boundingInfo.js.map
  19684. var BABYLON;
  19685. (function (BABYLON) {
  19686. /**
  19687. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  19688. * @see https://doc.babylonjs.com/how_to/transformnode
  19689. */
  19690. var TransformNode = /** @class */ (function (_super) {
  19691. __extends(TransformNode, _super);
  19692. function TransformNode(name, scene, isPure) {
  19693. if (scene === void 0) { scene = null; }
  19694. if (isPure === void 0) { isPure = true; }
  19695. var _this = _super.call(this, name, scene) || this;
  19696. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19697. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19698. _this._up = new BABYLON.Vector3(0, 1, 0);
  19699. _this._right = new BABYLON.Vector3(1, 0, 0);
  19700. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19701. // Properties
  19702. _this._position = BABYLON.Vector3.Zero();
  19703. _this._rotation = BABYLON.Vector3.Zero();
  19704. _this._scaling = BABYLON.Vector3.One();
  19705. _this._isDirty = false;
  19706. /**
  19707. * Set the billboard mode. Default is 0.
  19708. *
  19709. * | Value | Type | Description |
  19710. * | --- | --- | --- |
  19711. * | 0 | BILLBOARDMODE_NONE | |
  19712. * | 1 | BILLBOARDMODE_X | |
  19713. * | 2 | BILLBOARDMODE_Y | |
  19714. * | 4 | BILLBOARDMODE_Z | |
  19715. * | 7 | BILLBOARDMODE_ALL | |
  19716. *
  19717. */
  19718. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19719. /**
  19720. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  19721. */
  19722. _this.scalingDeterminant = 1;
  19723. /**
  19724. * Sets the distance of the object to max, often used by skybox
  19725. */
  19726. _this.infiniteDistance = false;
  19727. /**
  19728. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19729. * By default the system will update normals to compensate
  19730. */
  19731. _this.ignoreNonUniformScaling = false;
  19732. _this._localWorld = BABYLON.Matrix.Zero();
  19733. _this._absolutePosition = BABYLON.Vector3.Zero();
  19734. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19735. _this._postMultiplyPivotMatrix = false;
  19736. _this._isWorldMatrixFrozen = false;
  19737. /**
  19738. * An event triggered after the world matrix is updated
  19739. */
  19740. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19741. _this._nonUniformScaling = false;
  19742. if (isPure) {
  19743. _this.getScene().addTransformNode(_this);
  19744. }
  19745. return _this;
  19746. }
  19747. /**
  19748. * Gets a string identifying the name of the class
  19749. * @returns "TransformNode" string
  19750. */
  19751. TransformNode.prototype.getClassName = function () {
  19752. return "TransformNode";
  19753. };
  19754. Object.defineProperty(TransformNode.prototype, "position", {
  19755. /**
  19756. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19757. */
  19758. get: function () {
  19759. return this._position;
  19760. },
  19761. set: function (newPosition) {
  19762. this._position = newPosition;
  19763. this._isDirty = true;
  19764. },
  19765. enumerable: true,
  19766. configurable: true
  19767. });
  19768. Object.defineProperty(TransformNode.prototype, "rotation", {
  19769. /**
  19770. * 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)).
  19771. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19772. */
  19773. get: function () {
  19774. return this._rotation;
  19775. },
  19776. set: function (newRotation) {
  19777. this._rotation = newRotation;
  19778. this._isDirty = true;
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. Object.defineProperty(TransformNode.prototype, "scaling", {
  19784. /**
  19785. * 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)).
  19786. */
  19787. get: function () {
  19788. return this._scaling;
  19789. },
  19790. set: function (newScaling) {
  19791. this._scaling = newScaling;
  19792. this._isDirty = true;
  19793. },
  19794. enumerable: true,
  19795. configurable: true
  19796. });
  19797. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19798. /**
  19799. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19800. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19801. */
  19802. get: function () {
  19803. return this._rotationQuaternion;
  19804. },
  19805. set: function (quaternion) {
  19806. this._rotationQuaternion = quaternion;
  19807. //reset the rotation vector.
  19808. if (quaternion && this.rotation.length()) {
  19809. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19810. }
  19811. },
  19812. enumerable: true,
  19813. configurable: true
  19814. });
  19815. Object.defineProperty(TransformNode.prototype, "forward", {
  19816. /**
  19817. * The forward direction of that transform in world space.
  19818. */
  19819. get: function () {
  19820. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(TransformNode.prototype, "up", {
  19826. /**
  19827. * The up direction of that transform in world space.
  19828. */
  19829. get: function () {
  19830. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(TransformNode.prototype, "right", {
  19836. /**
  19837. * The right direction of that transform in world space.
  19838. */
  19839. get: function () {
  19840. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19841. },
  19842. enumerable: true,
  19843. configurable: true
  19844. });
  19845. /**
  19846. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19847. * @param matrix the matrix to copy the pose from
  19848. * @returns this TransformNode.
  19849. */
  19850. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19851. this._poseMatrix.copyFrom(matrix);
  19852. return this;
  19853. };
  19854. /**
  19855. * Returns the mesh Pose matrix.
  19856. * @returns the pose matrix
  19857. */
  19858. TransformNode.prototype.getPoseMatrix = function () {
  19859. return this._poseMatrix;
  19860. };
  19861. /** @hidden */
  19862. TransformNode.prototype._isSynchronized = function () {
  19863. if (this._isDirty) {
  19864. return false;
  19865. }
  19866. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19867. return false;
  19868. }
  19869. if (this._cache.pivotMatrixUpdated) {
  19870. return false;
  19871. }
  19872. if (this.infiniteDistance) {
  19873. return false;
  19874. }
  19875. if (!this._cache.position.equals(this._position)) {
  19876. return false;
  19877. }
  19878. if (this._rotationQuaternion) {
  19879. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  19880. return false;
  19881. }
  19882. }
  19883. if (!this._cache.rotation.equals(this._rotation)) {
  19884. return false;
  19885. }
  19886. if (!this._cache.scaling.equals(this._scaling)) {
  19887. return false;
  19888. }
  19889. return true;
  19890. };
  19891. /** @hidden */
  19892. TransformNode.prototype._initCache = function () {
  19893. _super.prototype._initCache.call(this);
  19894. this._cache.localMatrixUpdated = false;
  19895. this._cache.position = BABYLON.Vector3.Zero();
  19896. this._cache.scaling = BABYLON.Vector3.Zero();
  19897. this._cache.rotation = BABYLON.Vector3.Zero();
  19898. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19899. this._cache.billboardMode = -1;
  19900. };
  19901. /**
  19902. * Flag the transform node as dirty (Forcing it to update everything)
  19903. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19904. * @returns this transform node
  19905. */
  19906. TransformNode.prototype.markAsDirty = function (property) {
  19907. if (property === "rotation") {
  19908. this.rotationQuaternion = null;
  19909. }
  19910. this._currentRenderId = Number.MAX_VALUE;
  19911. this._isDirty = true;
  19912. return this;
  19913. };
  19914. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19915. /**
  19916. * Returns the current mesh absolute position.
  19917. * Returns a Vector3.
  19918. */
  19919. get: function () {
  19920. return this._absolutePosition;
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. /**
  19926. * Sets a new matrix to apply before all other transformation
  19927. * @param matrix defines the transform matrix
  19928. * @returns the current TransformNode
  19929. */
  19930. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19931. return this.setPivotMatrix(matrix, false);
  19932. };
  19933. /**
  19934. * Sets a new pivot matrix to the current node
  19935. * @param matrix defines the new pivot matrix to use
  19936. * @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
  19937. * @returns the current TransformNode
  19938. */
  19939. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19940. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19941. this._pivotMatrix = matrix.clone();
  19942. this._cache.pivotMatrixUpdated = true;
  19943. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19944. if (this._postMultiplyPivotMatrix) {
  19945. if (!this._pivotMatrixInverse) {
  19946. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19947. }
  19948. else {
  19949. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19950. }
  19951. }
  19952. return this;
  19953. };
  19954. /**
  19955. * Returns the mesh pivot matrix.
  19956. * Default : Identity.
  19957. * @returns the matrix
  19958. */
  19959. TransformNode.prototype.getPivotMatrix = function () {
  19960. return this._pivotMatrix;
  19961. };
  19962. /**
  19963. * Prevents the World matrix to be computed any longer.
  19964. * @returns the TransformNode.
  19965. */
  19966. TransformNode.prototype.freezeWorldMatrix = function () {
  19967. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19968. this.computeWorldMatrix(true);
  19969. this._isWorldMatrixFrozen = true;
  19970. return this;
  19971. };
  19972. /**
  19973. * Allows back the World matrix computation.
  19974. * @returns the TransformNode.
  19975. */
  19976. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19977. this._isWorldMatrixFrozen = false;
  19978. this.computeWorldMatrix(true);
  19979. return this;
  19980. };
  19981. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19982. /**
  19983. * True if the World matrix has been frozen.
  19984. */
  19985. get: function () {
  19986. return this._isWorldMatrixFrozen;
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. /**
  19992. * Retuns the mesh absolute position in the World.
  19993. * @returns a Vector3.
  19994. */
  19995. TransformNode.prototype.getAbsolutePosition = function () {
  19996. this.computeWorldMatrix();
  19997. return this._absolutePosition;
  19998. };
  19999. /**
  20000. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20001. * @param absolutePosition the absolute position to set
  20002. * @returns the TransformNode.
  20003. */
  20004. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20005. if (!absolutePosition) {
  20006. return this;
  20007. }
  20008. var absolutePositionX;
  20009. var absolutePositionY;
  20010. var absolutePositionZ;
  20011. if (absolutePosition.x === undefined) {
  20012. if (arguments.length < 3) {
  20013. return this;
  20014. }
  20015. absolutePositionX = arguments[0];
  20016. absolutePositionY = arguments[1];
  20017. absolutePositionZ = arguments[2];
  20018. }
  20019. else {
  20020. absolutePositionX = absolutePosition.x;
  20021. absolutePositionY = absolutePosition.y;
  20022. absolutePositionZ = absolutePosition.z;
  20023. }
  20024. if (this.parent) {
  20025. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20026. invertParentWorldMatrix.invert();
  20027. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  20028. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  20029. }
  20030. else {
  20031. this.position.x = absolutePositionX;
  20032. this.position.y = absolutePositionY;
  20033. this.position.z = absolutePositionZ;
  20034. }
  20035. return this;
  20036. };
  20037. /**
  20038. * Sets the mesh position in its local space.
  20039. * @param vector3 the position to set in localspace
  20040. * @returns the TransformNode.
  20041. */
  20042. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20043. this.computeWorldMatrix();
  20044. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20045. return this;
  20046. };
  20047. /**
  20048. * Returns the mesh position in the local space from the current World matrix values.
  20049. * @returns a new Vector3.
  20050. */
  20051. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20052. this.computeWorldMatrix();
  20053. var invLocalWorldMatrix = this._localWorld.clone();
  20054. invLocalWorldMatrix.invert();
  20055. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20056. };
  20057. /**
  20058. * Translates the mesh along the passed Vector3 in its local space.
  20059. * @param vector3 the distance to translate in localspace
  20060. * @returns the TransformNode.
  20061. */
  20062. TransformNode.prototype.locallyTranslate = function (vector3) {
  20063. this.computeWorldMatrix(true);
  20064. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20065. return this;
  20066. };
  20067. /**
  20068. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20069. * @param targetPoint the position (must be in same space as current mesh) to look at
  20070. * @param yawCor optional yaw (y-axis) correction in radians
  20071. * @param pitchCor optional pitch (x-axis) correction in radians
  20072. * @param rollCor optional roll (z-axis) correction in radians
  20073. * @param space the choosen space of the target
  20074. * @returns the TransformNode.
  20075. */
  20076. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20077. if (yawCor === void 0) { yawCor = 0; }
  20078. if (pitchCor === void 0) { pitchCor = 0; }
  20079. if (rollCor === void 0) { rollCor = 0; }
  20080. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20081. var dv = TransformNode._lookAtVectorCache;
  20082. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20083. targetPoint.subtractToRef(pos, dv);
  20084. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20085. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20086. var pitch = Math.atan2(dv.y, len);
  20087. if (this.rotationQuaternion) {
  20088. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20089. }
  20090. else {
  20091. this.rotation.x = pitch + pitchCor;
  20092. this.rotation.y = yaw + yawCor;
  20093. this.rotation.z = rollCor;
  20094. }
  20095. return this;
  20096. };
  20097. /**
  20098. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20099. * This Vector3 is expressed in the World space.
  20100. * @param localAxis axis to rotate
  20101. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20102. */
  20103. TransformNode.prototype.getDirection = function (localAxis) {
  20104. var result = BABYLON.Vector3.Zero();
  20105. this.getDirectionToRef(localAxis, result);
  20106. return result;
  20107. };
  20108. /**
  20109. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20110. * localAxis is expressed in the mesh local space.
  20111. * result is computed in the Wordl space from the mesh World matrix.
  20112. * @param localAxis axis to rotate
  20113. * @param result the resulting transformnode
  20114. * @returns this TransformNode.
  20115. */
  20116. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20117. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20118. return this;
  20119. };
  20120. /**
  20121. * Sets a new pivot point to the current node
  20122. * @param point defines the new pivot point to use
  20123. * @param space defines if the point is in world or local space (local by default)
  20124. * @returns the current TransformNode
  20125. */
  20126. TransformNode.prototype.setPivotPoint = function (point, space) {
  20127. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20128. if (this.getScene().getRenderId() == 0) {
  20129. this.computeWorldMatrix(true);
  20130. }
  20131. var wm = this.getWorldMatrix();
  20132. if (space == BABYLON.Space.WORLD) {
  20133. var tmat = BABYLON.Tmp.Matrix[0];
  20134. wm.invertToRef(tmat);
  20135. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20136. }
  20137. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20138. };
  20139. /**
  20140. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20141. * @returns the pivot point
  20142. */
  20143. TransformNode.prototype.getPivotPoint = function () {
  20144. var point = BABYLON.Vector3.Zero();
  20145. this.getPivotPointToRef(point);
  20146. return point;
  20147. };
  20148. /**
  20149. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20150. * @param result the vector3 to store the result
  20151. * @returns this TransformNode.
  20152. */
  20153. TransformNode.prototype.getPivotPointToRef = function (result) {
  20154. result.x = -this._pivotMatrix.m[12];
  20155. result.y = -this._pivotMatrix.m[13];
  20156. result.z = -this._pivotMatrix.m[14];
  20157. return this;
  20158. };
  20159. /**
  20160. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20161. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20162. */
  20163. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20164. var point = BABYLON.Vector3.Zero();
  20165. this.getAbsolutePivotPointToRef(point);
  20166. return point;
  20167. };
  20168. /**
  20169. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20170. * @param result vector3 to store the result
  20171. * @returns this TransformNode.
  20172. */
  20173. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20174. result.x = this._pivotMatrix.m[12];
  20175. result.y = this._pivotMatrix.m[13];
  20176. result.z = this._pivotMatrix.m[14];
  20177. this.getPivotPointToRef(result);
  20178. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20179. return this;
  20180. };
  20181. /**
  20182. * Defines the passed node as the parent of the current node.
  20183. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20184. * @param node the node ot set as the parent
  20185. * @returns this TransformNode.
  20186. */
  20187. TransformNode.prototype.setParent = function (node) {
  20188. if (!node && !this.parent) {
  20189. return this;
  20190. }
  20191. if (!node) {
  20192. var rotation = BABYLON.Tmp.Quaternion[0];
  20193. var position = BABYLON.Tmp.Vector3[0];
  20194. var scale = BABYLON.Tmp.Vector3[1];
  20195. if (this.parent && this.parent.computeWorldMatrix) {
  20196. this.parent.computeWorldMatrix(true);
  20197. }
  20198. this.computeWorldMatrix(true);
  20199. this.getWorldMatrix().decompose(scale, rotation, position);
  20200. if (this.rotationQuaternion) {
  20201. this.rotationQuaternion.copyFrom(rotation);
  20202. }
  20203. else {
  20204. rotation.toEulerAnglesToRef(this.rotation);
  20205. }
  20206. this.scaling.x = scale.x;
  20207. this.scaling.y = scale.y;
  20208. this.scaling.z = scale.z;
  20209. this.position.x = position.x;
  20210. this.position.y = position.y;
  20211. this.position.z = position.z;
  20212. }
  20213. else {
  20214. var rotation = BABYLON.Tmp.Quaternion[0];
  20215. var position = BABYLON.Tmp.Vector3[0];
  20216. var scale = BABYLON.Tmp.Vector3[1];
  20217. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20218. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20219. this.computeWorldMatrix(true);
  20220. node.computeWorldMatrix(true);
  20221. node.getWorldMatrix().invertToRef(invParentMatrix);
  20222. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20223. diffMatrix.decompose(scale, rotation, position);
  20224. if (this.rotationQuaternion) {
  20225. this.rotationQuaternion.copyFrom(rotation);
  20226. }
  20227. else {
  20228. rotation.toEulerAnglesToRef(this.rotation);
  20229. }
  20230. this.position.x = position.x;
  20231. this.position.y = position.y;
  20232. this.position.z = position.z;
  20233. this.scaling.x = scale.x;
  20234. this.scaling.y = scale.y;
  20235. this.scaling.z = scale.z;
  20236. }
  20237. this.parent = node;
  20238. return this;
  20239. };
  20240. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20241. /**
  20242. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20243. */
  20244. get: function () {
  20245. return this._nonUniformScaling;
  20246. },
  20247. enumerable: true,
  20248. configurable: true
  20249. });
  20250. /** @hidden */
  20251. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20252. if (this._nonUniformScaling === value) {
  20253. return false;
  20254. }
  20255. this._nonUniformScaling = value;
  20256. return true;
  20257. };
  20258. /**
  20259. * Attach the current TransformNode to another TransformNode associated with a bone
  20260. * @param bone Bone affecting the TransformNode
  20261. * @param affectedTransformNode TransformNode associated with the bone
  20262. * @returns this object
  20263. */
  20264. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20265. this._transformToBoneReferal = affectedTransformNode;
  20266. this.parent = bone;
  20267. if (bone.getWorldMatrix().determinant() < 0) {
  20268. this.scalingDeterminant *= -1;
  20269. }
  20270. return this;
  20271. };
  20272. /**
  20273. * Detach the transform node if its associated with a bone
  20274. * @returns this object
  20275. */
  20276. TransformNode.prototype.detachFromBone = function () {
  20277. if (!this.parent) {
  20278. return this;
  20279. }
  20280. if (this.parent.getWorldMatrix().determinant() < 0) {
  20281. this.scalingDeterminant *= -1;
  20282. }
  20283. this._transformToBoneReferal = null;
  20284. this.parent = null;
  20285. return this;
  20286. };
  20287. /**
  20288. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20289. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20290. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20291. * The passed axis is also normalized.
  20292. * @param axis the axis to rotate around
  20293. * @param amount the amount to rotate in radians
  20294. * @param space Space to rotate in (Default: local)
  20295. * @returns the TransformNode.
  20296. */
  20297. TransformNode.prototype.rotate = function (axis, amount, space) {
  20298. axis.normalize();
  20299. if (!this.rotationQuaternion) {
  20300. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20301. this.rotation = BABYLON.Vector3.Zero();
  20302. }
  20303. var rotationQuaternion;
  20304. if (!space || space === BABYLON.Space.LOCAL) {
  20305. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20306. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20307. }
  20308. else {
  20309. if (this.parent) {
  20310. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20311. invertParentWorldMatrix.invert();
  20312. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20313. }
  20314. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20315. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20316. }
  20317. return this;
  20318. };
  20319. /**
  20320. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20321. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20322. * The passed axis is also normalized. .
  20323. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20324. * @param point the point to rotate around
  20325. * @param axis the axis to rotate around
  20326. * @param amount the amount to rotate in radians
  20327. * @returns the TransformNode
  20328. */
  20329. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20330. axis.normalize();
  20331. if (!this.rotationQuaternion) {
  20332. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20333. this.rotation.copyFromFloats(0, 0, 0);
  20334. }
  20335. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20336. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20337. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20338. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20339. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20340. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20341. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20342. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20343. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20344. return this;
  20345. };
  20346. /**
  20347. * Translates the mesh along the axis vector for the passed distance in the given space.
  20348. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20349. * @param axis the axis to translate in
  20350. * @param distance the distance to translate
  20351. * @param space Space to rotate in (Default: local)
  20352. * @returns the TransformNode.
  20353. */
  20354. TransformNode.prototype.translate = function (axis, distance, space) {
  20355. var displacementVector = axis.scale(distance);
  20356. if (!space || space === BABYLON.Space.LOCAL) {
  20357. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20358. this.setPositionWithLocalVector(tempV3);
  20359. }
  20360. else {
  20361. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20362. }
  20363. return this;
  20364. };
  20365. /**
  20366. * Adds a rotation step to the mesh current rotation.
  20367. * x, y, z are Euler angles expressed in radians.
  20368. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20369. * This means this rotation is made in the mesh local space only.
  20370. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20371. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20372. * ```javascript
  20373. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20374. * ```
  20375. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20376. * 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.
  20377. * @param x Rotation to add
  20378. * @param y Rotation to add
  20379. * @param z Rotation to add
  20380. * @returns the TransformNode.
  20381. */
  20382. TransformNode.prototype.addRotation = function (x, y, z) {
  20383. var rotationQuaternion;
  20384. if (this.rotationQuaternion) {
  20385. rotationQuaternion = this.rotationQuaternion;
  20386. }
  20387. else {
  20388. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20389. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20390. }
  20391. var accumulation = BABYLON.Tmp.Quaternion[0];
  20392. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20393. rotationQuaternion.multiplyInPlace(accumulation);
  20394. if (!this.rotationQuaternion) {
  20395. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20396. }
  20397. return this;
  20398. };
  20399. /**
  20400. * Computes the world matrix of the node
  20401. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20402. * @returns the world matrix
  20403. */
  20404. TransformNode.prototype.computeWorldMatrix = function (force) {
  20405. if (this._isWorldMatrixFrozen) {
  20406. return this._worldMatrix;
  20407. }
  20408. if (!force && this.isSynchronized()) {
  20409. this._currentRenderId = this.getScene().getRenderId();
  20410. return this._worldMatrix;
  20411. }
  20412. this._updateCache();
  20413. this._cache.position.copyFrom(this.position);
  20414. this._cache.scaling.copyFrom(this.scaling);
  20415. this._cache.pivotMatrixUpdated = false;
  20416. this._cache.billboardMode = this.billboardMode;
  20417. this._currentRenderId = this.getScene().getRenderId();
  20418. this._childRenderId = this.getScene().getRenderId();
  20419. this._isDirty = false;
  20420. // Scaling
  20421. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20422. // Rotation
  20423. //rotate, if quaternion is set and rotation was used
  20424. if (this.rotationQuaternion) {
  20425. var len = this.rotation.length();
  20426. if (len) {
  20427. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20428. this.rotation.copyFromFloats(0, 0, 0);
  20429. }
  20430. }
  20431. if (this.rotationQuaternion) {
  20432. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20433. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20434. }
  20435. else {
  20436. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20437. this._cache.rotation.copyFrom(this.rotation);
  20438. }
  20439. // Translation
  20440. var camera = this.getScene().activeCamera;
  20441. if (this.infiniteDistance && !this.parent && camera) {
  20442. var cameraWorldMatrix = camera.getWorldMatrix();
  20443. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20444. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20445. }
  20446. else {
  20447. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20448. }
  20449. // Composing transformations
  20450. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20451. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20452. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20453. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20454. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20455. // Need to decompose each rotation here
  20456. var currentPosition = BABYLON.Tmp.Vector3[3];
  20457. if (this.parent && this.parent.getWorldMatrix) {
  20458. if (this._transformToBoneReferal) {
  20459. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20460. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20461. }
  20462. else {
  20463. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20464. }
  20465. }
  20466. else {
  20467. currentPosition.copyFrom(this.position);
  20468. }
  20469. currentPosition.subtractInPlace(camera.globalPosition);
  20470. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20471. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20472. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20473. }
  20474. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20475. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20476. }
  20477. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20478. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20479. }
  20480. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20481. }
  20482. else {
  20483. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20484. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20485. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20486. }
  20487. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20488. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20489. }
  20490. // Post multiply inverse of pivotMatrix
  20491. if (this._postMultiplyPivotMatrix) {
  20492. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20493. }
  20494. // Local world
  20495. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20496. // Parent
  20497. if (this.parent && this.parent.getWorldMatrix) {
  20498. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20499. if (this._transformToBoneReferal) {
  20500. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20501. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20502. }
  20503. else {
  20504. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20505. }
  20506. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20507. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20508. this._worldMatrix.copyFrom(this._localWorld);
  20509. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20510. }
  20511. else {
  20512. if (this._transformToBoneReferal) {
  20513. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20514. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20515. }
  20516. else {
  20517. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20518. }
  20519. }
  20520. this._markSyncedWithParent();
  20521. }
  20522. else {
  20523. this._worldMatrix.copyFrom(this._localWorld);
  20524. }
  20525. // Normal matrix
  20526. if (!this.ignoreNonUniformScaling) {
  20527. if (this.scaling.isNonUniform) {
  20528. this._updateNonUniformScalingState(true);
  20529. }
  20530. else if (this.parent && this.parent._nonUniformScaling) {
  20531. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20532. }
  20533. else {
  20534. this._updateNonUniformScalingState(false);
  20535. }
  20536. }
  20537. else {
  20538. this._updateNonUniformScalingState(false);
  20539. }
  20540. this._afterComputeWorldMatrix();
  20541. // Absolute position
  20542. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20543. // Callbacks
  20544. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20545. if (!this._poseMatrix) {
  20546. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20547. }
  20548. // Cache the determinant
  20549. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20550. return this._worldMatrix;
  20551. };
  20552. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20553. };
  20554. /**
  20555. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20556. * @param func callback function to add
  20557. *
  20558. * @returns the TransformNode.
  20559. */
  20560. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20561. this.onAfterWorldMatrixUpdateObservable.add(func);
  20562. return this;
  20563. };
  20564. /**
  20565. * Removes a registered callback function.
  20566. * @param func callback function to remove
  20567. * @returns the TransformNode.
  20568. */
  20569. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20570. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20571. return this;
  20572. };
  20573. /**
  20574. * Clone the current transform node
  20575. * @param name Name of the new clone
  20576. * @param newParent New parent for the clone
  20577. * @param doNotCloneChildren Do not clone children hierarchy
  20578. * @returns the new transform node
  20579. */
  20580. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20581. var _this = this;
  20582. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20583. result.name = name;
  20584. result.id = name;
  20585. if (newParent) {
  20586. result.parent = newParent;
  20587. }
  20588. if (!doNotCloneChildren) {
  20589. // Children
  20590. var directDescendants = this.getDescendants(true);
  20591. for (var index = 0; index < directDescendants.length; index++) {
  20592. var child = directDescendants[index];
  20593. if (child.clone) {
  20594. child.clone(name + "." + child.name, result);
  20595. }
  20596. }
  20597. }
  20598. return result;
  20599. };
  20600. /**
  20601. * Serializes the objects information.
  20602. * @param currentSerializationObject defines the object to serialize in
  20603. * @returns the serialized object
  20604. */
  20605. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20606. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20607. serializationObject.type = this.getClassName();
  20608. // Parent
  20609. if (this.parent) {
  20610. serializationObject.parentId = this.parent.id;
  20611. }
  20612. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20613. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20614. }
  20615. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20616. serializationObject.isEnabled = this.isEnabled();
  20617. // Parent
  20618. if (this.parent) {
  20619. serializationObject.parentId = this.parent.id;
  20620. }
  20621. return serializationObject;
  20622. };
  20623. // Statics
  20624. /**
  20625. * Returns a new TransformNode object parsed from the source provided.
  20626. * @param parsedTransformNode is the source.
  20627. * @param scene the scne the object belongs to
  20628. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20629. * @returns a new TransformNode object parsed from the source provided.
  20630. */
  20631. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20632. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20633. if (BABYLON.Tags) {
  20634. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20635. }
  20636. if (parsedTransformNode.localMatrix) {
  20637. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20638. }
  20639. else if (parsedTransformNode.pivotMatrix) {
  20640. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20641. }
  20642. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20643. // Parent
  20644. if (parsedTransformNode.parentId) {
  20645. transformNode._waitingParentId = parsedTransformNode.parentId;
  20646. }
  20647. return transformNode;
  20648. };
  20649. /**
  20650. * Releases resources associated with this transform node.
  20651. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20652. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20653. */
  20654. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20655. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20656. // Animations
  20657. this.getScene().stopAnimation(this);
  20658. // Remove from scene
  20659. this.getScene().removeTransformNode(this);
  20660. this.onAfterWorldMatrixUpdateObservable.clear();
  20661. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20662. };
  20663. // Statics
  20664. /**
  20665. * Object will not rotate to face the camera
  20666. */
  20667. TransformNode.BILLBOARDMODE_NONE = 0;
  20668. /**
  20669. * Object will rotate to face the camera but only on the x axis
  20670. */
  20671. TransformNode.BILLBOARDMODE_X = 1;
  20672. /**
  20673. * Object will rotate to face the camera but only on the y axis
  20674. */
  20675. TransformNode.BILLBOARDMODE_Y = 2;
  20676. /**
  20677. * Object will rotate to face the camera but only on the z axis
  20678. */
  20679. TransformNode.BILLBOARDMODE_Z = 4;
  20680. /**
  20681. * Object will rotate to face the camera
  20682. */
  20683. TransformNode.BILLBOARDMODE_ALL = 7;
  20684. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20685. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20686. __decorate([
  20687. BABYLON.serializeAsVector3("position")
  20688. ], TransformNode.prototype, "_position", void 0);
  20689. __decorate([
  20690. BABYLON.serializeAsVector3("rotation")
  20691. ], TransformNode.prototype, "_rotation", void 0);
  20692. __decorate([
  20693. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20694. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20695. __decorate([
  20696. BABYLON.serializeAsVector3("scaling")
  20697. ], TransformNode.prototype, "_scaling", void 0);
  20698. __decorate([
  20699. BABYLON.serialize()
  20700. ], TransformNode.prototype, "billboardMode", void 0);
  20701. __decorate([
  20702. BABYLON.serialize()
  20703. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20704. __decorate([
  20705. BABYLON.serialize()
  20706. ], TransformNode.prototype, "infiniteDistance", void 0);
  20707. __decorate([
  20708. BABYLON.serialize()
  20709. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20710. return TransformNode;
  20711. }(BABYLON.Node));
  20712. BABYLON.TransformNode = TransformNode;
  20713. })(BABYLON || (BABYLON = {}));
  20714. //# sourceMappingURL=babylon.transformNode.js.map
  20715. var BABYLON;
  20716. (function (BABYLON) {
  20717. /** @hidden */
  20718. var _FacetDataStorage = /** @class */ (function () {
  20719. function _FacetDataStorage() {
  20720. this.facetNb = 0; // facet number
  20721. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20722. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20723. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20724. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20725. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20726. this.subDiv = {
  20727. max: 1,
  20728. X: 1,
  20729. Y: 1,
  20730. Z: 1
  20731. };
  20732. this.facetDepthSort = false; // is the facet depth sort to be computed
  20733. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20734. }
  20735. return _FacetDataStorage;
  20736. }());
  20737. /**
  20738. * Class used to store all common mesh properties
  20739. */
  20740. var AbstractMesh = /** @class */ (function (_super) {
  20741. __extends(AbstractMesh, _super);
  20742. // Constructor
  20743. /**
  20744. * Creates a new AbstractMesh
  20745. * @param name defines the name of the mesh
  20746. * @param scene defines the hosting scene
  20747. */
  20748. function AbstractMesh(name, scene) {
  20749. if (scene === void 0) { scene = null; }
  20750. var _this = _super.call(this, name, scene, false) || this;
  20751. _this._facetData = new _FacetDataStorage();
  20752. /** Gets ot sets the culling strategy to use to find visible meshes */
  20753. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20754. // Events
  20755. /**
  20756. * An event triggered when this mesh collides with another one
  20757. */
  20758. _this.onCollideObservable = new BABYLON.Observable();
  20759. /**
  20760. * An event triggered when the collision's position changes
  20761. */
  20762. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20763. /**
  20764. * An event triggered when material is changed
  20765. */
  20766. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20767. // Properties
  20768. /**
  20769. * Gets or sets the orientation for POV movement & rotation
  20770. */
  20771. _this.definedFacingForward = true;
  20772. _this._visibility = 1.0;
  20773. /** Gets or sets the alpha index used to sort transparent meshes
  20774. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20775. */
  20776. _this.alphaIndex = Number.MAX_VALUE;
  20777. /**
  20778. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20779. */
  20780. _this.isVisible = true;
  20781. /**
  20782. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20783. */
  20784. _this.isPickable = true;
  20785. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20786. _this.showSubMeshesBoundingBox = false;
  20787. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20788. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20789. */
  20790. _this.isBlocker = false;
  20791. /**
  20792. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20793. */
  20794. _this.enablePointerMoveEvents = false;
  20795. /**
  20796. * Specifies the rendering group id for this mesh (0 by default)
  20797. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20798. */
  20799. _this.renderingGroupId = 0;
  20800. _this._receiveShadows = false;
  20801. /** Defines color to use when rendering outline */
  20802. _this.outlineColor = BABYLON.Color3.Red();
  20803. /** Define width to use when rendering outline */
  20804. _this.outlineWidth = 0.02;
  20805. /** Defines color to use when rendering overlay */
  20806. _this.overlayColor = BABYLON.Color3.Red();
  20807. /** Defines alpha to use when rendering overlay */
  20808. _this.overlayAlpha = 0.5;
  20809. _this._hasVertexAlpha = false;
  20810. _this._useVertexColors = true;
  20811. _this._computeBonesUsingShaders = true;
  20812. _this._numBoneInfluencers = 4;
  20813. _this._applyFog = true;
  20814. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20815. _this.useOctreeForRenderingSelection = true;
  20816. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20817. _this.useOctreeForPicking = true;
  20818. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20819. _this.useOctreeForCollisions = true;
  20820. _this._layerMask = 0x0FFFFFFF;
  20821. /**
  20822. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20823. */
  20824. _this.alwaysSelectAsActiveMesh = false;
  20825. /**
  20826. * Gets or sets the current action manager
  20827. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20828. */
  20829. _this.actionManager = null;
  20830. // Collisions
  20831. _this._checkCollisions = false;
  20832. _this._collisionMask = -1;
  20833. _this._collisionGroup = -1;
  20834. /**
  20835. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20836. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20837. */
  20838. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20839. /**
  20840. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20841. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20842. */
  20843. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20844. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20845. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20846. // Edges
  20847. /**
  20848. * Defines edge width used when edgesRenderer is enabled
  20849. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20850. */
  20851. _this.edgesWidth = 1;
  20852. /**
  20853. * Defines edge color used when edgesRenderer is enabled
  20854. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20855. */
  20856. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20857. /** @hidden */
  20858. _this._renderId = 0;
  20859. /** @hidden */
  20860. _this._intersectionsInProgress = new Array();
  20861. /** @hidden */
  20862. _this._unIndexed = false;
  20863. /** @hidden */
  20864. _this._lightSources = new Array();
  20865. /**
  20866. * An event triggered when the mesh is rebuilt.
  20867. */
  20868. _this.onRebuildObservable = new BABYLON.Observable();
  20869. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20870. if (collidedMesh === void 0) { collidedMesh = null; }
  20871. //TODO move this to the collision coordinator!
  20872. if (_this.getScene().workerCollisions) {
  20873. newPosition.multiplyInPlace(_this._collider._radius);
  20874. }
  20875. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20876. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20877. _this.position.addInPlace(_this._diffPositionForCollisions);
  20878. }
  20879. if (collidedMesh) {
  20880. _this.onCollideObservable.notifyObservers(collidedMesh);
  20881. }
  20882. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20883. };
  20884. _this.getScene().addMesh(_this);
  20885. _this._resyncLightSources();
  20886. return _this;
  20887. }
  20888. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20889. /**
  20890. * No billboard
  20891. */
  20892. get: function () {
  20893. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20894. },
  20895. enumerable: true,
  20896. configurable: true
  20897. });
  20898. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20899. /** Billboard on X axis */
  20900. get: function () {
  20901. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20902. },
  20903. enumerable: true,
  20904. configurable: true
  20905. });
  20906. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20907. /** Billboard on Y axis */
  20908. get: function () {
  20909. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20910. },
  20911. enumerable: true,
  20912. configurable: true
  20913. });
  20914. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20915. /** Billboard on Z axis */
  20916. get: function () {
  20917. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20918. },
  20919. enumerable: true,
  20920. configurable: true
  20921. });
  20922. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20923. /** Billboard on all axes */
  20924. get: function () {
  20925. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20926. },
  20927. enumerable: true,
  20928. configurable: true
  20929. });
  20930. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20931. /**
  20932. * Gets the number of facets in the mesh
  20933. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20934. */
  20935. get: function () {
  20936. return this._facetData.facetNb;
  20937. },
  20938. enumerable: true,
  20939. configurable: true
  20940. });
  20941. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20942. /**
  20943. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20944. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20945. */
  20946. get: function () {
  20947. return this._facetData.partitioningSubdivisions;
  20948. },
  20949. set: function (nb) {
  20950. this._facetData.partitioningSubdivisions = nb;
  20951. },
  20952. enumerable: true,
  20953. configurable: true
  20954. });
  20955. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20956. /**
  20957. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20958. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20959. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20960. */
  20961. get: function () {
  20962. return this._facetData.partitioningBBoxRatio;
  20963. },
  20964. set: function (ratio) {
  20965. this._facetData.partitioningBBoxRatio = ratio;
  20966. },
  20967. enumerable: true,
  20968. configurable: true
  20969. });
  20970. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20971. /**
  20972. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20973. * Works only for updatable meshes.
  20974. * Doesn't work with multi-materials
  20975. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20976. */
  20977. get: function () {
  20978. return this._facetData.facetDepthSort;
  20979. },
  20980. set: function (sort) {
  20981. this._facetData.facetDepthSort = sort;
  20982. },
  20983. enumerable: true,
  20984. configurable: true
  20985. });
  20986. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20987. /**
  20988. * The location (Vector3) where the facet depth sort must be computed from.
  20989. * By default, the active camera position.
  20990. * Used only when facet depth sort is enabled
  20991. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20992. */
  20993. get: function () {
  20994. return this._facetData.facetDepthSortFrom;
  20995. },
  20996. set: function (location) {
  20997. this._facetData.facetDepthSortFrom = location;
  20998. },
  20999. enumerable: true,
  21000. configurable: true
  21001. });
  21002. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21003. /**
  21004. * gets a boolean indicating if facetData is enabled
  21005. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21006. */
  21007. get: function () {
  21008. return this._facetData.facetDataEnabled;
  21009. },
  21010. enumerable: true,
  21011. configurable: true
  21012. });
  21013. /** @hidden */
  21014. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21015. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21016. return false;
  21017. }
  21018. this._markSubMeshesAsMiscDirty();
  21019. return true;
  21020. };
  21021. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21022. /** Set a function to call when this mesh collides with another one */
  21023. set: function (callback) {
  21024. if (this._onCollideObserver) {
  21025. this.onCollideObservable.remove(this._onCollideObserver);
  21026. }
  21027. this._onCollideObserver = this.onCollideObservable.add(callback);
  21028. },
  21029. enumerable: true,
  21030. configurable: true
  21031. });
  21032. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21033. /** Set a function to call when the collision's position changes */
  21034. set: function (callback) {
  21035. if (this._onCollisionPositionChangeObserver) {
  21036. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21037. }
  21038. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21039. },
  21040. enumerable: true,
  21041. configurable: true
  21042. });
  21043. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21044. /**
  21045. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21046. */
  21047. get: function () {
  21048. return this._visibility;
  21049. },
  21050. /**
  21051. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21052. */
  21053. set: function (value) {
  21054. if (this._visibility === value) {
  21055. return;
  21056. }
  21057. this._visibility = value;
  21058. this._markSubMeshesAsMiscDirty();
  21059. },
  21060. enumerable: true,
  21061. configurable: true
  21062. });
  21063. Object.defineProperty(AbstractMesh.prototype, "material", {
  21064. /** Gets or sets current material */
  21065. get: function () {
  21066. return this._material;
  21067. },
  21068. set: function (value) {
  21069. if (this._material === value) {
  21070. return;
  21071. }
  21072. this._material = value;
  21073. if (this.onMaterialChangedObservable.hasObservers) {
  21074. this.onMaterialChangedObservable.notifyObservers(this);
  21075. }
  21076. if (!this.subMeshes) {
  21077. return;
  21078. }
  21079. this._unBindEffect();
  21080. },
  21081. enumerable: true,
  21082. configurable: true
  21083. });
  21084. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21085. /**
  21086. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21087. * @see http://doc.babylonjs.com/babylon101/shadows
  21088. */
  21089. get: function () {
  21090. return this._receiveShadows;
  21091. },
  21092. set: function (value) {
  21093. if (this._receiveShadows === value) {
  21094. return;
  21095. }
  21096. this._receiveShadows = value;
  21097. this._markSubMeshesAsLightDirty();
  21098. },
  21099. enumerable: true,
  21100. configurable: true
  21101. });
  21102. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21103. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21104. get: function () {
  21105. return this._hasVertexAlpha;
  21106. },
  21107. set: function (value) {
  21108. if (this._hasVertexAlpha === value) {
  21109. return;
  21110. }
  21111. this._hasVertexAlpha = value;
  21112. this._markSubMeshesAsAttributesDirty();
  21113. this._markSubMeshesAsMiscDirty();
  21114. },
  21115. enumerable: true,
  21116. configurable: true
  21117. });
  21118. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21119. /** 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) */
  21120. get: function () {
  21121. return this._useVertexColors;
  21122. },
  21123. set: function (value) {
  21124. if (this._useVertexColors === value) {
  21125. return;
  21126. }
  21127. this._useVertexColors = value;
  21128. this._markSubMeshesAsAttributesDirty();
  21129. },
  21130. enumerable: true,
  21131. configurable: true
  21132. });
  21133. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21134. /**
  21135. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21136. */
  21137. get: function () {
  21138. return this._computeBonesUsingShaders;
  21139. },
  21140. set: function (value) {
  21141. if (this._computeBonesUsingShaders === value) {
  21142. return;
  21143. }
  21144. this._computeBonesUsingShaders = value;
  21145. this._markSubMeshesAsAttributesDirty();
  21146. },
  21147. enumerable: true,
  21148. configurable: true
  21149. });
  21150. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21151. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21152. get: function () {
  21153. return this._numBoneInfluencers;
  21154. },
  21155. set: function (value) {
  21156. if (this._numBoneInfluencers === value) {
  21157. return;
  21158. }
  21159. this._numBoneInfluencers = value;
  21160. this._markSubMeshesAsAttributesDirty();
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21166. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21167. get: function () {
  21168. return this._applyFog;
  21169. },
  21170. set: function (value) {
  21171. if (this._applyFog === value) {
  21172. return;
  21173. }
  21174. this._applyFog = value;
  21175. this._markSubMeshesAsMiscDirty();
  21176. },
  21177. enumerable: true,
  21178. configurable: true
  21179. });
  21180. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21181. /**
  21182. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21183. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21184. */
  21185. get: function () {
  21186. return this._layerMask;
  21187. },
  21188. set: function (value) {
  21189. if (value === this._layerMask) {
  21190. return;
  21191. }
  21192. this._layerMask = value;
  21193. this._resyncLightSources();
  21194. },
  21195. enumerable: true,
  21196. configurable: true
  21197. });
  21198. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21199. /**
  21200. * Gets or sets a collision mask used to mask collisions (default is -1).
  21201. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21202. */
  21203. get: function () {
  21204. return this._collisionMask;
  21205. },
  21206. set: function (mask) {
  21207. this._collisionMask = !isNaN(mask) ? mask : -1;
  21208. },
  21209. enumerable: true,
  21210. configurable: true
  21211. });
  21212. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21213. /**
  21214. * Gets or sets the current collision group mask (-1 by default).
  21215. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21216. */
  21217. get: function () {
  21218. return this._collisionGroup;
  21219. },
  21220. set: function (mask) {
  21221. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21222. },
  21223. enumerable: true,
  21224. configurable: true
  21225. });
  21226. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21227. /** @hidden */
  21228. get: function () {
  21229. return null;
  21230. },
  21231. enumerable: true,
  21232. configurable: true
  21233. });
  21234. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21235. get: function () {
  21236. return this._skeleton;
  21237. },
  21238. /**
  21239. * Gets or sets a skeleton to apply skining transformations
  21240. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21241. */
  21242. set: function (value) {
  21243. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21244. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21245. }
  21246. if (value && value.needInitialSkinMatrix) {
  21247. value._registerMeshWithPoseMatrix(this);
  21248. }
  21249. this._skeleton = value;
  21250. if (!this._skeleton) {
  21251. this._bonesTransformMatrices = null;
  21252. }
  21253. this._markSubMeshesAsAttributesDirty();
  21254. },
  21255. enumerable: true,
  21256. configurable: true
  21257. });
  21258. /**
  21259. * Returns the string "AbstractMesh"
  21260. * @returns "AbstractMesh"
  21261. */
  21262. AbstractMesh.prototype.getClassName = function () {
  21263. return "AbstractMesh";
  21264. };
  21265. /**
  21266. * Gets a string representation of the current mesh
  21267. * @param fullDetails defines a boolean indicating if full details must be included
  21268. * @returns a string representation of the current mesh
  21269. */
  21270. AbstractMesh.prototype.toString = function (fullDetails) {
  21271. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21272. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21273. if (this._skeleton) {
  21274. ret += ", skeleton: " + this._skeleton.name;
  21275. }
  21276. if (fullDetails) {
  21277. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21278. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21279. }
  21280. return ret;
  21281. };
  21282. /** @hidden */
  21283. AbstractMesh.prototype._rebuild = function () {
  21284. this.onRebuildObservable.notifyObservers(this);
  21285. if (this._occlusionQuery) {
  21286. this._occlusionQuery = null;
  21287. }
  21288. if (!this.subMeshes) {
  21289. return;
  21290. }
  21291. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21292. var subMesh = _a[_i];
  21293. subMesh._rebuild();
  21294. }
  21295. };
  21296. /** @hidden */
  21297. AbstractMesh.prototype._resyncLightSources = function () {
  21298. this._lightSources.length = 0;
  21299. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21300. var light = _a[_i];
  21301. if (!light.isEnabled()) {
  21302. continue;
  21303. }
  21304. if (light.canAffectMesh(this)) {
  21305. this._lightSources.push(light);
  21306. }
  21307. }
  21308. this._markSubMeshesAsLightDirty();
  21309. };
  21310. /** @hidden */
  21311. AbstractMesh.prototype._resyncLighSource = function (light) {
  21312. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21313. var index = this._lightSources.indexOf(light);
  21314. if (index === -1) {
  21315. if (!isIn) {
  21316. return;
  21317. }
  21318. this._lightSources.push(light);
  21319. }
  21320. else {
  21321. if (isIn) {
  21322. return;
  21323. }
  21324. this._lightSources.splice(index, 1);
  21325. }
  21326. this._markSubMeshesAsLightDirty();
  21327. };
  21328. /** @hidden */
  21329. AbstractMesh.prototype._unBindEffect = function () {
  21330. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21331. var subMesh = _a[_i];
  21332. subMesh.setEffect(null);
  21333. }
  21334. };
  21335. /** @hidden */
  21336. AbstractMesh.prototype._removeLightSource = function (light) {
  21337. var index = this._lightSources.indexOf(light);
  21338. if (index === -1) {
  21339. return;
  21340. }
  21341. this._lightSources.splice(index, 1);
  21342. this._markSubMeshesAsLightDirty();
  21343. };
  21344. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21345. if (!this.subMeshes) {
  21346. return;
  21347. }
  21348. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21349. var subMesh = _a[_i];
  21350. if (subMesh._materialDefines) {
  21351. func(subMesh._materialDefines);
  21352. }
  21353. }
  21354. };
  21355. /** @hidden */
  21356. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21357. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21358. };
  21359. /** @hidden */
  21360. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21361. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21362. };
  21363. /** @hidden */
  21364. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21365. if (!this.subMeshes) {
  21366. return;
  21367. }
  21368. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21369. var subMesh = _a[_i];
  21370. var material = subMesh.getMaterial();
  21371. if (material) {
  21372. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21373. }
  21374. }
  21375. };
  21376. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21377. /**
  21378. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21379. */
  21380. get: function () {
  21381. return this._scaling;
  21382. },
  21383. set: function (newScaling) {
  21384. this._scaling = newScaling;
  21385. if (this.physicsImpostor) {
  21386. this.physicsImpostor.forceUpdate();
  21387. }
  21388. },
  21389. enumerable: true,
  21390. configurable: true
  21391. });
  21392. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21393. // Methods
  21394. /**
  21395. * Returns true if the mesh is blocked. Implemented by child classes
  21396. */
  21397. get: function () {
  21398. return false;
  21399. },
  21400. enumerable: true,
  21401. configurable: true
  21402. });
  21403. /**
  21404. * Returns the mesh itself by default. Implemented by child classes
  21405. * @param camera defines the camera to use to pick the right LOD level
  21406. * @returns the currentAbstractMesh
  21407. */
  21408. AbstractMesh.prototype.getLOD = function (camera) {
  21409. return this;
  21410. };
  21411. /**
  21412. * Returns 0 by default. Implemented by child classes
  21413. * @returns an integer
  21414. */
  21415. AbstractMesh.prototype.getTotalVertices = function () {
  21416. return 0;
  21417. };
  21418. /**
  21419. * Returns null by default. Implemented by child classes
  21420. * @returns null
  21421. */
  21422. AbstractMesh.prototype.getIndices = function () {
  21423. return null;
  21424. };
  21425. /**
  21426. * Returns the array of the requested vertex data kind. Implemented by child classes
  21427. * @param kind defines the vertex data kind to use
  21428. * @returns null
  21429. */
  21430. AbstractMesh.prototype.getVerticesData = function (kind) {
  21431. return null;
  21432. };
  21433. /**
  21434. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21435. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21436. * Note that a new underlying VertexBuffer object is created each call.
  21437. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21438. * @param kind defines vertex data kind:
  21439. * * BABYLON.VertexBuffer.PositionKind
  21440. * * BABYLON.VertexBuffer.UVKind
  21441. * * BABYLON.VertexBuffer.UV2Kind
  21442. * * BABYLON.VertexBuffer.UV3Kind
  21443. * * BABYLON.VertexBuffer.UV4Kind
  21444. * * BABYLON.VertexBuffer.UV5Kind
  21445. * * BABYLON.VertexBuffer.UV6Kind
  21446. * * BABYLON.VertexBuffer.ColorKind
  21447. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21448. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21449. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21450. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21451. * @param data defines the data source
  21452. * @param updatable defines if the data must be flagged as updatable (or static)
  21453. * @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
  21454. * @returns the current mesh
  21455. */
  21456. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21457. return this;
  21458. };
  21459. /**
  21460. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21461. * If the mesh has no geometry, it is simply returned as it is.
  21462. * @param kind defines vertex data kind:
  21463. * * BABYLON.VertexBuffer.PositionKind
  21464. * * BABYLON.VertexBuffer.UVKind
  21465. * * BABYLON.VertexBuffer.UV2Kind
  21466. * * BABYLON.VertexBuffer.UV3Kind
  21467. * * BABYLON.VertexBuffer.UV4Kind
  21468. * * BABYLON.VertexBuffer.UV5Kind
  21469. * * BABYLON.VertexBuffer.UV6Kind
  21470. * * BABYLON.VertexBuffer.ColorKind
  21471. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21472. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21473. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21474. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21475. * @param data defines the data source
  21476. * @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
  21477. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21478. * @returns the current mesh
  21479. */
  21480. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21481. return this;
  21482. };
  21483. /**
  21484. * Sets the mesh indices,
  21485. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21486. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21487. * @param totalVertices Defines the total number of vertices
  21488. * @returns the current mesh
  21489. */
  21490. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21491. return this;
  21492. };
  21493. /**
  21494. * Gets a boolean indicating if specific vertex data is present
  21495. * @param kind defines the vertex data kind to use
  21496. * @returns true is data kind is present
  21497. */
  21498. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21499. return false;
  21500. };
  21501. /**
  21502. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21503. * @returns a BoundingInfo
  21504. */
  21505. AbstractMesh.prototype.getBoundingInfo = function () {
  21506. if (this._masterMesh) {
  21507. return this._masterMesh.getBoundingInfo();
  21508. }
  21509. if (!this._boundingInfo) {
  21510. // this._boundingInfo is being created here
  21511. this._updateBoundingInfo();
  21512. }
  21513. // cannot be null.
  21514. return this._boundingInfo;
  21515. };
  21516. /**
  21517. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21518. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21519. * @returns the current mesh
  21520. */
  21521. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21522. if (includeDescendants === void 0) { includeDescendants = true; }
  21523. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21524. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21525. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21526. if (maxDimension === 0) {
  21527. return this;
  21528. }
  21529. var scale = 1 / maxDimension;
  21530. this.scaling.scaleInPlace(scale);
  21531. return this;
  21532. };
  21533. /**
  21534. * Overwrite the current bounding info
  21535. * @param boundingInfo defines the new bounding info
  21536. * @returns the current mesh
  21537. */
  21538. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21539. this._boundingInfo = boundingInfo;
  21540. return this;
  21541. };
  21542. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21543. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21544. get: function () {
  21545. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. /** @hidden */
  21551. AbstractMesh.prototype._preActivate = function () {
  21552. };
  21553. /** @hidden */
  21554. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21555. };
  21556. /** @hidden */
  21557. AbstractMesh.prototype._activate = function (renderId) {
  21558. this._renderId = renderId;
  21559. };
  21560. /**
  21561. * Gets the current world matrix
  21562. * @returns a Matrix
  21563. */
  21564. AbstractMesh.prototype.getWorldMatrix = function () {
  21565. if (this._masterMesh) {
  21566. return this._masterMesh.getWorldMatrix();
  21567. }
  21568. return _super.prototype.getWorldMatrix.call(this);
  21569. };
  21570. /** @hidden */
  21571. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21572. if (this._masterMesh) {
  21573. return this._masterMesh._getWorldMatrixDeterminant();
  21574. }
  21575. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21576. };
  21577. // ================================== Point of View Movement =================================
  21578. /**
  21579. * Perform relative position change from the point of view of behind the front of the mesh.
  21580. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21581. * Supports definition of mesh facing forward or backward
  21582. * @param amountRight defines the distance on the right axis
  21583. * @param amountUp defines the distance on the up axis
  21584. * @param amountForward defines the distance on the forward axis
  21585. * @returns the current mesh
  21586. */
  21587. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21588. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21589. return this;
  21590. };
  21591. /**
  21592. * Calculate relative position change from the point of view of behind the front of the mesh.
  21593. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21594. * Supports definition of mesh facing forward or backward
  21595. * @param amountRight defines the distance on the right axis
  21596. * @param amountUp defines the distance on the up axis
  21597. * @param amountForward defines the distance on the forward axis
  21598. * @returns the new displacement vector
  21599. */
  21600. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21601. var rotMatrix = new BABYLON.Matrix();
  21602. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21603. rotQuaternion.toRotationMatrix(rotMatrix);
  21604. var translationDelta = BABYLON.Vector3.Zero();
  21605. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21606. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21607. return translationDelta;
  21608. };
  21609. // ================================== Point of View Rotation =================================
  21610. /**
  21611. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21612. * Supports definition of mesh facing forward or backward
  21613. * @param flipBack defines the flip
  21614. * @param twirlClockwise defines the twirl
  21615. * @param tiltRight defines the tilt
  21616. * @returns the current mesh
  21617. */
  21618. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21619. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21620. return this;
  21621. };
  21622. /**
  21623. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21624. * Supports definition of mesh facing forward or backward.
  21625. * @param flipBack defines the flip
  21626. * @param twirlClockwise defines the twirl
  21627. * @param tiltRight defines the tilt
  21628. * @returns the new rotation vector
  21629. */
  21630. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21631. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21632. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21633. };
  21634. /**
  21635. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21636. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21637. * @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
  21638. * @returns the new bounding vectors
  21639. */
  21640. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21641. if (includeDescendants === void 0) { includeDescendants = true; }
  21642. if (predicate === void 0) { predicate = null; }
  21643. // Ensures that all world matrix will be recomputed.
  21644. this.getScene().incrementRenderId();
  21645. this.computeWorldMatrix(true);
  21646. var min;
  21647. var max;
  21648. var boundingInfo = this.getBoundingInfo();
  21649. if (!this.subMeshes) {
  21650. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21651. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21652. }
  21653. else {
  21654. min = boundingInfo.boundingBox.minimumWorld;
  21655. max = boundingInfo.boundingBox.maximumWorld;
  21656. }
  21657. if (includeDescendants) {
  21658. var descendants = this.getDescendants(false);
  21659. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21660. var descendant = descendants_1[_i];
  21661. var childMesh = descendant;
  21662. childMesh.computeWorldMatrix(true);
  21663. // Filters meshes based on custom predicate function.
  21664. if (predicate && !predicate(childMesh)) {
  21665. continue;
  21666. }
  21667. //make sure we have the needed params to get mix and max
  21668. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21669. continue;
  21670. }
  21671. var childBoundingInfo = childMesh.getBoundingInfo();
  21672. var boundingBox = childBoundingInfo.boundingBox;
  21673. var minBox = boundingBox.minimumWorld;
  21674. var maxBox = boundingBox.maximumWorld;
  21675. BABYLON.Tools.CheckExtends(minBox, min, max);
  21676. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21677. }
  21678. }
  21679. return {
  21680. min: min,
  21681. max: max
  21682. };
  21683. };
  21684. /** @hidden */
  21685. AbstractMesh.prototype._updateBoundingInfo = function () {
  21686. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21687. this._boundingInfo.update(this.worldMatrixFromCache);
  21688. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21689. return this;
  21690. };
  21691. /** @hidden */
  21692. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21693. if (!this.subMeshes) {
  21694. return this;
  21695. }
  21696. var count = this.subMeshes.length;
  21697. for (var subIndex = 0; subIndex < count; subIndex++) {
  21698. var subMesh = this.subMeshes[subIndex];
  21699. if (count > 1 || !subMesh.IsGlobal) {
  21700. subMesh.updateBoundingInfo(matrix);
  21701. }
  21702. }
  21703. return this;
  21704. };
  21705. /** @hidden */
  21706. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21707. // Bounding info
  21708. this._updateBoundingInfo();
  21709. };
  21710. /**
  21711. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21712. * A mesh is in the frustum if its bounding box intersects the frustum
  21713. * @param frustumPlanes defines the frustum to test
  21714. * @returns true if the mesh is in the frustum planes
  21715. */
  21716. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21717. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21718. };
  21719. /**
  21720. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21721. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21722. * @param frustumPlanes defines the frustum to test
  21723. * @returns true if the mesh is completely in the frustum planes
  21724. */
  21725. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21726. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21727. };
  21728. /**
  21729. * True if the mesh intersects another mesh or a SolidParticle object
  21730. * @param mesh defines a target mesh or SolidParticle to test
  21731. * @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)
  21732. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21733. * @returns true if there is an intersection
  21734. */
  21735. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21736. if (precise === void 0) { precise = false; }
  21737. if (!this._boundingInfo || !mesh._boundingInfo) {
  21738. return false;
  21739. }
  21740. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21741. return true;
  21742. }
  21743. if (includeDescendants) {
  21744. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21745. var child = _a[_i];
  21746. if (child.intersectsMesh(mesh, precise, true)) {
  21747. return true;
  21748. }
  21749. }
  21750. }
  21751. return false;
  21752. };
  21753. /**
  21754. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21755. * @param point defines the point to test
  21756. * @returns true if there is an intersection
  21757. */
  21758. AbstractMesh.prototype.intersectsPoint = function (point) {
  21759. if (!this._boundingInfo) {
  21760. return false;
  21761. }
  21762. return this._boundingInfo.intersectsPoint(point);
  21763. };
  21764. /**
  21765. * Gets the position of the current mesh in camera space
  21766. * @param camera defines the camera to use
  21767. * @returns a position
  21768. */
  21769. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21770. if (camera === void 0) { camera = null; }
  21771. if (!camera) {
  21772. camera = this.getScene().activeCamera;
  21773. }
  21774. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21775. };
  21776. /**
  21777. * Returns the distance from the mesh to the active camera
  21778. * @param camera defines the camera to use
  21779. * @returns the distance
  21780. */
  21781. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21782. if (camera === void 0) { camera = null; }
  21783. if (!camera) {
  21784. camera = this.getScene().activeCamera;
  21785. }
  21786. return this.absolutePosition.subtract(camera.position).length();
  21787. };
  21788. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21789. // Collisions
  21790. /**
  21791. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21792. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21793. */
  21794. get: function () {
  21795. return this._checkCollisions;
  21796. },
  21797. set: function (collisionEnabled) {
  21798. this._checkCollisions = collisionEnabled;
  21799. if (this.getScene().workerCollisions) {
  21800. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21801. }
  21802. },
  21803. enumerable: true,
  21804. configurable: true
  21805. });
  21806. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21807. /**
  21808. * Gets Collider object used to compute collisions (not physics)
  21809. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21810. */
  21811. get: function () {
  21812. return this._collider;
  21813. },
  21814. enumerable: true,
  21815. configurable: true
  21816. });
  21817. /**
  21818. * Move the mesh using collision engine
  21819. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21820. * @param displacement defines the requested displacement vector
  21821. * @returns the current mesh
  21822. */
  21823. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21824. var globalPosition = this.getAbsolutePosition();
  21825. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21826. if (!this._collider) {
  21827. this._collider = new BABYLON.Collider();
  21828. }
  21829. this._collider._radius = this.ellipsoid;
  21830. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21831. return this;
  21832. };
  21833. // Collisions
  21834. /** @hidden */
  21835. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21836. this._generatePointsArray();
  21837. if (!this._positions) {
  21838. return this;
  21839. }
  21840. // Transformation
  21841. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21842. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21843. subMesh._lastColliderWorldVertices = [];
  21844. subMesh._trianglePlanes = [];
  21845. var start = subMesh.verticesStart;
  21846. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21847. for (var i = start; i < end; i++) {
  21848. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21849. }
  21850. }
  21851. // Collide
  21852. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21853. if (collider.collisionFound) {
  21854. collider.collidedMesh = this;
  21855. }
  21856. return this;
  21857. };
  21858. /** @hidden */
  21859. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21860. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21861. var len = subMeshes.length;
  21862. for (var index = 0; index < len; index++) {
  21863. var subMesh = subMeshes.data[index];
  21864. // Bounding test
  21865. if (len > 1 && !subMesh._checkCollision(collider)) {
  21866. continue;
  21867. }
  21868. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21869. }
  21870. return this;
  21871. };
  21872. /** @hidden */
  21873. AbstractMesh.prototype._checkCollision = function (collider) {
  21874. // Bounding box test
  21875. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  21876. return this;
  21877. }
  21878. // Transformation matrix
  21879. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21880. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21881. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21882. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21883. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21884. return this;
  21885. };
  21886. // Picking
  21887. /** @hidden */
  21888. AbstractMesh.prototype._generatePointsArray = function () {
  21889. return false;
  21890. };
  21891. /**
  21892. * Checks if the passed Ray intersects with the mesh
  21893. * @param ray defines the ray to use
  21894. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21895. * @returns the picking info
  21896. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21897. */
  21898. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21899. var pickingInfo = new BABYLON.PickingInfo();
  21900. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21901. return pickingInfo;
  21902. }
  21903. if (!this._generatePointsArray()) {
  21904. return pickingInfo;
  21905. }
  21906. var intersectInfo = null;
  21907. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21908. var len = subMeshes.length;
  21909. for (var index = 0; index < len; index++) {
  21910. var subMesh = subMeshes.data[index];
  21911. // Bounding test
  21912. if (len > 1 && !subMesh.canIntersects(ray)) {
  21913. continue;
  21914. }
  21915. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21916. if (currentIntersectInfo) {
  21917. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21918. intersectInfo = currentIntersectInfo;
  21919. intersectInfo.subMeshId = index;
  21920. if (fastCheck) {
  21921. break;
  21922. }
  21923. }
  21924. }
  21925. }
  21926. if (intersectInfo) {
  21927. // Get picked point
  21928. var world = this.getWorldMatrix();
  21929. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21930. var direction = ray.direction.clone();
  21931. direction = direction.scale(intersectInfo.distance);
  21932. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21933. var pickedPoint = worldOrigin.add(worldDirection);
  21934. // Return result
  21935. pickingInfo.hit = true;
  21936. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21937. pickingInfo.pickedPoint = pickedPoint;
  21938. pickingInfo.pickedMesh = this;
  21939. pickingInfo.bu = intersectInfo.bu || 0;
  21940. pickingInfo.bv = intersectInfo.bv || 0;
  21941. pickingInfo.faceId = intersectInfo.faceId;
  21942. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21943. return pickingInfo;
  21944. }
  21945. return pickingInfo;
  21946. };
  21947. /**
  21948. * Clones the current mesh
  21949. * @param name defines the mesh name
  21950. * @param newParent defines the new mesh parent
  21951. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21952. * @returns the new mesh
  21953. */
  21954. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21955. return null;
  21956. };
  21957. /**
  21958. * Disposes all the submeshes of the current meshnp
  21959. * @returns the current mesh
  21960. */
  21961. AbstractMesh.prototype.releaseSubMeshes = function () {
  21962. if (this.subMeshes) {
  21963. while (this.subMeshes.length) {
  21964. this.subMeshes[0].dispose();
  21965. }
  21966. }
  21967. else {
  21968. this.subMeshes = new Array();
  21969. }
  21970. return this;
  21971. };
  21972. /**
  21973. * Releases resources associated with this abstract mesh.
  21974. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21975. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21976. */
  21977. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21978. var _this = this;
  21979. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21980. var index;
  21981. // Smart Array Retainers.
  21982. this.getScene().freeActiveMeshes();
  21983. this.getScene().freeRenderingGroups();
  21984. // Action manager
  21985. if (this.actionManager !== undefined && this.actionManager !== null) {
  21986. this.actionManager.dispose();
  21987. this.actionManager = null;
  21988. }
  21989. // Skeleton
  21990. this._skeleton = null;
  21991. // Intersections in progress
  21992. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21993. var other = this._intersectionsInProgress[index];
  21994. var pos = other._intersectionsInProgress.indexOf(this);
  21995. other._intersectionsInProgress.splice(pos, 1);
  21996. }
  21997. this._intersectionsInProgress = [];
  21998. // Lights
  21999. var lights = this.getScene().lights;
  22000. lights.forEach(function (light) {
  22001. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22002. if (meshIndex !== -1) {
  22003. light.includedOnlyMeshes.splice(meshIndex, 1);
  22004. }
  22005. meshIndex = light.excludedMeshes.indexOf(_this);
  22006. if (meshIndex !== -1) {
  22007. light.excludedMeshes.splice(meshIndex, 1);
  22008. }
  22009. // Shadow generators
  22010. var generator = light.getShadowGenerator();
  22011. if (generator) {
  22012. var shadowMap = generator.getShadowMap();
  22013. if (shadowMap && shadowMap.renderList) {
  22014. meshIndex = shadowMap.renderList.indexOf(_this);
  22015. if (meshIndex !== -1) {
  22016. shadowMap.renderList.splice(meshIndex, 1);
  22017. }
  22018. }
  22019. }
  22020. });
  22021. // SubMeshes
  22022. if (this.getClassName() !== "InstancedMesh") {
  22023. this.releaseSubMeshes();
  22024. }
  22025. // Query
  22026. var engine = this.getScene().getEngine();
  22027. if (this._occlusionQuery) {
  22028. this.isOcclusionQueryInProgress = false;
  22029. engine.deleteQuery(this._occlusionQuery);
  22030. this._occlusionQuery = null;
  22031. }
  22032. // Engine
  22033. engine.wipeCaches();
  22034. // Remove from scene
  22035. this.getScene().removeMesh(this);
  22036. if (disposeMaterialAndTextures) {
  22037. if (this.material) {
  22038. this.material.dispose(false, true);
  22039. }
  22040. }
  22041. if (!doNotRecurse) {
  22042. // Particles
  22043. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22044. if (this.getScene().particleSystems[index].emitter === this) {
  22045. this.getScene().particleSystems[index].dispose();
  22046. index--;
  22047. }
  22048. }
  22049. }
  22050. // facet data
  22051. if (this._facetData.facetDataEnabled) {
  22052. this.disableFacetData();
  22053. }
  22054. this.onAfterWorldMatrixUpdateObservable.clear();
  22055. this.onCollideObservable.clear();
  22056. this.onCollisionPositionChangeObservable.clear();
  22057. this.onRebuildObservable.clear();
  22058. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22059. };
  22060. /**
  22061. * Adds the passed mesh as a child to the current mesh
  22062. * @param mesh defines the child mesh
  22063. * @returns the current mesh
  22064. */
  22065. AbstractMesh.prototype.addChild = function (mesh) {
  22066. mesh.setParent(this);
  22067. return this;
  22068. };
  22069. /**
  22070. * Removes the passed mesh from the current mesh children list
  22071. * @param mesh defines the child mesh
  22072. * @returns the current mesh
  22073. */
  22074. AbstractMesh.prototype.removeChild = function (mesh) {
  22075. mesh.setParent(null);
  22076. return this;
  22077. };
  22078. // Facet data
  22079. /** @hidden */
  22080. AbstractMesh.prototype._initFacetData = function () {
  22081. var data = this._facetData;
  22082. if (!data.facetNormals) {
  22083. data.facetNormals = new Array();
  22084. }
  22085. if (!data.facetPositions) {
  22086. data.facetPositions = new Array();
  22087. }
  22088. if (!data.facetPartitioning) {
  22089. data.facetPartitioning = new Array();
  22090. }
  22091. data.facetNb = (this.getIndices().length / 3) | 0;
  22092. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22093. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22094. for (var f = 0; f < data.facetNb; f++) {
  22095. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22096. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22097. }
  22098. data.facetDataEnabled = true;
  22099. return this;
  22100. };
  22101. /**
  22102. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22103. * This method can be called within the render loop.
  22104. * 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
  22105. * @returns the current mesh
  22106. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22107. */
  22108. AbstractMesh.prototype.updateFacetData = function () {
  22109. var data = this._facetData;
  22110. if (!data.facetDataEnabled) {
  22111. this._initFacetData();
  22112. }
  22113. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22114. var indices = this.getIndices();
  22115. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22116. var bInfo = this.getBoundingInfo();
  22117. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22118. // init arrays, matrix and sort function on first call
  22119. data.facetDepthSortEnabled = true;
  22120. if (indices instanceof Uint16Array) {
  22121. data.depthSortedIndices = new Uint16Array(indices);
  22122. }
  22123. else if (indices instanceof Uint32Array) {
  22124. data.depthSortedIndices = new Uint32Array(indices);
  22125. }
  22126. else {
  22127. var needs32bits = false;
  22128. for (var i = 0; i < indices.length; i++) {
  22129. if (indices[i] > 65535) {
  22130. needs32bits = true;
  22131. break;
  22132. }
  22133. }
  22134. if (needs32bits) {
  22135. data.depthSortedIndices = new Uint32Array(indices);
  22136. }
  22137. else {
  22138. data.depthSortedIndices = new Uint16Array(indices);
  22139. }
  22140. }
  22141. data.facetDepthSortFunction = function (f1, f2) {
  22142. return (f2.sqDistance - f1.sqDistance);
  22143. };
  22144. if (!data.facetDepthSortFrom) {
  22145. var camera = this.getScene().activeCamera;
  22146. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22147. }
  22148. data.depthSortedFacets = [];
  22149. for (var f = 0; f < data.facetNb; f++) {
  22150. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22151. data.depthSortedFacets.push(depthSortedFacet);
  22152. }
  22153. data.invertedMatrix = BABYLON.Matrix.Identity();
  22154. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22155. }
  22156. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22157. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22158. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22159. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22160. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22161. data.subDiv.max = data.partitioningSubdivisions;
  22162. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22163. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22164. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22165. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22166. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22167. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22168. // set the parameters for ComputeNormals()
  22169. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22170. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22171. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22172. data.facetParameters.bInfo = bInfo;
  22173. data.facetParameters.bbSize = data.bbSize;
  22174. data.facetParameters.subDiv = data.subDiv;
  22175. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22176. data.facetParameters.depthSort = data.facetDepthSort;
  22177. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22178. this.computeWorldMatrix(true);
  22179. this._worldMatrix.invertToRef(data.invertedMatrix);
  22180. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22181. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22182. }
  22183. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22184. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22185. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22186. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22187. var l = (data.depthSortedIndices.length / 3) | 0;
  22188. for (var f = 0; f < l; f++) {
  22189. var sind = data.depthSortedFacets[f].ind;
  22190. data.depthSortedIndices[f * 3] = indices[sind];
  22191. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22192. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22193. }
  22194. this.updateIndices(data.depthSortedIndices);
  22195. }
  22196. return this;
  22197. };
  22198. /**
  22199. * Returns the facetLocalNormals array.
  22200. * The normals are expressed in the mesh local spac
  22201. * @returns an array of Vector3
  22202. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22203. */
  22204. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22205. if (!this._facetData.facetNormals) {
  22206. this.updateFacetData();
  22207. }
  22208. return this._facetData.facetNormals;
  22209. };
  22210. /**
  22211. * Returns the facetLocalPositions array.
  22212. * The facet positions are expressed in the mesh local space
  22213. * @returns an array of Vector3
  22214. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22215. */
  22216. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22217. if (!this._facetData.facetPositions) {
  22218. this.updateFacetData();
  22219. }
  22220. return this._facetData.facetPositions;
  22221. };
  22222. /**
  22223. * Returns the facetLocalPartioning array
  22224. * @returns an array of array of numbers
  22225. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22226. */
  22227. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22228. if (!this._facetData.facetPartitioning) {
  22229. this.updateFacetData();
  22230. }
  22231. return this._facetData.facetPartitioning;
  22232. };
  22233. /**
  22234. * Returns the i-th facet position in the world system.
  22235. * This method allocates a new Vector3 per call
  22236. * @param i defines the facet index
  22237. * @returns a new Vector3
  22238. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22239. */
  22240. AbstractMesh.prototype.getFacetPosition = function (i) {
  22241. var pos = BABYLON.Vector3.Zero();
  22242. this.getFacetPositionToRef(i, pos);
  22243. return pos;
  22244. };
  22245. /**
  22246. * Sets the reference Vector3 with the i-th facet position in the world system
  22247. * @param i defines the facet index
  22248. * @param ref defines the target vector
  22249. * @returns the current mesh
  22250. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22251. */
  22252. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22253. var localPos = (this.getFacetLocalPositions())[i];
  22254. var world = this.getWorldMatrix();
  22255. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22256. return this;
  22257. };
  22258. /**
  22259. * Returns the i-th facet normal in the world system.
  22260. * This method allocates a new Vector3 per call
  22261. * @param i defines the facet index
  22262. * @returns a new Vector3
  22263. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22264. */
  22265. AbstractMesh.prototype.getFacetNormal = function (i) {
  22266. var norm = BABYLON.Vector3.Zero();
  22267. this.getFacetNormalToRef(i, norm);
  22268. return norm;
  22269. };
  22270. /**
  22271. * Sets the reference Vector3 with the i-th facet normal in the world system
  22272. * @param i defines the facet index
  22273. * @param ref defines the target vector
  22274. * @returns the current mesh
  22275. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22276. */
  22277. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22278. var localNorm = (this.getFacetLocalNormals())[i];
  22279. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22280. return this;
  22281. };
  22282. /**
  22283. * 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)
  22284. * @param x defines x coordinate
  22285. * @param y defines y coordinate
  22286. * @param z defines z coordinate
  22287. * @returns the array of facet indexes
  22288. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22289. */
  22290. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22291. var bInfo = this.getBoundingInfo();
  22292. var data = this._facetData;
  22293. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22294. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22295. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22296. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22297. return null;
  22298. }
  22299. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22300. };
  22301. /**
  22302. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22303. * @param projected sets as the (x,y,z) world projection on the facet
  22304. * @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
  22305. * @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
  22306. * @param x defines x coordinate
  22307. * @param y defines y coordinate
  22308. * @param z defines z coordinate
  22309. * @returns the face index if found (or null instead)
  22310. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22311. */
  22312. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22313. if (checkFace === void 0) { checkFace = false; }
  22314. if (facing === void 0) { facing = true; }
  22315. var world = this.getWorldMatrix();
  22316. var invMat = BABYLON.Tmp.Matrix[5];
  22317. world.invertToRef(invMat);
  22318. var invVect = BABYLON.Tmp.Vector3[8];
  22319. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22320. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22321. if (projected) {
  22322. // tranform the local computed projected vector to world coordinates
  22323. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22324. }
  22325. return closest;
  22326. };
  22327. /**
  22328. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22329. * @param projected sets as the (x,y,z) local projection on the facet
  22330. * @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
  22331. * @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
  22332. * @param x defines x coordinate
  22333. * @param y defines y coordinate
  22334. * @param z defines z coordinate
  22335. * @returns the face index if found (or null instead)
  22336. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22337. */
  22338. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22339. if (checkFace === void 0) { checkFace = false; }
  22340. if (facing === void 0) { facing = true; }
  22341. var closest = null;
  22342. var tmpx = 0.0;
  22343. var tmpy = 0.0;
  22344. var tmpz = 0.0;
  22345. var d = 0.0; // tmp dot facet normal * facet position
  22346. var t0 = 0.0;
  22347. var projx = 0.0;
  22348. var projy = 0.0;
  22349. var projz = 0.0;
  22350. // Get all the facets in the same partitioning block than (x, y, z)
  22351. var facetPositions = this.getFacetLocalPositions();
  22352. var facetNormals = this.getFacetLocalNormals();
  22353. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22354. if (!facetsInBlock) {
  22355. return null;
  22356. }
  22357. // Get the closest facet to (x, y, z)
  22358. var shortest = Number.MAX_VALUE; // init distance vars
  22359. var tmpDistance = shortest;
  22360. var fib; // current facet in the block
  22361. var norm; // current facet normal
  22362. var p0; // current facet barycenter position
  22363. // loop on all the facets in the current partitioning block
  22364. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22365. fib = facetsInBlock[idx];
  22366. norm = facetNormals[fib];
  22367. p0 = facetPositions[fib];
  22368. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22369. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22370. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22371. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22372. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22373. projx = x + norm.x * t0;
  22374. projy = y + norm.y * t0;
  22375. projz = z + norm.z * t0;
  22376. tmpx = projx - x;
  22377. tmpy = projy - y;
  22378. tmpz = projz - z;
  22379. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22380. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22381. shortest = tmpDistance;
  22382. closest = fib;
  22383. if (projected) {
  22384. projected.x = projx;
  22385. projected.y = projy;
  22386. projected.z = projz;
  22387. }
  22388. }
  22389. }
  22390. }
  22391. return closest;
  22392. };
  22393. /**
  22394. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22395. * @returns the parameters
  22396. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22397. */
  22398. AbstractMesh.prototype.getFacetDataParameters = function () {
  22399. return this._facetData.facetParameters;
  22400. };
  22401. /**
  22402. * Disables the feature FacetData and frees the related memory
  22403. * @returns the current mesh
  22404. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22405. */
  22406. AbstractMesh.prototype.disableFacetData = function () {
  22407. if (this._facetData.facetDataEnabled) {
  22408. this._facetData.facetDataEnabled = false;
  22409. this._facetData.facetPositions = new Array();
  22410. this._facetData.facetNormals = new Array();
  22411. this._facetData.facetPartitioning = new Array();
  22412. this._facetData.facetParameters = null;
  22413. this._facetData.depthSortedIndices = new Uint32Array(0);
  22414. }
  22415. return this;
  22416. };
  22417. /**
  22418. * Updates the AbstractMesh indices array
  22419. * @param indices defines the data source
  22420. * @returns the current mesh
  22421. */
  22422. AbstractMesh.prototype.updateIndices = function (indices) {
  22423. return this;
  22424. };
  22425. /**
  22426. * Creates new normals data for the mesh
  22427. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22428. * @returns the current mesh
  22429. */
  22430. AbstractMesh.prototype.createNormals = function (updatable) {
  22431. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22432. var indices = this.getIndices();
  22433. var normals;
  22434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22435. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22436. }
  22437. else {
  22438. normals = [];
  22439. }
  22440. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22442. return this;
  22443. };
  22444. /**
  22445. * Align the mesh with a normal
  22446. * @param normal defines the normal to use
  22447. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22448. * @returns the current mesh
  22449. */
  22450. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22451. if (!upDirection) {
  22452. upDirection = BABYLON.Axis.Y;
  22453. }
  22454. var axisX = BABYLON.Tmp.Vector3[0];
  22455. var axisZ = BABYLON.Tmp.Vector3[1];
  22456. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22457. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22458. if (this.rotationQuaternion) {
  22459. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22460. }
  22461. else {
  22462. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22463. }
  22464. return this;
  22465. };
  22466. /** @hidden */
  22467. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22468. return false;
  22469. };
  22470. /** No occlusion */
  22471. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22472. /** Occlusion set to optimisitic */
  22473. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22474. /** Occlusion set to strict */
  22475. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22476. /** Use an accurante occlusion algorithm */
  22477. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22478. /** Use a conservative occlusion algorithm */
  22479. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22480. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22481. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22482. /** Culling strategy with bounding sphere only and then frustum culling */
  22483. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22484. return AbstractMesh;
  22485. }(BABYLON.TransformNode));
  22486. BABYLON.AbstractMesh = AbstractMesh;
  22487. })(BABYLON || (BABYLON = {}));
  22488. //# sourceMappingURL=babylon.abstractMesh.js.map
  22489. var BABYLON;
  22490. (function (BABYLON) {
  22491. /**
  22492. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22493. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22494. * 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.
  22495. */
  22496. var Light = /** @class */ (function (_super) {
  22497. __extends(Light, _super);
  22498. /**
  22499. * Creates a Light object in the scene.
  22500. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22501. * @param name The firendly name of the light
  22502. * @param scene The scene the light belongs too
  22503. */
  22504. function Light(name, scene) {
  22505. var _this = _super.call(this, name, scene) || this;
  22506. /**
  22507. * Diffuse gives the basic color to an object.
  22508. */
  22509. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22510. /**
  22511. * Specular produces a highlight color on an object.
  22512. * Note: This is note affecting PBR materials.
  22513. */
  22514. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22515. /**
  22516. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22517. * falling off base on range or angle.
  22518. * This can be set to any values in Light.FALLOFF_x.
  22519. *
  22520. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22521. * other types of materials.
  22522. */
  22523. _this.falloffType = Light.FALLOFF_DEFAULT;
  22524. /**
  22525. * Strength of the light.
  22526. * Note: By default it is define in the framework own unit.
  22527. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22528. */
  22529. _this.intensity = 1.0;
  22530. _this._range = Number.MAX_VALUE;
  22531. _this._inverseSquaredRange = 0;
  22532. /**
  22533. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22534. * of light.
  22535. */
  22536. _this._photometricScale = 1.0;
  22537. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22538. _this._radius = 0.00001;
  22539. /**
  22540. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22541. * exceeding the number allowed of the materials.
  22542. */
  22543. _this.renderPriority = 0;
  22544. _this._shadowEnabled = true;
  22545. _this._excludeWithLayerMask = 0;
  22546. _this._includeOnlyWithLayerMask = 0;
  22547. _this._lightmapMode = 0;
  22548. /**
  22549. * @hidden Internal use only.
  22550. */
  22551. _this._excludedMeshesIds = new Array();
  22552. /**
  22553. * @hidden Internal use only.
  22554. */
  22555. _this._includedOnlyMeshesIds = new Array();
  22556. _this.getScene().addLight(_this);
  22557. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22558. _this._buildUniformLayout();
  22559. _this.includedOnlyMeshes = new Array();
  22560. _this.excludedMeshes = new Array();
  22561. _this._resyncMeshes();
  22562. return _this;
  22563. }
  22564. Object.defineProperty(Light.prototype, "range", {
  22565. /**
  22566. * Defines how far from the source the light is impacting in scene units.
  22567. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22568. */
  22569. get: function () {
  22570. return this._range;
  22571. },
  22572. /**
  22573. * Defines how far from the source the light is impacting in scene units.
  22574. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22575. */
  22576. set: function (value) {
  22577. this._range = value;
  22578. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22579. },
  22580. enumerable: true,
  22581. configurable: true
  22582. });
  22583. Object.defineProperty(Light.prototype, "intensityMode", {
  22584. /**
  22585. * Gets the photometric scale used to interpret the intensity.
  22586. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22587. */
  22588. get: function () {
  22589. return this._intensityMode;
  22590. },
  22591. /**
  22592. * Sets the photometric scale used to interpret the intensity.
  22593. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22594. */
  22595. set: function (value) {
  22596. this._intensityMode = value;
  22597. this._computePhotometricScale();
  22598. },
  22599. enumerable: true,
  22600. configurable: true
  22601. });
  22602. Object.defineProperty(Light.prototype, "radius", {
  22603. /**
  22604. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22605. */
  22606. get: function () {
  22607. return this._radius;
  22608. },
  22609. /**
  22610. * sets the light radius used by PBR Materials to simulate soft area lights.
  22611. */
  22612. set: function (value) {
  22613. this._radius = value;
  22614. this._computePhotometricScale();
  22615. },
  22616. enumerable: true,
  22617. configurable: true
  22618. });
  22619. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22620. /**
  22621. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22622. * the current shadow generator.
  22623. */
  22624. get: function () {
  22625. return this._shadowEnabled;
  22626. },
  22627. /**
  22628. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22629. * the current shadow generator.
  22630. */
  22631. set: function (value) {
  22632. if (this._shadowEnabled === value) {
  22633. return;
  22634. }
  22635. this._shadowEnabled = value;
  22636. this._markMeshesAsLightDirty();
  22637. },
  22638. enumerable: true,
  22639. configurable: true
  22640. });
  22641. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22642. /**
  22643. * Gets the only meshes impacted by this light.
  22644. */
  22645. get: function () {
  22646. return this._includedOnlyMeshes;
  22647. },
  22648. /**
  22649. * Sets the only meshes impacted by this light.
  22650. */
  22651. set: function (value) {
  22652. this._includedOnlyMeshes = value;
  22653. this._hookArrayForIncludedOnly(value);
  22654. },
  22655. enumerable: true,
  22656. configurable: true
  22657. });
  22658. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22659. /**
  22660. * Gets the meshes not impacted by this light.
  22661. */
  22662. get: function () {
  22663. return this._excludedMeshes;
  22664. },
  22665. /**
  22666. * Sets the meshes not impacted by this light.
  22667. */
  22668. set: function (value) {
  22669. this._excludedMeshes = value;
  22670. this._hookArrayForExcluded(value);
  22671. },
  22672. enumerable: true,
  22673. configurable: true
  22674. });
  22675. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22676. /**
  22677. * Gets the layer id use to find what meshes are not impacted by the light.
  22678. * Inactive if 0
  22679. */
  22680. get: function () {
  22681. return this._excludeWithLayerMask;
  22682. },
  22683. /**
  22684. * Sets the layer id use to find what meshes are not impacted by the light.
  22685. * Inactive if 0
  22686. */
  22687. set: function (value) {
  22688. this._excludeWithLayerMask = value;
  22689. this._resyncMeshes();
  22690. },
  22691. enumerable: true,
  22692. configurable: true
  22693. });
  22694. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22695. /**
  22696. * Gets the layer id use to find what meshes are impacted by the light.
  22697. * Inactive if 0
  22698. */
  22699. get: function () {
  22700. return this._includeOnlyWithLayerMask;
  22701. },
  22702. /**
  22703. * Sets the layer id use to find what meshes are impacted by the light.
  22704. * Inactive if 0
  22705. */
  22706. set: function (value) {
  22707. this._includeOnlyWithLayerMask = value;
  22708. this._resyncMeshes();
  22709. },
  22710. enumerable: true,
  22711. configurable: true
  22712. });
  22713. Object.defineProperty(Light.prototype, "lightmapMode", {
  22714. /**
  22715. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22716. */
  22717. get: function () {
  22718. return this._lightmapMode;
  22719. },
  22720. /**
  22721. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22722. */
  22723. set: function (value) {
  22724. if (this._lightmapMode === value) {
  22725. return;
  22726. }
  22727. this._lightmapMode = value;
  22728. this._markMeshesAsLightDirty();
  22729. },
  22730. enumerable: true,
  22731. configurable: true
  22732. });
  22733. /**
  22734. * Returns the string "Light".
  22735. * @returns the class name
  22736. */
  22737. Light.prototype.getClassName = function () {
  22738. return "Light";
  22739. };
  22740. /**
  22741. * Converts the light information to a readable string for debug purpose.
  22742. * @param fullDetails Supports for multiple levels of logging within scene loading
  22743. * @returns the human readable light info
  22744. */
  22745. Light.prototype.toString = function (fullDetails) {
  22746. var ret = "Name: " + this.name;
  22747. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22748. if (this.animations) {
  22749. for (var i = 0; i < this.animations.length; i++) {
  22750. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22751. }
  22752. }
  22753. if (fullDetails) {
  22754. }
  22755. return ret;
  22756. };
  22757. /** @hidden */
  22758. Light.prototype._syncParentEnabledState = function () {
  22759. _super.prototype._syncParentEnabledState.call(this);
  22760. this._resyncMeshes();
  22761. };
  22762. /**
  22763. * Set the enabled state of this node.
  22764. * @param value - the new enabled state
  22765. */
  22766. Light.prototype.setEnabled = function (value) {
  22767. _super.prototype.setEnabled.call(this, value);
  22768. this._resyncMeshes();
  22769. };
  22770. /**
  22771. * Returns the Light associated shadow generator if any.
  22772. * @return the associated shadow generator.
  22773. */
  22774. Light.prototype.getShadowGenerator = function () {
  22775. return this._shadowGenerator;
  22776. };
  22777. /**
  22778. * Returns a Vector3, the absolute light position in the World.
  22779. * @returns the world space position of the light
  22780. */
  22781. Light.prototype.getAbsolutePosition = function () {
  22782. return BABYLON.Vector3.Zero();
  22783. };
  22784. /**
  22785. * Specifies if the light will affect the passed mesh.
  22786. * @param mesh The mesh to test against the light
  22787. * @return true the mesh is affected otherwise, false.
  22788. */
  22789. Light.prototype.canAffectMesh = function (mesh) {
  22790. if (!mesh) {
  22791. return true;
  22792. }
  22793. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22794. return false;
  22795. }
  22796. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22797. return false;
  22798. }
  22799. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22800. return false;
  22801. }
  22802. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22803. return false;
  22804. }
  22805. return true;
  22806. };
  22807. /**
  22808. * Sort function to order lights for rendering.
  22809. * @param a First Light object to compare to second.
  22810. * @param b Second Light object to compare first.
  22811. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22812. */
  22813. Light.CompareLightsPriority = function (a, b) {
  22814. //shadow-casting lights have priority over non-shadow-casting lights
  22815. //the renderPrioirty is a secondary sort criterion
  22816. if (a.shadowEnabled !== b.shadowEnabled) {
  22817. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22818. }
  22819. return b.renderPriority - a.renderPriority;
  22820. };
  22821. /**
  22822. * Releases resources associated with this node.
  22823. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22824. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22825. */
  22826. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22827. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22828. if (this._shadowGenerator) {
  22829. this._shadowGenerator.dispose();
  22830. this._shadowGenerator = null;
  22831. }
  22832. // Animations
  22833. this.getScene().stopAnimation(this);
  22834. // Remove from meshes
  22835. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22836. var mesh = _a[_i];
  22837. mesh._removeLightSource(this);
  22838. }
  22839. this._uniformBuffer.dispose();
  22840. // Remove from scene
  22841. this.getScene().removeLight(this);
  22842. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22843. };
  22844. /**
  22845. * Returns the light type ID (integer).
  22846. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22847. */
  22848. Light.prototype.getTypeID = function () {
  22849. return 0;
  22850. };
  22851. /**
  22852. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22853. * @returns the scaled intensity in intensity mode unit
  22854. */
  22855. Light.prototype.getScaledIntensity = function () {
  22856. return this._photometricScale * this.intensity;
  22857. };
  22858. /**
  22859. * Returns a new Light object, named "name", from the current one.
  22860. * @param name The name of the cloned light
  22861. * @returns the new created light
  22862. */
  22863. Light.prototype.clone = function (name) {
  22864. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22865. if (!constructor) {
  22866. return null;
  22867. }
  22868. return BABYLON.SerializationHelper.Clone(constructor, this);
  22869. };
  22870. /**
  22871. * Serializes the current light into a Serialization object.
  22872. * @returns the serialized object.
  22873. */
  22874. Light.prototype.serialize = function () {
  22875. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22876. // Type
  22877. serializationObject.type = this.getTypeID();
  22878. // Parent
  22879. if (this.parent) {
  22880. serializationObject.parentId = this.parent.id;
  22881. }
  22882. // Inclusion / exclusions
  22883. if (this.excludedMeshes.length > 0) {
  22884. serializationObject.excludedMeshesIds = [];
  22885. this.excludedMeshes.forEach(function (mesh) {
  22886. serializationObject.excludedMeshesIds.push(mesh.id);
  22887. });
  22888. }
  22889. if (this.includedOnlyMeshes.length > 0) {
  22890. serializationObject.includedOnlyMeshesIds = [];
  22891. this.includedOnlyMeshes.forEach(function (mesh) {
  22892. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22893. });
  22894. }
  22895. // Animations
  22896. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22897. serializationObject.ranges = this.serializeAnimationRanges();
  22898. return serializationObject;
  22899. };
  22900. /**
  22901. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22902. * This new light is named "name" and added to the passed scene.
  22903. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22904. * @param name The friendly name of the light
  22905. * @param scene The scene the new light will belong to
  22906. * @returns the constructor function
  22907. */
  22908. Light.GetConstructorFromName = function (type, name, scene) {
  22909. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22910. if (constructorFunc) {
  22911. return constructorFunc;
  22912. }
  22913. // Default to no light for none present once.
  22914. return null;
  22915. };
  22916. /**
  22917. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22918. * @param parsedLight The JSON representation of the light
  22919. * @param scene The scene to create the parsed light in
  22920. * @returns the created light after parsing
  22921. */
  22922. Light.Parse = function (parsedLight, scene) {
  22923. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22924. if (!constructor) {
  22925. return null;
  22926. }
  22927. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22928. // Inclusion / exclusions
  22929. if (parsedLight.excludedMeshesIds) {
  22930. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22931. }
  22932. if (parsedLight.includedOnlyMeshesIds) {
  22933. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22934. }
  22935. // Parent
  22936. if (parsedLight.parentId) {
  22937. light._waitingParentId = parsedLight.parentId;
  22938. }
  22939. // Animations
  22940. if (parsedLight.animations) {
  22941. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22942. var parsedAnimation = parsedLight.animations[animationIndex];
  22943. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22944. }
  22945. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22946. }
  22947. if (parsedLight.autoAnimate) {
  22948. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22949. }
  22950. return light;
  22951. };
  22952. Light.prototype._hookArrayForExcluded = function (array) {
  22953. var _this = this;
  22954. var oldPush = array.push;
  22955. array.push = function () {
  22956. var items = [];
  22957. for (var _i = 0; _i < arguments.length; _i++) {
  22958. items[_i] = arguments[_i];
  22959. }
  22960. var result = oldPush.apply(array, items);
  22961. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22962. var item = items_1[_a];
  22963. item._resyncLighSource(_this);
  22964. }
  22965. return result;
  22966. };
  22967. var oldSplice = array.splice;
  22968. array.splice = function (index, deleteCount) {
  22969. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22970. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22971. var item = deleted_1[_i];
  22972. item._resyncLighSource(_this);
  22973. }
  22974. return deleted;
  22975. };
  22976. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22977. var item = array_1[_i];
  22978. item._resyncLighSource(this);
  22979. }
  22980. };
  22981. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22982. var _this = this;
  22983. var oldPush = array.push;
  22984. array.push = function () {
  22985. var items = [];
  22986. for (var _i = 0; _i < arguments.length; _i++) {
  22987. items[_i] = arguments[_i];
  22988. }
  22989. var result = oldPush.apply(array, items);
  22990. _this._resyncMeshes();
  22991. return result;
  22992. };
  22993. var oldSplice = array.splice;
  22994. array.splice = function (index, deleteCount) {
  22995. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22996. _this._resyncMeshes();
  22997. return deleted;
  22998. };
  22999. this._resyncMeshes();
  23000. };
  23001. Light.prototype._resyncMeshes = function () {
  23002. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23003. var mesh = _a[_i];
  23004. mesh._resyncLighSource(this);
  23005. }
  23006. };
  23007. /**
  23008. * Forces the meshes to update their light related information in their rendering used effects
  23009. * @hidden Internal Use Only
  23010. */
  23011. Light.prototype._markMeshesAsLightDirty = function () {
  23012. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23013. var mesh = _a[_i];
  23014. if (mesh._lightSources.indexOf(this) !== -1) {
  23015. mesh._markSubMeshesAsLightDirty();
  23016. }
  23017. }
  23018. };
  23019. /**
  23020. * Recomputes the cached photometric scale if needed.
  23021. */
  23022. Light.prototype._computePhotometricScale = function () {
  23023. this._photometricScale = this._getPhotometricScale();
  23024. this.getScene().resetCachedMaterial();
  23025. };
  23026. /**
  23027. * Returns the Photometric Scale according to the light type and intensity mode.
  23028. */
  23029. Light.prototype._getPhotometricScale = function () {
  23030. var photometricScale = 0.0;
  23031. var lightTypeID = this.getTypeID();
  23032. //get photometric mode
  23033. var photometricMode = this.intensityMode;
  23034. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23035. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23036. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23037. }
  23038. else {
  23039. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23040. }
  23041. }
  23042. //compute photometric scale
  23043. switch (lightTypeID) {
  23044. case Light.LIGHTTYPEID_POINTLIGHT:
  23045. case Light.LIGHTTYPEID_SPOTLIGHT:
  23046. switch (photometricMode) {
  23047. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23048. photometricScale = 1.0 / (4.0 * Math.PI);
  23049. break;
  23050. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23051. photometricScale = 1.0;
  23052. break;
  23053. case Light.INTENSITYMODE_LUMINANCE:
  23054. photometricScale = this.radius * this.radius;
  23055. break;
  23056. }
  23057. break;
  23058. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23059. switch (photometricMode) {
  23060. case Light.INTENSITYMODE_ILLUMINANCE:
  23061. photometricScale = 1.0;
  23062. break;
  23063. case Light.INTENSITYMODE_LUMINANCE:
  23064. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23065. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23066. var apexAngleRadians = this.radius;
  23067. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23068. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23069. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23070. photometricScale = solidAngle;
  23071. break;
  23072. }
  23073. break;
  23074. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23075. // No fall off in hemisperic light.
  23076. photometricScale = 1.0;
  23077. break;
  23078. }
  23079. return photometricScale;
  23080. };
  23081. /**
  23082. * Reorder the light in the scene according to their defined priority.
  23083. * @hidden Internal Use Only
  23084. */
  23085. Light.prototype._reorderLightsInScene = function () {
  23086. var scene = this.getScene();
  23087. if (this._renderPriority != 0) {
  23088. scene.requireLightSorting = true;
  23089. }
  23090. this.getScene().sortLightsByPriority();
  23091. };
  23092. /**
  23093. * Falloff Default: light is falling off following the material specification:
  23094. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23095. */
  23096. Light.FALLOFF_DEFAULT = 0;
  23097. /**
  23098. * Falloff Physical: light is falling off following the inverse squared distance law.
  23099. */
  23100. Light.FALLOFF_PHYSICAL = 1;
  23101. /**
  23102. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23103. * to enhance interoperability with other engines.
  23104. */
  23105. Light.FALLOFF_GLTF = 2;
  23106. /**
  23107. * Falloff Standard: light is falling off like in the standard material
  23108. * to enhance interoperability with other materials.
  23109. */
  23110. Light.FALLOFF_STANDARD = 3;
  23111. //lightmapMode Consts
  23112. /**
  23113. * If every light affecting the material is in this lightmapMode,
  23114. * material.lightmapTexture adds or multiplies
  23115. * (depends on material.useLightmapAsShadowmap)
  23116. * after every other light calculations.
  23117. */
  23118. Light.LIGHTMAP_DEFAULT = 0;
  23119. /**
  23120. * material.lightmapTexture as only diffuse lighting from this light
  23121. * adds only specular lighting from this light
  23122. * adds dynamic shadows
  23123. */
  23124. Light.LIGHTMAP_SPECULAR = 1;
  23125. /**
  23126. * material.lightmapTexture as only lighting
  23127. * no light calculation from this light
  23128. * only adds dynamic shadows from this light
  23129. */
  23130. Light.LIGHTMAP_SHADOWSONLY = 2;
  23131. // Intensity Mode Consts
  23132. /**
  23133. * Each light type uses the default quantity according to its type:
  23134. * point/spot lights use luminous intensity
  23135. * directional lights use illuminance
  23136. */
  23137. Light.INTENSITYMODE_AUTOMATIC = 0;
  23138. /**
  23139. * lumen (lm)
  23140. */
  23141. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23142. /**
  23143. * candela (lm/sr)
  23144. */
  23145. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23146. /**
  23147. * lux (lm/m^2)
  23148. */
  23149. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23150. /**
  23151. * nit (cd/m^2)
  23152. */
  23153. Light.INTENSITYMODE_LUMINANCE = 4;
  23154. // Light types ids const.
  23155. /**
  23156. * Light type const id of the point light.
  23157. */
  23158. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23159. /**
  23160. * Light type const id of the directional light.
  23161. */
  23162. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23163. /**
  23164. * Light type const id of the spot light.
  23165. */
  23166. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23167. /**
  23168. * Light type const id of the hemispheric light.
  23169. */
  23170. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23171. __decorate([
  23172. BABYLON.serializeAsColor3()
  23173. ], Light.prototype, "diffuse", void 0);
  23174. __decorate([
  23175. BABYLON.serializeAsColor3()
  23176. ], Light.prototype, "specular", void 0);
  23177. __decorate([
  23178. BABYLON.serialize()
  23179. ], Light.prototype, "falloffType", void 0);
  23180. __decorate([
  23181. BABYLON.serialize()
  23182. ], Light.prototype, "intensity", void 0);
  23183. __decorate([
  23184. BABYLON.serialize()
  23185. ], Light.prototype, "range", null);
  23186. __decorate([
  23187. BABYLON.serialize()
  23188. ], Light.prototype, "intensityMode", null);
  23189. __decorate([
  23190. BABYLON.serialize()
  23191. ], Light.prototype, "radius", null);
  23192. __decorate([
  23193. BABYLON.serialize()
  23194. ], Light.prototype, "_renderPriority", void 0);
  23195. __decorate([
  23196. BABYLON.expandToProperty("_reorderLightsInScene")
  23197. ], Light.prototype, "renderPriority", void 0);
  23198. __decorate([
  23199. BABYLON.serialize("shadowEnabled")
  23200. ], Light.prototype, "_shadowEnabled", void 0);
  23201. __decorate([
  23202. BABYLON.serialize("excludeWithLayerMask")
  23203. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23204. __decorate([
  23205. BABYLON.serialize("includeOnlyWithLayerMask")
  23206. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23207. __decorate([
  23208. BABYLON.serialize("lightmapMode")
  23209. ], Light.prototype, "_lightmapMode", void 0);
  23210. return Light;
  23211. }(BABYLON.Node));
  23212. BABYLON.Light = Light;
  23213. })(BABYLON || (BABYLON = {}));
  23214. //# sourceMappingURL=babylon.light.js.map
  23215. var BABYLON;
  23216. (function (BABYLON) {
  23217. /**
  23218. * This is the base class of all the camera used in the application.
  23219. * @see http://doc.babylonjs.com/features/cameras
  23220. */
  23221. var Camera = /** @class */ (function (_super) {
  23222. __extends(Camera, _super);
  23223. /**
  23224. * Instantiates a new camera object.
  23225. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23226. * @see http://doc.babylonjs.com/features/cameras
  23227. * @param name Defines the name of the camera in the scene
  23228. * @param position Defines the position of the camera
  23229. * @param scene Defines the scene the camera belongs too
  23230. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23231. */
  23232. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23233. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23234. var _this = _super.call(this, name, scene) || this;
  23235. /**
  23236. * The vector the camera should consider as up.
  23237. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23238. */
  23239. _this.upVector = BABYLON.Vector3.Up();
  23240. /**
  23241. * Define the current limit on the left side for an orthographic camera
  23242. * In scene unit
  23243. */
  23244. _this.orthoLeft = null;
  23245. /**
  23246. * Define the current limit on the right side for an orthographic camera
  23247. * In scene unit
  23248. */
  23249. _this.orthoRight = null;
  23250. /**
  23251. * Define the current limit on the bottom side for an orthographic camera
  23252. * In scene unit
  23253. */
  23254. _this.orthoBottom = null;
  23255. /**
  23256. * Define the current limit on the top side for an orthographic camera
  23257. * In scene unit
  23258. */
  23259. _this.orthoTop = null;
  23260. /**
  23261. * Field Of View is set in Radians. (default is 0.8)
  23262. */
  23263. _this.fov = 0.8;
  23264. /**
  23265. * Define the minimum distance the camera can see from.
  23266. * This is important to note that the depth buffer are not infinite and the closer it starts
  23267. * the more your scene might encounter depth fighting issue.
  23268. */
  23269. _this.minZ = 1;
  23270. /**
  23271. * Define the maximum distance the camera can see to.
  23272. * This is important to note that the depth buffer are not infinite and the further it end
  23273. * the more your scene might encounter depth fighting issue.
  23274. */
  23275. _this.maxZ = 10000.0;
  23276. /**
  23277. * Define the default inertia of the camera.
  23278. * This helps giving a smooth feeling to the camera movement.
  23279. */
  23280. _this.inertia = 0.9;
  23281. /**
  23282. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23283. */
  23284. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23285. /**
  23286. * Define wether the camera is intermediate.
  23287. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23288. */
  23289. _this.isIntermediate = false;
  23290. /**
  23291. * Define the viewport of the camera.
  23292. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23293. */
  23294. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23295. /**
  23296. * Restricts the camera to viewing objects with the same layerMask.
  23297. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23298. */
  23299. _this.layerMask = 0x0FFFFFFF;
  23300. /**
  23301. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23302. */
  23303. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23304. /**
  23305. * Rig mode of the camera.
  23306. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23307. * This is normally controlled byt the camera themselves as internal use.
  23308. */
  23309. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23310. /**
  23311. * Defines the list of custom render target the camera should render to.
  23312. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23313. * else in the scene.
  23314. */
  23315. _this.customRenderTargets = new Array();
  23316. /**
  23317. * Observable triggered when the camera view matrix has changed.
  23318. */
  23319. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23320. /**
  23321. * Observable triggered when the camera Projection matrix has changed.
  23322. */
  23323. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23324. /**
  23325. * Observable triggered when the inputs have been processed.
  23326. */
  23327. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23328. /**
  23329. * Observable triggered when reset has been called and applied to the camera.
  23330. */
  23331. _this.onRestoreStateObservable = new BABYLON.Observable();
  23332. /** @hidden */
  23333. _this._rigCameras = new Array();
  23334. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23335. /** @hidden */
  23336. _this._skipRendering = false;
  23337. /** @hidden */
  23338. _this._projectionMatrix = new BABYLON.Matrix();
  23339. /** @hidden */
  23340. _this._postProcesses = new Array();
  23341. /** @hidden */
  23342. _this._activeMeshes = new BABYLON.SmartArray(256);
  23343. _this._globalPosition = BABYLON.Vector3.Zero();
  23344. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23345. _this._doNotComputeProjectionMatrix = false;
  23346. _this._transformMatrix = BABYLON.Matrix.Zero();
  23347. _this._refreshFrustumPlanes = true;
  23348. _this.getScene().addCamera(_this);
  23349. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23350. _this.getScene().activeCamera = _this;
  23351. }
  23352. _this.position = position;
  23353. return _this;
  23354. }
  23355. /**
  23356. * Store current camera state (fov, position, etc..)
  23357. * @returns the camera
  23358. */
  23359. Camera.prototype.storeState = function () {
  23360. this._stateStored = true;
  23361. this._storedFov = this.fov;
  23362. return this;
  23363. };
  23364. /**
  23365. * Restores the camera state values if it has been stored. You must call storeState() first
  23366. */
  23367. Camera.prototype._restoreStateValues = function () {
  23368. if (!this._stateStored) {
  23369. return false;
  23370. }
  23371. this.fov = this._storedFov;
  23372. return true;
  23373. };
  23374. /**
  23375. * Restored camera state. You must call storeState() first.
  23376. * @returns true if restored and false otherwise
  23377. */
  23378. Camera.prototype.restoreState = function () {
  23379. if (this._restoreStateValues()) {
  23380. this.onRestoreStateObservable.notifyObservers(this);
  23381. return true;
  23382. }
  23383. return false;
  23384. };
  23385. /**
  23386. * Gets the class name of the camera.
  23387. * @returns the class name
  23388. */
  23389. Camera.prototype.getClassName = function () {
  23390. return "Camera";
  23391. };
  23392. /**
  23393. * Gets a string representation of the camera usefull for debug purpose.
  23394. * @param fullDetails Defines that a more verboe level of logging is required
  23395. * @returns the string representation
  23396. */
  23397. Camera.prototype.toString = function (fullDetails) {
  23398. var ret = "Name: " + this.name;
  23399. ret += ", type: " + this.getClassName();
  23400. if (this.animations) {
  23401. for (var i = 0; i < this.animations.length; i++) {
  23402. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23403. }
  23404. }
  23405. if (fullDetails) {
  23406. }
  23407. return ret;
  23408. };
  23409. Object.defineProperty(Camera.prototype, "globalPosition", {
  23410. /**
  23411. * Gets the current world space position of the camera.
  23412. */
  23413. get: function () {
  23414. return this._globalPosition;
  23415. },
  23416. enumerable: true,
  23417. configurable: true
  23418. });
  23419. /**
  23420. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23421. * @returns the active meshe list
  23422. */
  23423. Camera.prototype.getActiveMeshes = function () {
  23424. return this._activeMeshes;
  23425. };
  23426. /**
  23427. * Check wether a mesh is part of the current active mesh list of the camera
  23428. * @param mesh Defines the mesh to check
  23429. * @returns true if active, false otherwise
  23430. */
  23431. Camera.prototype.isActiveMesh = function (mesh) {
  23432. return (this._activeMeshes.indexOf(mesh) !== -1);
  23433. };
  23434. /**
  23435. * Is this camera ready to be used/rendered
  23436. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23437. * @return true if the camera is ready
  23438. */
  23439. Camera.prototype.isReady = function (completeCheck) {
  23440. if (completeCheck === void 0) { completeCheck = false; }
  23441. if (completeCheck) {
  23442. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23443. var pp = _a[_i];
  23444. if (pp && !pp.isReady()) {
  23445. return false;
  23446. }
  23447. }
  23448. }
  23449. return _super.prototype.isReady.call(this, completeCheck);
  23450. };
  23451. /** @hidden */
  23452. Camera.prototype._initCache = function () {
  23453. _super.prototype._initCache.call(this);
  23454. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23455. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23456. this._cache.mode = undefined;
  23457. this._cache.minZ = undefined;
  23458. this._cache.maxZ = undefined;
  23459. this._cache.fov = undefined;
  23460. this._cache.fovMode = undefined;
  23461. this._cache.aspectRatio = undefined;
  23462. this._cache.orthoLeft = undefined;
  23463. this._cache.orthoRight = undefined;
  23464. this._cache.orthoBottom = undefined;
  23465. this._cache.orthoTop = undefined;
  23466. this._cache.renderWidth = undefined;
  23467. this._cache.renderHeight = undefined;
  23468. };
  23469. /** @hidden */
  23470. Camera.prototype._updateCache = function (ignoreParentClass) {
  23471. if (!ignoreParentClass) {
  23472. _super.prototype._updateCache.call(this);
  23473. }
  23474. this._cache.position.copyFrom(this.position);
  23475. this._cache.upVector.copyFrom(this.upVector);
  23476. };
  23477. /** @hidden */
  23478. Camera.prototype._isSynchronized = function () {
  23479. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23480. };
  23481. /** @hidden */
  23482. Camera.prototype._isSynchronizedViewMatrix = function () {
  23483. if (!_super.prototype._isSynchronized.call(this)) {
  23484. return false;
  23485. }
  23486. return this._cache.position.equals(this.position)
  23487. && this._cache.upVector.equals(this.upVector)
  23488. && this.isSynchronizedWithParent();
  23489. };
  23490. /** @hidden */
  23491. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23492. var check = this._cache.mode === this.mode
  23493. && this._cache.minZ === this.minZ
  23494. && this._cache.maxZ === this.maxZ;
  23495. if (!check) {
  23496. return false;
  23497. }
  23498. var engine = this.getEngine();
  23499. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23500. check = this._cache.fov === this.fov
  23501. && this._cache.fovMode === this.fovMode
  23502. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23503. }
  23504. else {
  23505. check = this._cache.orthoLeft === this.orthoLeft
  23506. && this._cache.orthoRight === this.orthoRight
  23507. && this._cache.orthoBottom === this.orthoBottom
  23508. && this._cache.orthoTop === this.orthoTop
  23509. && this._cache.renderWidth === engine.getRenderWidth()
  23510. && this._cache.renderHeight === engine.getRenderHeight();
  23511. }
  23512. return check;
  23513. };
  23514. /**
  23515. * Attach the input controls to a specific dom element to get the input from.
  23516. * @param element Defines the element the controls should be listened from
  23517. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23518. */
  23519. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23520. };
  23521. /**
  23522. * Detach the current controls from the specified dom element.
  23523. * @param element Defines the element to stop listening the inputs from
  23524. */
  23525. Camera.prototype.detachControl = function (element) {
  23526. };
  23527. /**
  23528. * Update the camera state according to the different inputs gathered during the frame.
  23529. */
  23530. Camera.prototype.update = function () {
  23531. this._checkInputs();
  23532. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23533. this._updateRigCameras();
  23534. }
  23535. };
  23536. /** @hidden */
  23537. Camera.prototype._checkInputs = function () {
  23538. this.onAfterCheckInputsObservable.notifyObservers(this);
  23539. };
  23540. Object.defineProperty(Camera.prototype, "rigCameras", {
  23541. /** @hidden */
  23542. get: function () {
  23543. return this._rigCameras;
  23544. },
  23545. enumerable: true,
  23546. configurable: true
  23547. });
  23548. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23549. /**
  23550. * Gets the post process used by the rig cameras
  23551. */
  23552. get: function () {
  23553. return this._rigPostProcess;
  23554. },
  23555. enumerable: true,
  23556. configurable: true
  23557. });
  23558. /**
  23559. * Internal, gets the first post proces.
  23560. * @returns the first post process to be run on this camera.
  23561. */
  23562. Camera.prototype._getFirstPostProcess = function () {
  23563. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23564. if (this._postProcesses[ppIndex] !== null) {
  23565. return this._postProcesses[ppIndex];
  23566. }
  23567. }
  23568. return null;
  23569. };
  23570. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23571. // invalidate framebuffer
  23572. var firstPostProcess = this._getFirstPostProcess();
  23573. if (firstPostProcess) {
  23574. firstPostProcess.markTextureDirty();
  23575. }
  23576. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23577. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23578. var cam = this._rigCameras[i];
  23579. var rigPostProcess = cam._rigPostProcess;
  23580. // for VR rig, there does not have to be a post process
  23581. if (rigPostProcess) {
  23582. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23583. if (isPass) {
  23584. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23585. cam.isIntermediate = this._postProcesses.length === 0;
  23586. }
  23587. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23588. rigPostProcess.markTextureDirty();
  23589. }
  23590. else {
  23591. cam._postProcesses = this._postProcesses.slice(0);
  23592. }
  23593. }
  23594. };
  23595. /**
  23596. * Attach a post process to the camera.
  23597. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23598. * @param postProcess The post process to attach to the camera
  23599. * @param insertAt The position of the post process in case several of them are in use in the scene
  23600. * @returns the position the post process has been inserted at
  23601. */
  23602. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23603. if (insertAt === void 0) { insertAt = null; }
  23604. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23605. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23606. return 0;
  23607. }
  23608. if (insertAt == null || insertAt < 0) {
  23609. this._postProcesses.push(postProcess);
  23610. }
  23611. else if (this._postProcesses[insertAt] === null) {
  23612. this._postProcesses[insertAt] = postProcess;
  23613. }
  23614. else {
  23615. this._postProcesses.splice(insertAt, 0, postProcess);
  23616. }
  23617. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23618. return this._postProcesses.indexOf(postProcess);
  23619. };
  23620. /**
  23621. * Detach a post process to the camera.
  23622. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23623. * @param postProcess The post process to detach from the camera
  23624. */
  23625. Camera.prototype.detachPostProcess = function (postProcess) {
  23626. var idx = this._postProcesses.indexOf(postProcess);
  23627. if (idx !== -1) {
  23628. this._postProcesses[idx] = null;
  23629. }
  23630. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23631. };
  23632. /**
  23633. * Gets the current world matrix of the camera
  23634. */
  23635. Camera.prototype.getWorldMatrix = function () {
  23636. if (this._isSynchronizedViewMatrix()) {
  23637. return this._worldMatrix;
  23638. }
  23639. // Getting the the view matrix will also compute the world matrix.
  23640. this.getViewMatrix();
  23641. return this._worldMatrix;
  23642. };
  23643. /** @hidden */
  23644. Camera.prototype._getViewMatrix = function () {
  23645. return BABYLON.Matrix.Identity();
  23646. };
  23647. /**
  23648. * Gets the current view matrix of the camera.
  23649. * @param force forces the camera to recompute the matrix without looking at the cached state
  23650. * @returns the view matrix
  23651. */
  23652. Camera.prototype.getViewMatrix = function (force) {
  23653. if (!force && this._isSynchronizedViewMatrix()) {
  23654. return this._computedViewMatrix;
  23655. }
  23656. this.updateCache();
  23657. this._computedViewMatrix = this._getViewMatrix();
  23658. this._currentRenderId = this.getScene().getRenderId();
  23659. this._childRenderId = this._currentRenderId;
  23660. this._refreshFrustumPlanes = true;
  23661. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23662. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23663. }
  23664. this.onViewMatrixChangedObservable.notifyObservers(this);
  23665. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23666. return this._computedViewMatrix;
  23667. };
  23668. /**
  23669. * Freeze the projection matrix.
  23670. * It will prevent the cache check of the camera projection compute and can speed up perf
  23671. * if no parameter of the camera are meant to change
  23672. * @param projection Defines manually a projection if necessary
  23673. */
  23674. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23675. this._doNotComputeProjectionMatrix = true;
  23676. if (projection !== undefined) {
  23677. this._projectionMatrix = projection;
  23678. }
  23679. };
  23680. /**
  23681. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23682. */
  23683. Camera.prototype.unfreezeProjectionMatrix = function () {
  23684. this._doNotComputeProjectionMatrix = false;
  23685. };
  23686. /**
  23687. * Gets the current projection matrix of the camera.
  23688. * @param force forces the camera to recompute the matrix without looking at the cached state
  23689. * @returns the projection matrix
  23690. */
  23691. Camera.prototype.getProjectionMatrix = function (force) {
  23692. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23693. return this._projectionMatrix;
  23694. }
  23695. // Cache
  23696. this._cache.mode = this.mode;
  23697. this._cache.minZ = this.minZ;
  23698. this._cache.maxZ = this.maxZ;
  23699. // Matrix
  23700. this._refreshFrustumPlanes = true;
  23701. var engine = this.getEngine();
  23702. var scene = this.getScene();
  23703. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23704. this._cache.fov = this.fov;
  23705. this._cache.fovMode = this.fovMode;
  23706. this._cache.aspectRatio = engine.getAspectRatio(this);
  23707. if (this.minZ <= 0) {
  23708. this.minZ = 0.1;
  23709. }
  23710. if (scene.useRightHandedSystem) {
  23711. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23712. }
  23713. else {
  23714. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23715. }
  23716. }
  23717. else {
  23718. var halfWidth = engine.getRenderWidth() / 2.0;
  23719. var halfHeight = engine.getRenderHeight() / 2.0;
  23720. if (scene.useRightHandedSystem) {
  23721. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23722. }
  23723. else {
  23724. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23725. }
  23726. this._cache.orthoLeft = this.orthoLeft;
  23727. this._cache.orthoRight = this.orthoRight;
  23728. this._cache.orthoBottom = this.orthoBottom;
  23729. this._cache.orthoTop = this.orthoTop;
  23730. this._cache.renderWidth = engine.getRenderWidth();
  23731. this._cache.renderHeight = engine.getRenderHeight();
  23732. }
  23733. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23734. return this._projectionMatrix;
  23735. };
  23736. /**
  23737. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23738. * @returns a Matrix
  23739. */
  23740. Camera.prototype.getTransformationMatrix = function () {
  23741. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23742. return this._transformMatrix;
  23743. };
  23744. Camera.prototype._updateFrustumPlanes = function () {
  23745. if (!this._refreshFrustumPlanes) {
  23746. return;
  23747. }
  23748. this.getTransformationMatrix();
  23749. if (!this._frustumPlanes) {
  23750. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23751. }
  23752. else {
  23753. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23754. }
  23755. this._refreshFrustumPlanes = false;
  23756. };
  23757. /**
  23758. * Checks if a cullable object (mesh...) is in the camera frustum
  23759. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23760. * @param target The object to check
  23761. * @returns true if the object is in frustum otherwise false
  23762. */
  23763. Camera.prototype.isInFrustum = function (target) {
  23764. this._updateFrustumPlanes();
  23765. return target.isInFrustum(this._frustumPlanes);
  23766. };
  23767. /**
  23768. * Checks if a cullable object (mesh...) is in the camera frustum
  23769. * Unlike isInFrustum this cheks the full bounding box
  23770. * @param target The object to check
  23771. * @returns true if the object is in frustum otherwise false
  23772. */
  23773. Camera.prototype.isCompletelyInFrustum = function (target) {
  23774. this._updateFrustumPlanes();
  23775. return target.isCompletelyInFrustum(this._frustumPlanes);
  23776. };
  23777. /**
  23778. * Gets a ray in the forward direction from the camera.
  23779. * @param length Defines the length of the ray to create
  23780. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23781. * @param origin Defines the start point of the ray which defaults to the camera position
  23782. * @returns the forward ray
  23783. */
  23784. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23785. if (length === void 0) { length = 100; }
  23786. if (!transform) {
  23787. transform = this.getWorldMatrix();
  23788. }
  23789. if (!origin) {
  23790. origin = this.position;
  23791. }
  23792. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23793. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23794. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23795. return new BABYLON.Ray(origin, direction, length);
  23796. };
  23797. /**
  23798. * Releases resources associated with this node.
  23799. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23800. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23801. */
  23802. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23803. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23804. // Observables
  23805. this.onViewMatrixChangedObservable.clear();
  23806. this.onProjectionMatrixChangedObservable.clear();
  23807. this.onAfterCheckInputsObservable.clear();
  23808. this.onRestoreStateObservable.clear();
  23809. // Inputs
  23810. if (this.inputs) {
  23811. this.inputs.clear();
  23812. }
  23813. // Animations
  23814. this.getScene().stopAnimation(this);
  23815. // Remove from scene
  23816. this.getScene().removeCamera(this);
  23817. while (this._rigCameras.length > 0) {
  23818. var camera = this._rigCameras.pop();
  23819. if (camera) {
  23820. camera.dispose();
  23821. }
  23822. }
  23823. // Postprocesses
  23824. if (this._rigPostProcess) {
  23825. this._rigPostProcess.dispose(this);
  23826. this._rigPostProcess = null;
  23827. this._postProcesses = [];
  23828. }
  23829. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23830. this._rigPostProcess = null;
  23831. this._postProcesses = [];
  23832. }
  23833. else {
  23834. var i = this._postProcesses.length;
  23835. while (--i >= 0) {
  23836. var postProcess = this._postProcesses[i];
  23837. if (postProcess) {
  23838. postProcess.dispose(this);
  23839. }
  23840. }
  23841. }
  23842. // Render targets
  23843. var i = this.customRenderTargets.length;
  23844. while (--i >= 0) {
  23845. this.customRenderTargets[i].dispose();
  23846. }
  23847. this.customRenderTargets = [];
  23848. // Active Meshes
  23849. this._activeMeshes.dispose();
  23850. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23851. };
  23852. Object.defineProperty(Camera.prototype, "leftCamera", {
  23853. /**
  23854. * Gets the left camera of a rig setup in case of Rigged Camera
  23855. */
  23856. get: function () {
  23857. if (this._rigCameras.length < 1) {
  23858. return null;
  23859. }
  23860. return this._rigCameras[0];
  23861. },
  23862. enumerable: true,
  23863. configurable: true
  23864. });
  23865. Object.defineProperty(Camera.prototype, "rightCamera", {
  23866. /**
  23867. * Gets the right camera of a rig setup in case of Rigged Camera
  23868. */
  23869. get: function () {
  23870. if (this._rigCameras.length < 2) {
  23871. return null;
  23872. }
  23873. return this._rigCameras[1];
  23874. },
  23875. enumerable: true,
  23876. configurable: true
  23877. });
  23878. /**
  23879. * Gets the left camera target of a rig setup in case of Rigged Camera
  23880. * @returns the target position
  23881. */
  23882. Camera.prototype.getLeftTarget = function () {
  23883. if (this._rigCameras.length < 1) {
  23884. return null;
  23885. }
  23886. return this._rigCameras[0].getTarget();
  23887. };
  23888. /**
  23889. * Gets the right camera target of a rig setup in case of Rigged Camera
  23890. * @returns the target position
  23891. */
  23892. Camera.prototype.getRightTarget = function () {
  23893. if (this._rigCameras.length < 2) {
  23894. return null;
  23895. }
  23896. return this._rigCameras[1].getTarget();
  23897. };
  23898. /**
  23899. * @hidden
  23900. */
  23901. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23902. if (this.cameraRigMode === mode) {
  23903. return;
  23904. }
  23905. while (this._rigCameras.length > 0) {
  23906. var camera = this._rigCameras.pop();
  23907. if (camera) {
  23908. camera.dispose();
  23909. }
  23910. }
  23911. this.cameraRigMode = mode;
  23912. this._cameraRigParams = {};
  23913. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23914. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23915. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23916. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23917. // create the rig cameras, unless none
  23918. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23919. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23920. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23921. if (leftCamera && rightCamera) {
  23922. this._rigCameras.push(leftCamera);
  23923. this._rigCameras.push(rightCamera);
  23924. }
  23925. }
  23926. switch (this.cameraRigMode) {
  23927. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23928. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23929. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23930. break;
  23931. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23932. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23933. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23934. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23935. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23936. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23937. break;
  23938. case Camera.RIG_MODE_VR:
  23939. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23940. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23941. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23942. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23943. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23944. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23945. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23946. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23947. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23948. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23949. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23950. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23951. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23952. if (metrics.compensateDistortion) {
  23953. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23954. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23955. }
  23956. break;
  23957. case Camera.RIG_MODE_WEBVR:
  23958. if (rigParams.vrDisplay) {
  23959. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23960. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23961. //Left eye
  23962. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23963. this._rigCameras[0].setCameraRigParameter("left", true);
  23964. //leaving this for future reference
  23965. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23966. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23967. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23968. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23969. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23970. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23971. this._rigCameras[0].parent = this;
  23972. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23973. //Right eye
  23974. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23975. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23976. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23977. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23978. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23979. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23980. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23981. this._rigCameras[1].parent = this;
  23982. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23983. if (Camera.UseAlternateWebVRRendering) {
  23984. this._rigCameras[1]._skipRendering = true;
  23985. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23986. }
  23987. }
  23988. break;
  23989. }
  23990. this._cascadePostProcessesToRigCams();
  23991. this.update();
  23992. };
  23993. Camera.prototype._getVRProjectionMatrix = function () {
  23994. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23995. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23996. return this._projectionMatrix;
  23997. };
  23998. Camera.prototype._updateCameraRotationMatrix = function () {
  23999. //Here for WebVR
  24000. };
  24001. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24002. //Here for WebVR
  24003. };
  24004. /**
  24005. * This function MUST be overwritten by the different WebVR cameras available.
  24006. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24007. */
  24008. Camera.prototype._getWebVRProjectionMatrix = function () {
  24009. return BABYLON.Matrix.Identity();
  24010. };
  24011. /**
  24012. * This function MUST be overwritten by the different WebVR cameras available.
  24013. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24014. */
  24015. Camera.prototype._getWebVRViewMatrix = function () {
  24016. return BABYLON.Matrix.Identity();
  24017. };
  24018. /** @hidden */
  24019. Camera.prototype.setCameraRigParameter = function (name, value) {
  24020. if (!this._cameraRigParams) {
  24021. this._cameraRigParams = {};
  24022. }
  24023. this._cameraRigParams[name] = value;
  24024. //provisionnally:
  24025. if (name === "interaxialDistance") {
  24026. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24027. }
  24028. };
  24029. /**
  24030. * needs to be overridden by children so sub has required properties to be copied
  24031. * @hidden
  24032. */
  24033. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24034. return null;
  24035. };
  24036. /**
  24037. * May need to be overridden by children
  24038. * @hidden
  24039. */
  24040. Camera.prototype._updateRigCameras = function () {
  24041. for (var i = 0; i < this._rigCameras.length; i++) {
  24042. this._rigCameras[i].minZ = this.minZ;
  24043. this._rigCameras[i].maxZ = this.maxZ;
  24044. this._rigCameras[i].fov = this.fov;
  24045. }
  24046. // only update viewport when ANAGLYPH
  24047. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24048. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24049. }
  24050. };
  24051. /** @hidden */
  24052. Camera.prototype._setupInputs = function () {
  24053. };
  24054. /**
  24055. * Serialiaze the camera setup to a json represention
  24056. * @returns the JSON representation
  24057. */
  24058. Camera.prototype.serialize = function () {
  24059. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24060. // Type
  24061. serializationObject.type = this.getClassName();
  24062. // Parent
  24063. if (this.parent) {
  24064. serializationObject.parentId = this.parent.id;
  24065. }
  24066. if (this.inputs) {
  24067. this.inputs.serialize(serializationObject);
  24068. }
  24069. // Animations
  24070. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24071. serializationObject.ranges = this.serializeAnimationRanges();
  24072. return serializationObject;
  24073. };
  24074. /**
  24075. * Clones the current camera.
  24076. * @param name The cloned camera name
  24077. * @returns the cloned camera
  24078. */
  24079. Camera.prototype.clone = function (name) {
  24080. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24081. };
  24082. /**
  24083. * Gets the direction of the camera relative to a given local axis.
  24084. * @param localAxis Defines the reference axis to provide a relative direction.
  24085. * @return the direction
  24086. */
  24087. Camera.prototype.getDirection = function (localAxis) {
  24088. var result = BABYLON.Vector3.Zero();
  24089. this.getDirectionToRef(localAxis, result);
  24090. return result;
  24091. };
  24092. /**
  24093. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24094. * @param localAxis Defines the reference axis to provide a relative direction.
  24095. * @param result Defines the vector to store the result in
  24096. */
  24097. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24098. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24099. };
  24100. /**
  24101. * Gets a camera constructor for a given camera type
  24102. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24103. * @param name The name of the camera the result will be able to instantiate
  24104. * @param scene The scene the result will construct the camera in
  24105. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24106. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24107. * @returns a factory method to construc the camera
  24108. */
  24109. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24110. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24111. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24112. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24113. interaxial_distance: interaxial_distance,
  24114. isStereoscopicSideBySide: isStereoscopicSideBySide
  24115. });
  24116. if (constructorFunc) {
  24117. return constructorFunc;
  24118. }
  24119. // Default to universal camera
  24120. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24121. };
  24122. /**
  24123. * Compute the world matrix of the camera.
  24124. * @returns the camera workd matrix
  24125. */
  24126. Camera.prototype.computeWorldMatrix = function () {
  24127. return this.getWorldMatrix();
  24128. };
  24129. /**
  24130. * Parse a JSON and creates the camera from the parsed information
  24131. * @param parsedCamera The JSON to parse
  24132. * @param scene The scene to instantiate the camera in
  24133. * @returns the newly constructed camera
  24134. */
  24135. Camera.Parse = function (parsedCamera, scene) {
  24136. var type = parsedCamera.type;
  24137. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24138. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24139. // Parent
  24140. if (parsedCamera.parentId) {
  24141. camera._waitingParentId = parsedCamera.parentId;
  24142. }
  24143. //If camera has an input manager, let it parse inputs settings
  24144. if (camera.inputs) {
  24145. camera.inputs.parse(parsedCamera);
  24146. camera._setupInputs();
  24147. }
  24148. if (camera.setPosition) { // need to force position
  24149. camera.position.copyFromFloats(0, 0, 0);
  24150. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24151. }
  24152. // Target
  24153. if (parsedCamera.target) {
  24154. if (camera.setTarget) {
  24155. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24156. }
  24157. }
  24158. // Apply 3d rig, when found
  24159. if (parsedCamera.cameraRigMode) {
  24160. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24161. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24162. }
  24163. // Animations
  24164. if (parsedCamera.animations) {
  24165. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24166. var parsedAnimation = parsedCamera.animations[animationIndex];
  24167. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24168. }
  24169. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24170. }
  24171. if (parsedCamera.autoAnimate) {
  24172. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24173. }
  24174. return camera;
  24175. };
  24176. /**
  24177. * This is the default projection mode used by the cameras.
  24178. * It helps recreating a feeling of perspective and better appreciate depth.
  24179. * This is the best way to simulate real life cameras.
  24180. */
  24181. Camera.PERSPECTIVE_CAMERA = 0;
  24182. /**
  24183. * This helps creating camera with an orthographic mode.
  24184. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  24185. */
  24186. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24187. /**
  24188. * This is the default FOV mode for perspective cameras.
  24189. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24190. */
  24191. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24192. /**
  24193. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24194. */
  24195. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24196. /**
  24197. * This specifies ther is no need for a camera rig.
  24198. * Basically only one eye is rendered corresponding to the camera.
  24199. */
  24200. Camera.RIG_MODE_NONE = 0;
  24201. /**
  24202. * Simulates a camera Rig with one blue eye and one red eye.
  24203. * This can be use with 3d blue and red glasses.
  24204. */
  24205. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24206. /**
  24207. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24208. */
  24209. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24210. /**
  24211. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24212. */
  24213. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24214. /**
  24215. * Defines that both eyes of the camera will be rendered over under each other.
  24216. */
  24217. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24218. /**
  24219. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24220. */
  24221. Camera.RIG_MODE_VR = 20;
  24222. /**
  24223. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24224. */
  24225. Camera.RIG_MODE_WEBVR = 21;
  24226. /**
  24227. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24228. */
  24229. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24230. /**
  24231. * @hidden
  24232. * Might be removed once multiview will be a thing
  24233. */
  24234. Camera.UseAlternateWebVRRendering = false;
  24235. __decorate([
  24236. BABYLON.serializeAsVector3()
  24237. ], Camera.prototype, "position", void 0);
  24238. __decorate([
  24239. BABYLON.serializeAsVector3()
  24240. ], Camera.prototype, "upVector", void 0);
  24241. __decorate([
  24242. BABYLON.serialize()
  24243. ], Camera.prototype, "orthoLeft", void 0);
  24244. __decorate([
  24245. BABYLON.serialize()
  24246. ], Camera.prototype, "orthoRight", void 0);
  24247. __decorate([
  24248. BABYLON.serialize()
  24249. ], Camera.prototype, "orthoBottom", void 0);
  24250. __decorate([
  24251. BABYLON.serialize()
  24252. ], Camera.prototype, "orthoTop", void 0);
  24253. __decorate([
  24254. BABYLON.serialize()
  24255. ], Camera.prototype, "fov", void 0);
  24256. __decorate([
  24257. BABYLON.serialize()
  24258. ], Camera.prototype, "minZ", void 0);
  24259. __decorate([
  24260. BABYLON.serialize()
  24261. ], Camera.prototype, "maxZ", void 0);
  24262. __decorate([
  24263. BABYLON.serialize()
  24264. ], Camera.prototype, "inertia", void 0);
  24265. __decorate([
  24266. BABYLON.serialize()
  24267. ], Camera.prototype, "mode", void 0);
  24268. __decorate([
  24269. BABYLON.serialize()
  24270. ], Camera.prototype, "layerMask", void 0);
  24271. __decorate([
  24272. BABYLON.serialize()
  24273. ], Camera.prototype, "fovMode", void 0);
  24274. __decorate([
  24275. BABYLON.serialize()
  24276. ], Camera.prototype, "cameraRigMode", void 0);
  24277. __decorate([
  24278. BABYLON.serialize()
  24279. ], Camera.prototype, "interaxialDistance", void 0);
  24280. __decorate([
  24281. BABYLON.serialize()
  24282. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24283. return Camera;
  24284. }(BABYLON.Node));
  24285. BABYLON.Camera = Camera;
  24286. })(BABYLON || (BABYLON = {}));
  24287. //# sourceMappingURL=babylon.camera.js.map
  24288. var BABYLON;
  24289. (function (BABYLON) {
  24290. /**
  24291. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24292. * It is enable to manage the different groups as well as the different necessary sort functions.
  24293. * This should not be used directly aside of the few static configurations
  24294. */
  24295. var RenderingManager = /** @class */ (function () {
  24296. /**
  24297. * Instantiates a new rendering group for a particular scene
  24298. * @param scene Defines the scene the groups belongs to
  24299. */
  24300. function RenderingManager(scene) {
  24301. /**
  24302. * @hidden
  24303. */
  24304. this._useSceneAutoClearSetup = false;
  24305. this._renderingGroups = new Array();
  24306. this._autoClearDepthStencil = {};
  24307. this._customOpaqueSortCompareFn = {};
  24308. this._customAlphaTestSortCompareFn = {};
  24309. this._customTransparentSortCompareFn = {};
  24310. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24311. this._scene = scene;
  24312. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24313. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24314. }
  24315. }
  24316. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24317. if (depth === void 0) { depth = true; }
  24318. if (stencil === void 0) { stencil = true; }
  24319. if (this._depthStencilBufferAlreadyCleaned) {
  24320. return;
  24321. }
  24322. this._scene.getEngine().clear(null, false, depth, stencil);
  24323. this._depthStencilBufferAlreadyCleaned = true;
  24324. };
  24325. /**
  24326. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24327. * @hidden
  24328. */
  24329. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24330. // Update the observable context (not null as it only goes away on dispose)
  24331. var info = this._renderingGroupInfo;
  24332. info.scene = this._scene;
  24333. info.camera = this._scene.activeCamera;
  24334. // Dispatch sprites
  24335. if (this._scene.spriteManagers && renderSprites) {
  24336. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24337. var manager = this._scene.spriteManagers[index];
  24338. this.dispatchSprites(manager);
  24339. }
  24340. }
  24341. // Render
  24342. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24343. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24344. var renderingGroup = this._renderingGroups[index];
  24345. if (!renderingGroup) {
  24346. continue;
  24347. }
  24348. var renderingGroupMask = Math.pow(2, index);
  24349. info.renderingGroupId = index;
  24350. // Before Observable
  24351. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24352. // Clear depth/stencil if needed
  24353. if (RenderingManager.AUTOCLEAR) {
  24354. var autoClear = this._useSceneAutoClearSetup ?
  24355. this._scene.getAutoClearDepthStencilSetup(index) :
  24356. this._autoClearDepthStencil[index];
  24357. if (autoClear && autoClear.autoClear) {
  24358. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24359. }
  24360. }
  24361. // Render
  24362. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24363. var step = _a[_i];
  24364. step.action(index);
  24365. }
  24366. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24367. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24368. var step = _c[_b];
  24369. step.action(index);
  24370. }
  24371. // After Observable
  24372. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24373. }
  24374. };
  24375. /**
  24376. * Resets the different information of the group to prepare a new frame
  24377. * @hidden
  24378. */
  24379. RenderingManager.prototype.reset = function () {
  24380. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24381. var renderingGroup = this._renderingGroups[index];
  24382. if (renderingGroup) {
  24383. renderingGroup.prepare();
  24384. }
  24385. }
  24386. };
  24387. /**
  24388. * Dispose and release the group and its associated resources.
  24389. * @hidden
  24390. */
  24391. RenderingManager.prototype.dispose = function () {
  24392. this.freeRenderingGroups();
  24393. this._renderingGroups.length = 0;
  24394. this._renderingGroupInfo = null;
  24395. };
  24396. /**
  24397. * Clear the info related to rendering groups preventing retention points during dispose.
  24398. */
  24399. RenderingManager.prototype.freeRenderingGroups = function () {
  24400. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24401. var renderingGroup = this._renderingGroups[index];
  24402. if (renderingGroup) {
  24403. renderingGroup.dispose();
  24404. }
  24405. }
  24406. };
  24407. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24408. if (this._renderingGroups[renderingGroupId] === undefined) {
  24409. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24410. }
  24411. };
  24412. /**
  24413. * Add a sprite manager to the rendering manager in order to render it this frame.
  24414. * @param spriteManager Define the sprite manager to render
  24415. */
  24416. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24417. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24418. this._prepareRenderingGroup(renderingGroupId);
  24419. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24420. };
  24421. /**
  24422. * Add a particle system to the rendering manager in order to render it this frame.
  24423. * @param particleSystem Define the particle system to render
  24424. */
  24425. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24426. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24427. this._prepareRenderingGroup(renderingGroupId);
  24428. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24429. };
  24430. /**
  24431. * Add a submesh to the manager in order to render it this frame
  24432. * @param subMesh The submesh to dispatch
  24433. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24434. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24435. */
  24436. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24437. if (mesh === undefined) {
  24438. mesh = subMesh.getMesh();
  24439. }
  24440. var renderingGroupId = mesh.renderingGroupId || 0;
  24441. this._prepareRenderingGroup(renderingGroupId);
  24442. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24443. };
  24444. /**
  24445. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24446. * This allowed control for front to back rendering or reversly depending of the special needs.
  24447. *
  24448. * @param renderingGroupId The rendering group id corresponding to its index
  24449. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24450. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24451. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24452. */
  24453. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24454. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24455. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24456. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24457. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24458. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24459. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24460. if (this._renderingGroups[renderingGroupId]) {
  24461. var group = this._renderingGroups[renderingGroupId];
  24462. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24463. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24464. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24465. }
  24466. };
  24467. /**
  24468. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24469. *
  24470. * @param renderingGroupId The rendering group id corresponding to its index
  24471. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24472. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24473. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24474. */
  24475. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24476. if (depth === void 0) { depth = true; }
  24477. if (stencil === void 0) { stencil = true; }
  24478. this._autoClearDepthStencil[renderingGroupId] = {
  24479. autoClear: autoClearDepthStencil,
  24480. depth: depth,
  24481. stencil: stencil
  24482. };
  24483. };
  24484. /**
  24485. * Gets the current auto clear configuration for one rendering group of the rendering
  24486. * manager.
  24487. * @param index the rendering group index to get the information for
  24488. * @returns The auto clear setup for the requested rendering group
  24489. */
  24490. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24491. return this._autoClearDepthStencil[index];
  24492. };
  24493. /**
  24494. * The max id used for rendering groups (not included)
  24495. */
  24496. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24497. /**
  24498. * The min id used for rendering groups (included)
  24499. */
  24500. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24501. /**
  24502. * Used to globally prevent autoclearing scenes.
  24503. */
  24504. RenderingManager.AUTOCLEAR = true;
  24505. return RenderingManager;
  24506. }());
  24507. BABYLON.RenderingManager = RenderingManager;
  24508. })(BABYLON || (BABYLON = {}));
  24509. //# sourceMappingURL=babylon.renderingManager.js.map
  24510. var BABYLON;
  24511. (function (BABYLON) {
  24512. /**
  24513. * This represents the object necessary to create a rendering group.
  24514. * This is exclusively used and created by the rendering manager.
  24515. * To modify the behavior, you use the available helpers in your scene or meshes.
  24516. * @hidden
  24517. */
  24518. var RenderingGroup = /** @class */ (function () {
  24519. /**
  24520. * Creates a new rendering group.
  24521. * @param index The rendering group index
  24522. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24523. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24524. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24525. */
  24526. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24527. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24528. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24529. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24530. this.index = index;
  24531. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24532. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24533. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24534. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24535. this._particleSystems = new BABYLON.SmartArray(256);
  24536. this._spriteManagers = new BABYLON.SmartArray(256);
  24537. this._edgesRenderers = new BABYLON.SmartArray(16);
  24538. this._scene = scene;
  24539. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24540. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24541. this.transparentSortCompareFn = transparentSortCompareFn;
  24542. }
  24543. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24544. /**
  24545. * Set the opaque sort comparison function.
  24546. * If null the sub meshes will be render in the order they were created
  24547. */
  24548. set: function (value) {
  24549. this._opaqueSortCompareFn = value;
  24550. if (value) {
  24551. this._renderOpaque = this.renderOpaqueSorted;
  24552. }
  24553. else {
  24554. this._renderOpaque = RenderingGroup.renderUnsorted;
  24555. }
  24556. },
  24557. enumerable: true,
  24558. configurable: true
  24559. });
  24560. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24561. /**
  24562. * Set the alpha test sort comparison function.
  24563. * If null the sub meshes will be render in the order they were created
  24564. */
  24565. set: function (value) {
  24566. this._alphaTestSortCompareFn = value;
  24567. if (value) {
  24568. this._renderAlphaTest = this.renderAlphaTestSorted;
  24569. }
  24570. else {
  24571. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24572. }
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24578. /**
  24579. * Set the transparent sort comparison function.
  24580. * If null the sub meshes will be render in the order they were created
  24581. */
  24582. set: function (value) {
  24583. if (value) {
  24584. this._transparentSortCompareFn = value;
  24585. }
  24586. else {
  24587. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24588. }
  24589. this._renderTransparent = this.renderTransparentSorted;
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. /**
  24595. * Render all the sub meshes contained in the group.
  24596. * @param customRenderFunction Used to override the default render behaviour of the group.
  24597. * @returns true if rendered some submeshes.
  24598. */
  24599. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24600. if (customRenderFunction) {
  24601. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24602. return;
  24603. }
  24604. var engine = this._scene.getEngine();
  24605. // Depth only
  24606. if (this._depthOnlySubMeshes.length !== 0) {
  24607. engine.setColorWrite(false);
  24608. this._renderAlphaTest(this._depthOnlySubMeshes);
  24609. engine.setColorWrite(true);
  24610. }
  24611. // Opaque
  24612. if (this._opaqueSubMeshes.length !== 0) {
  24613. this._renderOpaque(this._opaqueSubMeshes);
  24614. }
  24615. // Alpha test
  24616. if (this._alphaTestSubMeshes.length !== 0) {
  24617. this._renderAlphaTest(this._alphaTestSubMeshes);
  24618. }
  24619. var stencilState = engine.getStencilBuffer();
  24620. engine.setStencilBuffer(false);
  24621. // Sprites
  24622. if (renderSprites) {
  24623. this._renderSprites();
  24624. }
  24625. // Particles
  24626. if (renderParticles) {
  24627. this._renderParticles(activeMeshes);
  24628. }
  24629. if (this.onBeforeTransparentRendering) {
  24630. this.onBeforeTransparentRendering();
  24631. }
  24632. // Transparent
  24633. if (this._transparentSubMeshes.length !== 0) {
  24634. this._renderTransparent(this._transparentSubMeshes);
  24635. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24636. }
  24637. // Set back stencil to false in case it changes before the edge renderer.
  24638. engine.setStencilBuffer(false);
  24639. // Edges
  24640. if (this._edgesRenderers.length) {
  24641. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24642. this._edgesRenderers.data[edgesRendererIndex].render();
  24643. }
  24644. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24645. }
  24646. // Restore Stencil state.
  24647. engine.setStencilBuffer(stencilState);
  24648. };
  24649. /**
  24650. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24651. * @param subMeshes The submeshes to render
  24652. */
  24653. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24654. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24655. };
  24656. /**
  24657. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24658. * @param subMeshes The submeshes to render
  24659. */
  24660. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24661. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24662. };
  24663. /**
  24664. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24665. * @param subMeshes The submeshes to render
  24666. */
  24667. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24668. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24669. };
  24670. /**
  24671. * Renders the submeshes in a specified order.
  24672. * @param subMeshes The submeshes to sort before render
  24673. * @param sortCompareFn The comparison function use to sort
  24674. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24675. * @param transparent Specifies to activate blending if true
  24676. */
  24677. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24678. var subIndex = 0;
  24679. var subMesh;
  24680. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24681. for (; subIndex < subMeshes.length; subIndex++) {
  24682. subMesh = subMeshes.data[subIndex];
  24683. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24684. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24685. }
  24686. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24687. if (sortCompareFn) {
  24688. sortedArray.sort(sortCompareFn);
  24689. }
  24690. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24691. subMesh = sortedArray[subIndex];
  24692. if (transparent) {
  24693. var material = subMesh.getMaterial();
  24694. if (material && material.needDepthPrePass) {
  24695. var engine = material.getScene().getEngine();
  24696. engine.setColorWrite(false);
  24697. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24698. subMesh.render(false);
  24699. engine.setColorWrite(true);
  24700. }
  24701. }
  24702. subMesh.render(transparent);
  24703. }
  24704. };
  24705. /**
  24706. * Renders the submeshes in the order they were dispatched (no sort applied).
  24707. * @param subMeshes The submeshes to render
  24708. */
  24709. RenderingGroup.renderUnsorted = function (subMeshes) {
  24710. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24711. var submesh = subMeshes.data[subIndex];
  24712. submesh.render(false);
  24713. }
  24714. };
  24715. /**
  24716. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24717. * are rendered back to front if in the same alpha index.
  24718. *
  24719. * @param a The first submesh
  24720. * @param b The second submesh
  24721. * @returns The result of the comparison
  24722. */
  24723. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24724. // Alpha index first
  24725. if (a._alphaIndex > b._alphaIndex) {
  24726. return 1;
  24727. }
  24728. if (a._alphaIndex < b._alphaIndex) {
  24729. return -1;
  24730. }
  24731. // Then distance to camera
  24732. return RenderingGroup.backToFrontSortCompare(a, b);
  24733. };
  24734. /**
  24735. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24736. * are rendered back to front.
  24737. *
  24738. * @param a The first submesh
  24739. * @param b The second submesh
  24740. * @returns The result of the comparison
  24741. */
  24742. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24743. // Then distance to camera
  24744. if (a._distanceToCamera < b._distanceToCamera) {
  24745. return 1;
  24746. }
  24747. if (a._distanceToCamera > b._distanceToCamera) {
  24748. return -1;
  24749. }
  24750. return 0;
  24751. };
  24752. /**
  24753. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24754. * are rendered front to back (prevent overdraw).
  24755. *
  24756. * @param a The first submesh
  24757. * @param b The second submesh
  24758. * @returns The result of the comparison
  24759. */
  24760. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24761. // Then distance to camera
  24762. if (a._distanceToCamera < b._distanceToCamera) {
  24763. return -1;
  24764. }
  24765. if (a._distanceToCamera > b._distanceToCamera) {
  24766. return 1;
  24767. }
  24768. return 0;
  24769. };
  24770. /**
  24771. * Resets the different lists of submeshes to prepare a new frame.
  24772. */
  24773. RenderingGroup.prototype.prepare = function () {
  24774. this._opaqueSubMeshes.reset();
  24775. this._transparentSubMeshes.reset();
  24776. this._alphaTestSubMeshes.reset();
  24777. this._depthOnlySubMeshes.reset();
  24778. this._particleSystems.reset();
  24779. this._spriteManagers.reset();
  24780. this._edgesRenderers.reset();
  24781. };
  24782. RenderingGroup.prototype.dispose = function () {
  24783. this._opaqueSubMeshes.dispose();
  24784. this._transparentSubMeshes.dispose();
  24785. this._alphaTestSubMeshes.dispose();
  24786. this._depthOnlySubMeshes.dispose();
  24787. this._particleSystems.dispose();
  24788. this._spriteManagers.dispose();
  24789. this._edgesRenderers.dispose();
  24790. };
  24791. /**
  24792. * Inserts the submesh in its correct queue depending on its material.
  24793. * @param subMesh The submesh to dispatch
  24794. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24795. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24796. */
  24797. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24798. // Get mesh and materials if not provided
  24799. if (mesh === undefined) {
  24800. mesh = subMesh.getMesh();
  24801. }
  24802. if (material === undefined) {
  24803. material = subMesh.getMaterial();
  24804. }
  24805. if (material === null || material === undefined) {
  24806. return;
  24807. }
  24808. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24809. this._transparentSubMeshes.push(subMesh);
  24810. }
  24811. else if (material.needAlphaTesting()) { // Alpha test
  24812. if (material.needDepthPrePass) {
  24813. this._depthOnlySubMeshes.push(subMesh);
  24814. }
  24815. this._alphaTestSubMeshes.push(subMesh);
  24816. }
  24817. else {
  24818. if (material.needDepthPrePass) {
  24819. this._depthOnlySubMeshes.push(subMesh);
  24820. }
  24821. this._opaqueSubMeshes.push(subMesh); // Opaque
  24822. }
  24823. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24824. this._edgesRenderers.push(mesh._edgesRenderer);
  24825. }
  24826. };
  24827. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24828. this._spriteManagers.push(spriteManager);
  24829. };
  24830. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24831. this._particleSystems.push(particleSystem);
  24832. };
  24833. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24834. if (this._particleSystems.length === 0) {
  24835. return;
  24836. }
  24837. // Particles
  24838. var activeCamera = this._scene.activeCamera;
  24839. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24840. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24841. var particleSystem = this._particleSystems.data[particleIndex];
  24842. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24843. continue;
  24844. }
  24845. var emitter = particleSystem.emitter;
  24846. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24847. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24848. }
  24849. }
  24850. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24851. };
  24852. RenderingGroup.prototype._renderSprites = function () {
  24853. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24854. return;
  24855. }
  24856. // Sprites
  24857. var activeCamera = this._scene.activeCamera;
  24858. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24859. for (var id = 0; id < this._spriteManagers.length; id++) {
  24860. var spriteManager = this._spriteManagers.data[id];
  24861. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24862. spriteManager.render();
  24863. }
  24864. }
  24865. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24866. };
  24867. return RenderingGroup;
  24868. }());
  24869. BABYLON.RenderingGroup = RenderingGroup;
  24870. })(BABYLON || (BABYLON = {}));
  24871. //# sourceMappingURL=babylon.renderingGroup.js.map
  24872. var BABYLON;
  24873. (function (BABYLON) {
  24874. /**
  24875. * Groups all the scene component constants in one place to ease maintenance.
  24876. * @hidden
  24877. */
  24878. var SceneComponentConstants = /** @class */ (function () {
  24879. function SceneComponentConstants() {
  24880. }
  24881. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24882. SceneComponentConstants.NAME_LAYER = "Layer";
  24883. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24884. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24885. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24886. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24887. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24888. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24889. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24890. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24891. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24892. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24893. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24894. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24895. SceneComponentConstants.NAME_OCTREE = "Octree";
  24896. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24897. SceneComponentConstants.NAME_AUDIO = "Audio";
  24898. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24899. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24900. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24901. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24902. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24903. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24904. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24905. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24906. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24907. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24908. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24909. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24910. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24911. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24912. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24913. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24914. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24915. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24916. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24917. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24918. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24919. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24920. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24921. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24922. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24923. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24924. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24925. return SceneComponentConstants;
  24926. }());
  24927. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24928. /**
  24929. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24930. * @hidden
  24931. */
  24932. var Stage = /** @class */ (function (_super) {
  24933. __extends(Stage, _super);
  24934. /**
  24935. * Hide ctor from the rest of the world.
  24936. * @param items The items to add.
  24937. */
  24938. function Stage(items) {
  24939. return _super.apply(this, items) || this;
  24940. }
  24941. /**
  24942. * Creates a new Stage.
  24943. * @returns A new instance of a Stage
  24944. */
  24945. Stage.Create = function () {
  24946. return Object.create(Stage.prototype);
  24947. };
  24948. /**
  24949. * Registers a step in an ordered way in the targeted stage.
  24950. * @param index Defines the position to register the step in
  24951. * @param component Defines the component attached to the step
  24952. * @param action Defines the action to launch during the step
  24953. */
  24954. Stage.prototype.registerStep = function (index, component, action) {
  24955. var i = 0;
  24956. var maxIndex = Number.MAX_VALUE;
  24957. for (; i < this.length; i++) {
  24958. var step = this[i];
  24959. maxIndex = step.index;
  24960. if (index < maxIndex) {
  24961. break;
  24962. }
  24963. }
  24964. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24965. };
  24966. /**
  24967. * Clears all the steps from the stage.
  24968. */
  24969. Stage.prototype.clear = function () {
  24970. this.length = 0;
  24971. };
  24972. return Stage;
  24973. }(Array));
  24974. BABYLON.Stage = Stage;
  24975. })(BABYLON || (BABYLON = {}));
  24976. //# sourceMappingURL=babylon.sceneComponent.js.map
  24977. var BABYLON;
  24978. (function (BABYLON) {
  24979. /**
  24980. * Base class of the scene acting as a container for the different elements composing a scene.
  24981. * This class is dynamically extended by the different components of the scene increasing
  24982. * flexibility and reducing coupling
  24983. */
  24984. var AbstractScene = /** @class */ (function () {
  24985. function AbstractScene() {
  24986. /**
  24987. * Gets the list of root nodes (ie. nodes with no parent)
  24988. */
  24989. this.rootNodes = new Array();
  24990. /** All of the cameras added to this scene
  24991. * @see http://doc.babylonjs.com/babylon101/cameras
  24992. */
  24993. this.cameras = new Array();
  24994. /**
  24995. * All of the lights added to this scene
  24996. * @see http://doc.babylonjs.com/babylon101/lights
  24997. */
  24998. this.lights = new Array();
  24999. /**
  25000. * All of the (abstract) meshes added to this scene
  25001. */
  25002. this.meshes = new Array();
  25003. /**
  25004. * The list of skeletons added to the scene
  25005. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25006. */
  25007. this.skeletons = new Array();
  25008. /**
  25009. * All of the particle systems added to this scene
  25010. * @see http://doc.babylonjs.com/babylon101/particles
  25011. */
  25012. this.particleSystems = new Array();
  25013. /**
  25014. * Gets a list of Animations associated with the scene
  25015. */
  25016. this.animations = [];
  25017. /**
  25018. * All of the animation groups added to this scene
  25019. * @see http://doc.babylonjs.com/how_to/group
  25020. */
  25021. this.animationGroups = new Array();
  25022. /**
  25023. * All of the multi-materials added to this scene
  25024. * @see http://doc.babylonjs.com/how_to/multi_materials
  25025. */
  25026. this.multiMaterials = new Array();
  25027. /**
  25028. * All of the materials added to this scene
  25029. * @see http://doc.babylonjs.com/babylon101/materials
  25030. */
  25031. this.materials = new Array();
  25032. /**
  25033. * The list of morph target managers added to the scene
  25034. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25035. */
  25036. this.morphTargetManagers = new Array();
  25037. /**
  25038. * The list of geometries used in the scene.
  25039. */
  25040. this.geometries = new Array();
  25041. /**
  25042. * All of the tranform nodes added to this scene
  25043. * @see http://doc.babylonjs.com/how_to/transformnode
  25044. */
  25045. this.transformNodes = new Array();
  25046. /**
  25047. * ActionManagers available on the scene.
  25048. */
  25049. this.actionManagers = new Array();
  25050. /**
  25051. * Textures to keep.
  25052. */
  25053. this.textures = new Array();
  25054. }
  25055. /**
  25056. * Adds a parser in the list of available ones
  25057. * @param name Defines the name of the parser
  25058. * @param parser Defines the parser to add
  25059. */
  25060. AbstractScene.AddParser = function (name, parser) {
  25061. this._BabylonFileParsers[name] = parser;
  25062. };
  25063. /**
  25064. * Gets a general parser from the list of avaialble ones
  25065. * @param name Defines the name of the parser
  25066. * @returns the requested parser or null
  25067. */
  25068. AbstractScene.GetParser = function (name) {
  25069. if (this._BabylonFileParsers[name]) {
  25070. return this._BabylonFileParsers[name];
  25071. }
  25072. return null;
  25073. };
  25074. /**
  25075. * Adds n individual parser in the list of available ones
  25076. * @param name Defines the name of the parser
  25077. * @param parser Defines the parser to add
  25078. */
  25079. AbstractScene.AddIndividualParser = function (name, parser) {
  25080. this._IndividualBabylonFileParsers[name] = parser;
  25081. };
  25082. /**
  25083. * Gets an individual parser from the list of avaialble ones
  25084. * @param name Defines the name of the parser
  25085. * @returns the requested parser or null
  25086. */
  25087. AbstractScene.GetIndividualParser = function (name) {
  25088. if (this._IndividualBabylonFileParsers[name]) {
  25089. return this._IndividualBabylonFileParsers[name];
  25090. }
  25091. return null;
  25092. };
  25093. /**
  25094. * Parser json data and populate both a scene and its associated container object
  25095. * @param jsonData Defines the data to parse
  25096. * @param scene Defines the scene to parse the data for
  25097. * @param container Defines the container attached to the parsing sequence
  25098. * @param rootUrl Defines the root url of the data
  25099. */
  25100. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25101. for (var parserName in this._BabylonFileParsers) {
  25102. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25103. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25104. }
  25105. }
  25106. };
  25107. /**
  25108. * Stores the list of available parsers in the application.
  25109. */
  25110. AbstractScene._BabylonFileParsers = {};
  25111. /**
  25112. * Stores the list of available individual parsers in the application.
  25113. */
  25114. AbstractScene._IndividualBabylonFileParsers = {};
  25115. return AbstractScene;
  25116. }());
  25117. BABYLON.AbstractScene = AbstractScene;
  25118. })(BABYLON || (BABYLON = {}));
  25119. //# sourceMappingURL=babylon.abstractScene.js.map
  25120. var BABYLON;
  25121. (function (BABYLON) {
  25122. /** @hidden */
  25123. var ClickInfo = /** @class */ (function () {
  25124. function ClickInfo() {
  25125. this._singleClick = false;
  25126. this._doubleClick = false;
  25127. this._hasSwiped = false;
  25128. this._ignore = false;
  25129. }
  25130. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25131. get: function () {
  25132. return this._singleClick;
  25133. },
  25134. set: function (b) {
  25135. this._singleClick = b;
  25136. },
  25137. enumerable: true,
  25138. configurable: true
  25139. });
  25140. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25141. get: function () {
  25142. return this._doubleClick;
  25143. },
  25144. set: function (b) {
  25145. this._doubleClick = b;
  25146. },
  25147. enumerable: true,
  25148. configurable: true
  25149. });
  25150. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25151. get: function () {
  25152. return this._hasSwiped;
  25153. },
  25154. set: function (b) {
  25155. this._hasSwiped = b;
  25156. },
  25157. enumerable: true,
  25158. configurable: true
  25159. });
  25160. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25161. get: function () {
  25162. return this._ignore;
  25163. },
  25164. set: function (b) {
  25165. this._ignore = b;
  25166. },
  25167. enumerable: true,
  25168. configurable: true
  25169. });
  25170. return ClickInfo;
  25171. }());
  25172. /**
  25173. * This class is used by the onRenderingGroupObservable
  25174. */
  25175. var RenderingGroupInfo = /** @class */ (function () {
  25176. function RenderingGroupInfo() {
  25177. }
  25178. return RenderingGroupInfo;
  25179. }());
  25180. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25181. /**
  25182. * Represents a scene to be rendered by the engine.
  25183. * @see http://doc.babylonjs.com/features/scene
  25184. */
  25185. var Scene = /** @class */ (function (_super) {
  25186. __extends(Scene, _super);
  25187. /**
  25188. * Creates a new Scene
  25189. * @param engine defines the engine to use to render this scene
  25190. */
  25191. function Scene(engine) {
  25192. var _this = _super.call(this) || this;
  25193. // Members
  25194. /**
  25195. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25196. */
  25197. _this.autoClear = true;
  25198. /**
  25199. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25200. */
  25201. _this.autoClearDepthAndStencil = true;
  25202. /**
  25203. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25204. */
  25205. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25206. /**
  25207. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25208. */
  25209. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25210. _this._forceWireframe = false;
  25211. _this._forcePointsCloud = false;
  25212. /**
  25213. * Gets or sets a boolean indicating if animations are enabled
  25214. */
  25215. _this.animationsEnabled = true;
  25216. _this._animationPropertiesOverride = null;
  25217. /**
  25218. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25219. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25220. */
  25221. _this.useConstantAnimationDeltaTime = false;
  25222. /**
  25223. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25224. * Please note that it requires to run a ray cast through the scene on every frame
  25225. */
  25226. _this.constantlyUpdateMeshUnderPointer = false;
  25227. /**
  25228. * Defines the HTML cursor to use when hovering over interactive elements
  25229. */
  25230. _this.hoverCursor = "pointer";
  25231. /**
  25232. * Defines the HTML default cursor to use (empty by default)
  25233. */
  25234. _this.defaultCursor = "";
  25235. /**
  25236. * This is used to call preventDefault() on pointer down
  25237. * in order to block unwanted artifacts like system double clicks
  25238. */
  25239. _this.preventDefaultOnPointerDown = true;
  25240. // Metadata
  25241. /**
  25242. * Gets or sets user defined metadata
  25243. */
  25244. _this.metadata = null;
  25245. /**
  25246. * Use this array to add regular expressions used to disable offline support for specific urls
  25247. */
  25248. _this.disableOfflineSupportExceptionRules = new Array();
  25249. /**
  25250. * An event triggered when the scene is disposed.
  25251. */
  25252. _this.onDisposeObservable = new BABYLON.Observable();
  25253. _this._onDisposeObserver = null;
  25254. /**
  25255. * An event triggered before rendering the scene (right after animations and physics)
  25256. */
  25257. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25258. _this._onBeforeRenderObserver = null;
  25259. /**
  25260. * An event triggered after rendering the scene
  25261. */
  25262. _this.onAfterRenderObservable = new BABYLON.Observable();
  25263. _this._onAfterRenderObserver = null;
  25264. /**
  25265. * An event triggered before animating the scene
  25266. */
  25267. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25268. /**
  25269. * An event triggered after animations processing
  25270. */
  25271. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25272. /**
  25273. * An event triggered before draw calls are ready to be sent
  25274. */
  25275. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25276. /**
  25277. * An event triggered after draw calls have been sent
  25278. */
  25279. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25280. /**
  25281. * An event triggered when the scene is ready
  25282. */
  25283. _this.onReadyObservable = new BABYLON.Observable();
  25284. /**
  25285. * An event triggered before rendering a camera
  25286. */
  25287. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25288. _this._onBeforeCameraRenderObserver = null;
  25289. /**
  25290. * An event triggered after rendering a camera
  25291. */
  25292. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25293. _this._onAfterCameraRenderObserver = null;
  25294. /**
  25295. * An event triggered when active meshes evaluation is about to start
  25296. */
  25297. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25298. /**
  25299. * An event triggered when active meshes evaluation is done
  25300. */
  25301. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25302. /**
  25303. * An event triggered when particles rendering is about to start
  25304. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25305. */
  25306. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25307. /**
  25308. * An event triggered when particles rendering is done
  25309. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25310. */
  25311. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25312. /**
  25313. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25314. */
  25315. _this.onDataLoadedObservable = new BABYLON.Observable();
  25316. /**
  25317. * An event triggered when a camera is created
  25318. */
  25319. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25320. /**
  25321. * An event triggered when a camera is removed
  25322. */
  25323. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25324. /**
  25325. * An event triggered when a light is created
  25326. */
  25327. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25328. /**
  25329. * An event triggered when a light is removed
  25330. */
  25331. _this.onLightRemovedObservable = new BABYLON.Observable();
  25332. /**
  25333. * An event triggered when a geometry is created
  25334. */
  25335. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25336. /**
  25337. * An event triggered when a geometry is removed
  25338. */
  25339. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25340. /**
  25341. * An event triggered when a transform node is created
  25342. */
  25343. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25344. /**
  25345. * An event triggered when a transform node is removed
  25346. */
  25347. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25348. /**
  25349. * An event triggered when a mesh is created
  25350. */
  25351. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25352. /**
  25353. * An event triggered when a mesh is removed
  25354. */
  25355. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25356. /**
  25357. * An event triggered when a material is created
  25358. */
  25359. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25360. /**
  25361. * An event triggered when a material is removed
  25362. */
  25363. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25364. /**
  25365. * An event triggered when a texture is created
  25366. */
  25367. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25368. /**
  25369. * An event triggered when a texture is removed
  25370. */
  25371. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25372. /**
  25373. * An event triggered when render targets are about to be rendered
  25374. * Can happen multiple times per frame.
  25375. */
  25376. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25377. /**
  25378. * An event triggered when render targets were rendered.
  25379. * Can happen multiple times per frame.
  25380. */
  25381. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25382. /**
  25383. * An event triggered before calculating deterministic simulation step
  25384. */
  25385. _this.onBeforeStepObservable = new BABYLON.Observable();
  25386. /**
  25387. * An event triggered after calculating deterministic simulation step
  25388. */
  25389. _this.onAfterStepObservable = new BABYLON.Observable();
  25390. /**
  25391. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25392. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25393. * 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)
  25394. */
  25395. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25396. /**
  25397. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25398. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25399. * 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)
  25400. */
  25401. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25402. /**
  25403. * This Observable will when a mesh has been imported into the scene.
  25404. */
  25405. _this.onMeshImportedObservable = new BABYLON.Observable();
  25406. // Animations
  25407. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25408. /**
  25409. * 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).
  25410. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25411. */
  25412. _this.onPrePointerObservable = new BABYLON.Observable();
  25413. /**
  25414. * Observable event triggered each time an input event is received from the rendering canvas
  25415. */
  25416. _this.onPointerObservable = new BABYLON.Observable();
  25417. _this._meshPickProceed = false;
  25418. _this._currentPickResult = null;
  25419. _this._previousPickResult = null;
  25420. _this._totalPointersPressed = 0;
  25421. _this._doubleClickOccured = false;
  25422. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25423. _this.cameraToUseForPointers = null;
  25424. _this._pointerX = 0;
  25425. _this._pointerY = 0;
  25426. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25427. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25428. _this._startingPointerTime = 0;
  25429. _this._previousStartingPointerTime = 0;
  25430. _this._pointerCaptures = {};
  25431. // Deterministic lockstep
  25432. _this._timeAccumulator = 0;
  25433. _this._currentStepId = 0;
  25434. _this._currentInternalStep = 0;
  25435. // Keyboard
  25436. /**
  25437. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25438. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25439. */
  25440. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25441. /**
  25442. * Observable event triggered each time an keyboard event is received from the hosting window
  25443. */
  25444. _this.onKeyboardObservable = new BABYLON.Observable();
  25445. // Coordinates system
  25446. _this._useRightHandedSystem = false;
  25447. // Fog
  25448. _this._fogEnabled = true;
  25449. _this._fogMode = Scene.FOGMODE_NONE;
  25450. /**
  25451. * Gets or sets the fog color to use
  25452. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25453. * (Default is Color3(0.2, 0.2, 0.3))
  25454. */
  25455. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25456. /**
  25457. * Gets or sets the fog density to use
  25458. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25459. * (Default is 0.1)
  25460. */
  25461. _this.fogDensity = 0.1;
  25462. /**
  25463. * Gets or sets the fog start distance to use
  25464. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25465. * (Default is 0)
  25466. */
  25467. _this.fogStart = 0;
  25468. /**
  25469. * Gets or sets the fog end distance to use
  25470. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25471. * (Default is 1000)
  25472. */
  25473. _this.fogEnd = 1000.0;
  25474. // Lights
  25475. _this._shadowsEnabled = true;
  25476. _this._lightsEnabled = true;
  25477. /** All of the active cameras added to this scene. */
  25478. _this.activeCameras = new Array();
  25479. // Textures
  25480. _this._texturesEnabled = true;
  25481. // Particles
  25482. /**
  25483. * Gets or sets a boolean indicating if particles are enabled on this scene
  25484. */
  25485. _this.particlesEnabled = true;
  25486. // Sprites
  25487. /**
  25488. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25489. */
  25490. _this.spritesEnabled = true;
  25491. // Skeletons
  25492. _this._skeletonsEnabled = true;
  25493. // Lens flares
  25494. /**
  25495. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25496. */
  25497. _this.lensFlaresEnabled = true;
  25498. // Collisions
  25499. /**
  25500. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25501. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25502. */
  25503. _this.collisionsEnabled = true;
  25504. /**
  25505. * Defines the gravity applied to this scene (used only for collisions)
  25506. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25507. */
  25508. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25509. // Postprocesses
  25510. /**
  25511. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25512. */
  25513. _this.postProcessesEnabled = true;
  25514. /**
  25515. * The list of postprocesses added to the scene
  25516. */
  25517. _this.postProcesses = new Array();
  25518. // Customs render targets
  25519. /**
  25520. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25521. */
  25522. _this.renderTargetsEnabled = true;
  25523. /**
  25524. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25525. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25526. */
  25527. _this.dumpNextRenderTargets = false;
  25528. /**
  25529. * The list of user defined render targets added to the scene
  25530. */
  25531. _this.customRenderTargets = new Array();
  25532. /**
  25533. * Gets the list of meshes imported to the scene through SceneLoader
  25534. */
  25535. _this.importedMeshesFiles = new Array();
  25536. // Probes
  25537. /**
  25538. * Gets or sets a boolean indicating if probes are enabled on this scene
  25539. */
  25540. _this.probesEnabled = true;
  25541. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25542. // Procedural textures
  25543. /**
  25544. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25545. */
  25546. _this.proceduralTexturesEnabled = true;
  25547. // Performance counters
  25548. _this._totalVertices = new BABYLON.PerfCounter();
  25549. /** @hidden */
  25550. _this._activeIndices = new BABYLON.PerfCounter();
  25551. /** @hidden */
  25552. _this._activeParticles = new BABYLON.PerfCounter();
  25553. /** @hidden */
  25554. _this._activeBones = new BABYLON.PerfCounter();
  25555. _this._animationTime = 0;
  25556. /**
  25557. * Gets or sets a general scale for animation speed
  25558. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25559. */
  25560. _this.animationTimeScale = 1;
  25561. _this._renderId = 0;
  25562. _this._frameId = 0;
  25563. _this._executeWhenReadyTimeoutId = -1;
  25564. _this._intermediateRendering = false;
  25565. _this._viewUpdateFlag = -1;
  25566. _this._projectionUpdateFlag = -1;
  25567. _this._alternateViewUpdateFlag = -1;
  25568. _this._alternateProjectionUpdateFlag = -1;
  25569. /** @hidden */
  25570. _this._toBeDisposed = new Array(256);
  25571. _this._activeRequests = new Array();
  25572. _this._pendingData = new Array();
  25573. _this._isDisposed = false;
  25574. /**
  25575. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25576. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25577. */
  25578. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25579. _this._activeMeshes = new BABYLON.SmartArray(256);
  25580. _this._processedMaterials = new BABYLON.SmartArray(256);
  25581. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25582. /** @hidden */
  25583. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25584. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25585. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25586. /** @hidden */
  25587. _this._activeAnimatables = new Array();
  25588. _this._transformMatrix = BABYLON.Matrix.Zero();
  25589. _this._useAlternateCameraConfiguration = false;
  25590. _this._alternateRendering = false;
  25591. /**
  25592. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25593. * This is useful if there are more lights that the maximum simulteanous authorized
  25594. */
  25595. _this.requireLightSorting = false;
  25596. /**
  25597. * @hidden
  25598. * Backing store of defined scene components.
  25599. */
  25600. _this._components = [];
  25601. /**
  25602. * @hidden
  25603. * Backing store of defined scene components.
  25604. */
  25605. _this._serializableComponents = [];
  25606. /**
  25607. * List of components to register on the next registration step.
  25608. */
  25609. _this._transientComponents = [];
  25610. /**
  25611. * @hidden
  25612. * Defines the actions happening before camera updates.
  25613. */
  25614. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25615. /**
  25616. * @hidden
  25617. * Defines the actions happening before clear the canvas.
  25618. */
  25619. _this._beforeClearStage = BABYLON.Stage.Create();
  25620. /**
  25621. * @hidden
  25622. * Defines the actions when collecting render targets for the frame.
  25623. */
  25624. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25625. /**
  25626. * @hidden
  25627. * Defines the actions happening for one camera in the frame.
  25628. */
  25629. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25630. /**
  25631. * @hidden
  25632. * Defines the actions happening during the per mesh ready checks.
  25633. */
  25634. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25635. /**
  25636. * @hidden
  25637. * Defines the actions happening before evaluate active mesh checks.
  25638. */
  25639. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25640. /**
  25641. * @hidden
  25642. * Defines the actions happening during the evaluate sub mesh checks.
  25643. */
  25644. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25645. /**
  25646. * @hidden
  25647. * Defines the actions happening during the active mesh stage.
  25648. */
  25649. _this._activeMeshStage = BABYLON.Stage.Create();
  25650. /**
  25651. * @hidden
  25652. * Defines the actions happening during the per camera render target step.
  25653. */
  25654. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25655. /**
  25656. * @hidden
  25657. * Defines the actions happening just before the active camera is drawing.
  25658. */
  25659. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25660. /**
  25661. * @hidden
  25662. * Defines the actions happening just before a rendering group is drawing.
  25663. */
  25664. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25665. /**
  25666. * @hidden
  25667. * Defines the actions happening just before a mesh is drawing.
  25668. */
  25669. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25670. /**
  25671. * @hidden
  25672. * Defines the actions happening just after a mesh has been drawn.
  25673. */
  25674. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25675. /**
  25676. * @hidden
  25677. * Defines the actions happening just after a rendering group has been drawn.
  25678. */
  25679. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25680. /**
  25681. * @hidden
  25682. * Defines the actions happening just after the active camera has been drawn.
  25683. */
  25684. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25685. /**
  25686. * @hidden
  25687. * Defines the actions happening just after rendering all cameras and computing intersections.
  25688. */
  25689. _this._afterRenderStage = BABYLON.Stage.Create();
  25690. /**
  25691. * @hidden
  25692. * Defines the actions happening when a pointer move event happens.
  25693. */
  25694. _this._pointerMoveStage = BABYLON.Stage.Create();
  25695. /**
  25696. * @hidden
  25697. * Defines the actions happening when a pointer down event happens.
  25698. */
  25699. _this._pointerDownStage = BABYLON.Stage.Create();
  25700. /**
  25701. * @hidden
  25702. * Defines the actions happening when a pointer up event happens.
  25703. */
  25704. _this._pointerUpStage = BABYLON.Stage.Create();
  25705. _this._defaultMeshCandidates = {
  25706. data: [],
  25707. length: 0
  25708. };
  25709. _this._defaultSubMeshCandidates = {
  25710. data: [],
  25711. length: 0
  25712. };
  25713. _this._activeMeshesFrozen = false;
  25714. /** @hidden */
  25715. _this._allowPostProcessClearColor = true;
  25716. /**
  25717. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25718. */
  25719. _this.getDeterministicFrameTime = function () {
  25720. return 1000.0 / 60.0; // frame time in ms
  25721. };
  25722. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25723. _this._blockMaterialDirtyMechanism = false;
  25724. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25725. _this._engine.scenes.push(_this);
  25726. _this._uid = null;
  25727. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25728. if (BABYLON.PostProcessManager) {
  25729. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25730. }
  25731. if (BABYLON.Tools.IsWindowObjectExist()) {
  25732. _this.attachControl();
  25733. }
  25734. //collision coordinator initialization. For now legacy per default.
  25735. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25736. // Uniform Buffer
  25737. _this._createUbo();
  25738. // Default Image processing definition
  25739. if (BABYLON.ImageProcessingConfiguration) {
  25740. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25741. }
  25742. _this.setDefaultCandidateProviders();
  25743. return _this;
  25744. }
  25745. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25746. /**
  25747. * Texture used in all pbr material as the reflection texture.
  25748. * As in the majority of the scene they are the same (exception for multi room and so on),
  25749. * this is easier to reference from here than from all the materials.
  25750. */
  25751. get: function () {
  25752. return this._environmentTexture;
  25753. },
  25754. /**
  25755. * Texture used in all pbr material as the reflection texture.
  25756. * As in the majority of the scene they are the same (exception for multi room and so on),
  25757. * this is easier to set here than in all the materials.
  25758. */
  25759. set: function (value) {
  25760. if (this._environmentTexture === value) {
  25761. return;
  25762. }
  25763. this._environmentTexture = value;
  25764. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25765. },
  25766. enumerable: true,
  25767. configurable: true
  25768. });
  25769. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25770. /**
  25771. * Default image processing configuration used either in the rendering
  25772. * Forward main pass or through the imageProcessingPostProcess if present.
  25773. * As in the majority of the scene they are the same (exception for multi camera),
  25774. * this is easier to reference from here than from all the materials and post process.
  25775. *
  25776. * No setter as we it is a shared configuration, you can set the values instead.
  25777. */
  25778. get: function () {
  25779. return this._imageProcessingConfiguration;
  25780. },
  25781. enumerable: true,
  25782. configurable: true
  25783. });
  25784. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25785. get: function () {
  25786. return this._forceWireframe;
  25787. },
  25788. /**
  25789. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25790. */
  25791. set: function (value) {
  25792. if (this._forceWireframe === value) {
  25793. return;
  25794. }
  25795. this._forceWireframe = value;
  25796. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25797. },
  25798. enumerable: true,
  25799. configurable: true
  25800. });
  25801. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25802. get: function () {
  25803. return this._forcePointsCloud;
  25804. },
  25805. /**
  25806. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25807. */
  25808. set: function (value) {
  25809. if (this._forcePointsCloud === value) {
  25810. return;
  25811. }
  25812. this._forcePointsCloud = value;
  25813. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25814. },
  25815. enumerable: true,
  25816. configurable: true
  25817. });
  25818. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25819. /**
  25820. * Gets or sets the animation properties override
  25821. */
  25822. get: function () {
  25823. return this._animationPropertiesOverride;
  25824. },
  25825. set: function (value) {
  25826. this._animationPropertiesOverride = value;
  25827. },
  25828. enumerable: true,
  25829. configurable: true
  25830. });
  25831. Object.defineProperty(Scene.prototype, "onDispose", {
  25832. /** Sets a function to be executed when this scene is disposed. */
  25833. set: function (callback) {
  25834. if (this._onDisposeObserver) {
  25835. this.onDisposeObservable.remove(this._onDisposeObserver);
  25836. }
  25837. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25838. },
  25839. enumerable: true,
  25840. configurable: true
  25841. });
  25842. Object.defineProperty(Scene.prototype, "beforeRender", {
  25843. /** Sets a function to be executed before rendering this scene */
  25844. set: function (callback) {
  25845. if (this._onBeforeRenderObserver) {
  25846. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25847. }
  25848. if (callback) {
  25849. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25850. }
  25851. },
  25852. enumerable: true,
  25853. configurable: true
  25854. });
  25855. Object.defineProperty(Scene.prototype, "afterRender", {
  25856. /** Sets a function to be executed after rendering this scene */
  25857. set: function (callback) {
  25858. if (this._onAfterRenderObserver) {
  25859. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25860. }
  25861. if (callback) {
  25862. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25863. }
  25864. },
  25865. enumerable: true,
  25866. configurable: true
  25867. });
  25868. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25869. /** Sets a function to be executed before rendering a camera*/
  25870. set: function (callback) {
  25871. if (this._onBeforeCameraRenderObserver) {
  25872. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25873. }
  25874. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25880. /** Sets a function to be executed after rendering a camera*/
  25881. set: function (callback) {
  25882. if (this._onAfterCameraRenderObserver) {
  25883. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25884. }
  25885. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25891. /**
  25892. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25893. */
  25894. get: function () {
  25895. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25896. },
  25897. enumerable: true,
  25898. configurable: true
  25899. });
  25900. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25901. get: function () {
  25902. return this._useRightHandedSystem;
  25903. },
  25904. /**
  25905. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25906. */
  25907. set: function (value) {
  25908. if (this._useRightHandedSystem === value) {
  25909. return;
  25910. }
  25911. this._useRightHandedSystem = value;
  25912. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25913. },
  25914. enumerable: true,
  25915. configurable: true
  25916. });
  25917. /**
  25918. * Sets the step Id used by deterministic lock step
  25919. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25920. * @param newStepId defines the step Id
  25921. */
  25922. Scene.prototype.setStepId = function (newStepId) {
  25923. this._currentStepId = newStepId;
  25924. };
  25925. /**
  25926. * Gets the step Id used by deterministic lock step
  25927. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25928. * @returns the step Id
  25929. */
  25930. Scene.prototype.getStepId = function () {
  25931. return this._currentStepId;
  25932. };
  25933. /**
  25934. * Gets the internal step used by deterministic lock step
  25935. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25936. * @returns the internal step
  25937. */
  25938. Scene.prototype.getInternalStep = function () {
  25939. return this._currentInternalStep;
  25940. };
  25941. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25942. get: function () {
  25943. return this._fogEnabled;
  25944. },
  25945. /**
  25946. * Gets or sets a boolean indicating if fog is enabled on this scene
  25947. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25948. * (Default is true)
  25949. */
  25950. set: function (value) {
  25951. if (this._fogEnabled === value) {
  25952. return;
  25953. }
  25954. this._fogEnabled = value;
  25955. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25956. },
  25957. enumerable: true,
  25958. configurable: true
  25959. });
  25960. Object.defineProperty(Scene.prototype, "fogMode", {
  25961. get: function () {
  25962. return this._fogMode;
  25963. },
  25964. /**
  25965. * Gets or sets the fog mode to use
  25966. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25967. * | mode | value |
  25968. * | --- | --- |
  25969. * | FOGMODE_NONE | 0 |
  25970. * | FOGMODE_EXP | 1 |
  25971. * | FOGMODE_EXP2 | 2 |
  25972. * | FOGMODE_LINEAR | 3 |
  25973. */
  25974. set: function (value) {
  25975. if (this._fogMode === value) {
  25976. return;
  25977. }
  25978. this._fogMode = value;
  25979. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25980. },
  25981. enumerable: true,
  25982. configurable: true
  25983. });
  25984. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25985. get: function () {
  25986. return this._shadowsEnabled;
  25987. },
  25988. /**
  25989. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25990. */
  25991. set: function (value) {
  25992. if (this._shadowsEnabled === value) {
  25993. return;
  25994. }
  25995. this._shadowsEnabled = value;
  25996. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25997. },
  25998. enumerable: true,
  25999. configurable: true
  26000. });
  26001. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26002. get: function () {
  26003. return this._lightsEnabled;
  26004. },
  26005. /**
  26006. * Gets or sets a boolean indicating if lights are enabled on this scene
  26007. */
  26008. set: function (value) {
  26009. if (this._lightsEnabled === value) {
  26010. return;
  26011. }
  26012. this._lightsEnabled = value;
  26013. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26014. },
  26015. enumerable: true,
  26016. configurable: true
  26017. });
  26018. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26019. /** The default material used on meshes when no material is affected */
  26020. get: function () {
  26021. if (!this._defaultMaterial) {
  26022. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26023. }
  26024. return this._defaultMaterial;
  26025. },
  26026. /** The default material used on meshes when no material is affected */
  26027. set: function (value) {
  26028. this._defaultMaterial = value;
  26029. },
  26030. enumerable: true,
  26031. configurable: true
  26032. });
  26033. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26034. get: function () {
  26035. return this._texturesEnabled;
  26036. },
  26037. /**
  26038. * Gets or sets a boolean indicating if textures are enabled on this scene
  26039. */
  26040. set: function (value) {
  26041. if (this._texturesEnabled === value) {
  26042. return;
  26043. }
  26044. this._texturesEnabled = value;
  26045. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26046. },
  26047. enumerable: true,
  26048. configurable: true
  26049. });
  26050. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26051. get: function () {
  26052. return this._skeletonsEnabled;
  26053. },
  26054. /**
  26055. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26056. */
  26057. set: function (value) {
  26058. if (this._skeletonsEnabled === value) {
  26059. return;
  26060. }
  26061. this._skeletonsEnabled = value;
  26062. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26063. },
  26064. enumerable: true,
  26065. configurable: true
  26066. });
  26067. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26068. /** @hidden */
  26069. get: function () {
  26070. return this._alternateRendering;
  26071. },
  26072. enumerable: true,
  26073. configurable: true
  26074. });
  26075. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26076. /**
  26077. * Gets the list of frustum planes (built from the active camera)
  26078. */
  26079. get: function () {
  26080. return this._frustumPlanes;
  26081. },
  26082. enumerable: true,
  26083. configurable: true
  26084. });
  26085. /**
  26086. * Registers the transient components if needed.
  26087. */
  26088. Scene.prototype._registerTransientComponents = function () {
  26089. // Register components that have been associated lately to the scene.
  26090. if (this._transientComponents.length > 0) {
  26091. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26092. var component = _a[_i];
  26093. component.register();
  26094. }
  26095. this._transientComponents = [];
  26096. }
  26097. };
  26098. /**
  26099. * @hidden
  26100. * Add a component to the scene.
  26101. * Note that the ccomponent could be registered on th next frame if this is called after
  26102. * the register component stage.
  26103. * @param component Defines the component to add to the scene
  26104. */
  26105. Scene.prototype._addComponent = function (component) {
  26106. this._components.push(component);
  26107. this._transientComponents.push(component);
  26108. var serializableComponent = component;
  26109. if (serializableComponent.addFromContainer) {
  26110. this._serializableComponents.push(serializableComponent);
  26111. }
  26112. };
  26113. /**
  26114. * @hidden
  26115. * Gets a component from the scene.
  26116. * @param name defines the name of the component to retrieve
  26117. * @returns the component or null if not present
  26118. */
  26119. Scene.prototype._getComponent = function (name) {
  26120. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26121. var component = _a[_i];
  26122. if (component.name === name) {
  26123. return component;
  26124. }
  26125. }
  26126. return null;
  26127. };
  26128. /**
  26129. * @hidden
  26130. */
  26131. Scene.prototype._getDefaultMeshCandidates = function () {
  26132. this._defaultMeshCandidates.data = this.meshes;
  26133. this._defaultMeshCandidates.length = this.meshes.length;
  26134. return this._defaultMeshCandidates;
  26135. };
  26136. /**
  26137. * @hidden
  26138. */
  26139. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26140. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26141. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26142. return this._defaultSubMeshCandidates;
  26143. };
  26144. /**
  26145. * Sets the default candidate providers for the scene.
  26146. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26147. * and getCollidingSubMeshCandidates to their default function
  26148. */
  26149. Scene.prototype.setDefaultCandidateProviders = function () {
  26150. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26151. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26152. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26153. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26154. };
  26155. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26156. /**
  26157. * Gets a boolean indicating if collisions are processed on a web worker
  26158. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26159. */
  26160. get: function () {
  26161. return this._workerCollisions;
  26162. },
  26163. set: function (enabled) {
  26164. if (!BABYLON.CollisionCoordinatorLegacy) {
  26165. return;
  26166. }
  26167. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26168. this._workerCollisions = enabled;
  26169. if (this.collisionCoordinator) {
  26170. this.collisionCoordinator.destroy();
  26171. }
  26172. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26173. this.collisionCoordinator.init(this);
  26174. },
  26175. enumerable: true,
  26176. configurable: true
  26177. });
  26178. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26179. /**
  26180. * Gets the mesh that is currently under the pointer
  26181. */
  26182. get: function () {
  26183. return this._pointerOverMesh;
  26184. },
  26185. enumerable: true,
  26186. configurable: true
  26187. });
  26188. Object.defineProperty(Scene.prototype, "pointerX", {
  26189. /**
  26190. * Gets the current on-screen X position of the pointer
  26191. */
  26192. get: function () {
  26193. return this._pointerX;
  26194. },
  26195. enumerable: true,
  26196. configurable: true
  26197. });
  26198. Object.defineProperty(Scene.prototype, "pointerY", {
  26199. /**
  26200. * Gets the current on-screen Y position of the pointer
  26201. */
  26202. get: function () {
  26203. return this._pointerY;
  26204. },
  26205. enumerable: true,
  26206. configurable: true
  26207. });
  26208. /**
  26209. * Gets the cached material (ie. the latest rendered one)
  26210. * @returns the cached material
  26211. */
  26212. Scene.prototype.getCachedMaterial = function () {
  26213. return this._cachedMaterial;
  26214. };
  26215. /**
  26216. * Gets the cached effect (ie. the latest rendered one)
  26217. * @returns the cached effect
  26218. */
  26219. Scene.prototype.getCachedEffect = function () {
  26220. return this._cachedEffect;
  26221. };
  26222. /**
  26223. * Gets the cached visibility state (ie. the latest rendered one)
  26224. * @returns the cached visibility state
  26225. */
  26226. Scene.prototype.getCachedVisibility = function () {
  26227. return this._cachedVisibility;
  26228. };
  26229. /**
  26230. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26231. * @param material defines the current material
  26232. * @param effect defines the current effect
  26233. * @param visibility defines the current visibility state
  26234. * @returns true if one parameter is not cached
  26235. */
  26236. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26237. if (visibility === void 0) { visibility = 1; }
  26238. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26239. };
  26240. /**
  26241. * Gets the engine associated with the scene
  26242. * @returns an Engine
  26243. */
  26244. Scene.prototype.getEngine = function () {
  26245. return this._engine;
  26246. };
  26247. /**
  26248. * Gets the total number of vertices rendered per frame
  26249. * @returns the total number of vertices rendered per frame
  26250. */
  26251. Scene.prototype.getTotalVertices = function () {
  26252. return this._totalVertices.current;
  26253. };
  26254. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26255. /**
  26256. * Gets the performance counter for total vertices
  26257. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26258. */
  26259. get: function () {
  26260. return this._totalVertices;
  26261. },
  26262. enumerable: true,
  26263. configurable: true
  26264. });
  26265. /**
  26266. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26267. * @returns the total number of active indices rendered per frame
  26268. */
  26269. Scene.prototype.getActiveIndices = function () {
  26270. return this._activeIndices.current;
  26271. };
  26272. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26273. /**
  26274. * Gets the performance counter for active indices
  26275. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26276. */
  26277. get: function () {
  26278. return this._activeIndices;
  26279. },
  26280. enumerable: true,
  26281. configurable: true
  26282. });
  26283. /**
  26284. * Gets the total number of active particles rendered per frame
  26285. * @returns the total number of active particles rendered per frame
  26286. */
  26287. Scene.prototype.getActiveParticles = function () {
  26288. return this._activeParticles.current;
  26289. };
  26290. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26291. /**
  26292. * Gets the performance counter for active particles
  26293. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26294. */
  26295. get: function () {
  26296. return this._activeParticles;
  26297. },
  26298. enumerable: true,
  26299. configurable: true
  26300. });
  26301. /**
  26302. * Gets the total number of active bones rendered per frame
  26303. * @returns the total number of active bones rendered per frame
  26304. */
  26305. Scene.prototype.getActiveBones = function () {
  26306. return this._activeBones.current;
  26307. };
  26308. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26309. /**
  26310. * Gets the performance counter for active bones
  26311. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26312. */
  26313. get: function () {
  26314. return this._activeBones;
  26315. },
  26316. enumerable: true,
  26317. configurable: true
  26318. });
  26319. /** @hidden */
  26320. Scene.prototype.getInterFramePerfCounter = function () {
  26321. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26322. return 0;
  26323. };
  26324. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26325. /** @hidden */
  26326. get: function () {
  26327. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26328. return null;
  26329. },
  26330. enumerable: true,
  26331. configurable: true
  26332. });
  26333. /** @hidden */
  26334. Scene.prototype.getLastFrameDuration = function () {
  26335. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26336. return 0;
  26337. };
  26338. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26339. /** @hidden */
  26340. get: function () {
  26341. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26342. return null;
  26343. },
  26344. enumerable: true,
  26345. configurable: true
  26346. });
  26347. /** @hidden */
  26348. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26349. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26350. return 0;
  26351. };
  26352. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26353. /** @hidden */
  26354. get: function () {
  26355. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26356. return null;
  26357. },
  26358. enumerable: true,
  26359. configurable: true
  26360. });
  26361. /**
  26362. * Gets the array of active meshes
  26363. * @returns an array of AbstractMesh
  26364. */
  26365. Scene.prototype.getActiveMeshes = function () {
  26366. return this._activeMeshes;
  26367. };
  26368. /** @hidden */
  26369. Scene.prototype.getRenderTargetsDuration = function () {
  26370. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26371. return 0;
  26372. };
  26373. /** @hidden */
  26374. Scene.prototype.getRenderDuration = function () {
  26375. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26376. return 0;
  26377. };
  26378. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26379. /** @hidden */
  26380. get: function () {
  26381. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26382. return null;
  26383. },
  26384. enumerable: true,
  26385. configurable: true
  26386. });
  26387. /** @hidden */
  26388. Scene.prototype.getParticlesDuration = function () {
  26389. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26390. return 0;
  26391. };
  26392. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26393. /** @hidden */
  26394. get: function () {
  26395. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26396. return null;
  26397. },
  26398. enumerable: true,
  26399. configurable: true
  26400. });
  26401. /** @hidden */
  26402. Scene.prototype.getSpritesDuration = function () {
  26403. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26404. return 0;
  26405. };
  26406. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26407. /** @hidden */
  26408. get: function () {
  26409. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26410. return null;
  26411. },
  26412. enumerable: true,
  26413. configurable: true
  26414. });
  26415. /**
  26416. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26417. * @returns a number
  26418. */
  26419. Scene.prototype.getAnimationRatio = function () {
  26420. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26421. };
  26422. /**
  26423. * Gets an unique Id for the current render phase
  26424. * @returns a number
  26425. */
  26426. Scene.prototype.getRenderId = function () {
  26427. return this._renderId;
  26428. };
  26429. /**
  26430. * Gets an unique Id for the current frame
  26431. * @returns a number
  26432. */
  26433. Scene.prototype.getFrameId = function () {
  26434. return this._frameId;
  26435. };
  26436. /** Call this function if you want to manually increment the render Id*/
  26437. Scene.prototype.incrementRenderId = function () {
  26438. this._renderId++;
  26439. };
  26440. Scene.prototype._updatePointerPosition = function (evt) {
  26441. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26442. if (!canvasRect) {
  26443. return;
  26444. }
  26445. this._pointerX = evt.clientX - canvasRect.left;
  26446. this._pointerY = evt.clientY - canvasRect.top;
  26447. this._unTranslatedPointerX = this._pointerX;
  26448. this._unTranslatedPointerY = this._pointerY;
  26449. };
  26450. Scene.prototype._createUbo = function () {
  26451. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26452. this._sceneUbo.addUniform("viewProjection", 16);
  26453. this._sceneUbo.addUniform("view", 16);
  26454. };
  26455. Scene.prototype._createAlternateUbo = function () {
  26456. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26457. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26458. this._alternateSceneUbo.addUniform("view", 16);
  26459. };
  26460. // Pointers handling
  26461. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26462. if (pointerInfo.pickInfo) {
  26463. if (!pointerInfo.pickInfo.ray) {
  26464. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26465. }
  26466. }
  26467. };
  26468. /**
  26469. * Use this method to simulate a pointer move on a mesh
  26470. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26471. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26472. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26473. * @returns the current scene
  26474. */
  26475. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26476. var evt = new PointerEvent("pointermove", pointerEventInit);
  26477. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26478. return this;
  26479. }
  26480. return this._processPointerMove(pickResult, evt);
  26481. };
  26482. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26483. var canvas = this._engine.getRenderingCanvas();
  26484. if (!canvas) {
  26485. return this;
  26486. }
  26487. // Restore pointer
  26488. canvas.style.cursor = this.defaultCursor;
  26489. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26490. if (isMeshPicked) {
  26491. this.setPointerOverMesh(pickResult.pickedMesh);
  26492. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26493. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26494. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26495. }
  26496. else {
  26497. canvas.style.cursor = this.hoverCursor;
  26498. }
  26499. }
  26500. }
  26501. else {
  26502. this.setPointerOverMesh(null);
  26503. }
  26504. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26505. var step = _a[_i];
  26506. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26507. }
  26508. if (pickResult) {
  26509. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26510. if (this.onPointerMove) {
  26511. this.onPointerMove(evt, pickResult, type);
  26512. }
  26513. if (this.onPointerObservable.hasObservers()) {
  26514. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26515. this._setRayOnPointerInfo(pi);
  26516. this.onPointerObservable.notifyObservers(pi, type);
  26517. }
  26518. }
  26519. return this;
  26520. };
  26521. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26522. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26523. if (pickResult) {
  26524. pi.ray = pickResult.ray;
  26525. }
  26526. this.onPrePointerObservable.notifyObservers(pi, type);
  26527. if (pi.skipOnPointerObservable) {
  26528. return true;
  26529. }
  26530. else {
  26531. return false;
  26532. }
  26533. };
  26534. /**
  26535. * Use this method to simulate a pointer down on a mesh
  26536. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26537. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26538. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26539. * @returns the current scene
  26540. */
  26541. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26542. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26543. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26544. return this;
  26545. }
  26546. return this._processPointerDown(pickResult, evt);
  26547. };
  26548. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26549. var _this = this;
  26550. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26551. this._pickedDownMesh = pickResult.pickedMesh;
  26552. var actionManager = pickResult.pickedMesh.actionManager;
  26553. if (actionManager) {
  26554. if (actionManager.hasPickTriggers) {
  26555. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26556. switch (evt.button) {
  26557. case 0:
  26558. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26559. break;
  26560. case 1:
  26561. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26562. break;
  26563. case 2:
  26564. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26565. break;
  26566. }
  26567. }
  26568. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26569. window.setTimeout(function () {
  26570. 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);
  26571. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26572. if (_this._totalPointersPressed !== 0 &&
  26573. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26574. !_this._isPointerSwiping()) {
  26575. _this._startingPointerTime = 0;
  26576. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26577. }
  26578. }
  26579. }, Scene.LongPressDelay);
  26580. }
  26581. }
  26582. }
  26583. else {
  26584. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26585. var step = _a[_i];
  26586. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26587. }
  26588. }
  26589. if (pickResult) {
  26590. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26591. if (this.onPointerDown) {
  26592. this.onPointerDown(evt, pickResult, type);
  26593. }
  26594. if (this.onPointerObservable.hasObservers()) {
  26595. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26596. this._setRayOnPointerInfo(pi);
  26597. this.onPointerObservable.notifyObservers(pi, type);
  26598. }
  26599. }
  26600. return this;
  26601. };
  26602. /**
  26603. * Use this method to simulate a pointer up on a mesh
  26604. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26605. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26606. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26607. * @returns the current scene
  26608. */
  26609. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26610. var evt = new PointerEvent("pointerup", pointerEventInit);
  26611. var clickInfo = new ClickInfo();
  26612. clickInfo.singleClick = true;
  26613. clickInfo.ignore = true;
  26614. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26615. return this;
  26616. }
  26617. return this._processPointerUp(pickResult, evt, clickInfo);
  26618. };
  26619. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26620. if (pickResult && pickResult && pickResult.pickedMesh) {
  26621. this._pickedUpMesh = pickResult.pickedMesh;
  26622. if (this._pickedDownMesh === this._pickedUpMesh) {
  26623. if (this.onPointerPick) {
  26624. this.onPointerPick(evt, pickResult);
  26625. }
  26626. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26627. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26628. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26629. this._setRayOnPointerInfo(pi);
  26630. this.onPointerObservable.notifyObservers(pi, type_1);
  26631. }
  26632. }
  26633. if (pickResult.pickedMesh.actionManager) {
  26634. if (clickInfo.ignore) {
  26635. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26636. }
  26637. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26638. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26639. }
  26640. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26641. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26642. }
  26643. }
  26644. }
  26645. else {
  26646. if (!clickInfo.ignore) {
  26647. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26648. var step = _a[_i];
  26649. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26650. }
  26651. }
  26652. }
  26653. if (this._pickedDownMesh &&
  26654. this._pickedDownMesh.actionManager &&
  26655. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26656. this._pickedDownMesh !== this._pickedUpMesh) {
  26657. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26658. }
  26659. var type = BABYLON.PointerEventTypes.POINTERUP;
  26660. if (this.onPointerObservable.hasObservers()) {
  26661. if (!clickInfo.ignore) {
  26662. if (!clickInfo.hasSwiped) {
  26663. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26664. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26665. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26666. this._setRayOnPointerInfo(pi);
  26667. this.onPointerObservable.notifyObservers(pi, type_2);
  26668. }
  26669. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26670. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26671. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26672. this._setRayOnPointerInfo(pi);
  26673. this.onPointerObservable.notifyObservers(pi, type_3);
  26674. }
  26675. }
  26676. }
  26677. else {
  26678. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26679. this._setRayOnPointerInfo(pi);
  26680. this.onPointerObservable.notifyObservers(pi, type);
  26681. }
  26682. }
  26683. if (this.onPointerUp) {
  26684. this.onPointerUp(evt, pickResult, type);
  26685. }
  26686. return this;
  26687. };
  26688. /**
  26689. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26690. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26691. * @returns true if the pointer was captured
  26692. */
  26693. Scene.prototype.isPointerCaptured = function (pointerId) {
  26694. if (pointerId === void 0) { pointerId = 0; }
  26695. return this._pointerCaptures[pointerId];
  26696. };
  26697. /** @hidden */
  26698. Scene.prototype._isPointerSwiping = function () {
  26699. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26700. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26701. };
  26702. /**
  26703. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26704. * @param attachUp defines if you want to attach events to pointerup
  26705. * @param attachDown defines if you want to attach events to pointerdown
  26706. * @param attachMove defines if you want to attach events to pointermove
  26707. */
  26708. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26709. var _this = this;
  26710. if (attachUp === void 0) { attachUp = true; }
  26711. if (attachDown === void 0) { attachDown = true; }
  26712. if (attachMove === void 0) { attachMove = true; }
  26713. this._initActionManager = function (act, clickInfo) {
  26714. if (!_this._meshPickProceed) {
  26715. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26716. _this._currentPickResult = pickResult;
  26717. if (pickResult) {
  26718. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26719. }
  26720. _this._meshPickProceed = true;
  26721. }
  26722. return act;
  26723. };
  26724. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26725. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26726. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26727. btn !== _this._previousButtonPressed) {
  26728. _this._doubleClickOccured = false;
  26729. clickInfo.singleClick = true;
  26730. clickInfo.ignore = false;
  26731. cb(clickInfo, _this._currentPickResult);
  26732. }
  26733. };
  26734. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26735. var clickInfo = new ClickInfo();
  26736. _this._currentPickResult = null;
  26737. var act = null;
  26738. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26739. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26740. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26741. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26742. act = _this._initActionManager(act, clickInfo);
  26743. if (act) {
  26744. checkPicking = act.hasPickTriggers;
  26745. }
  26746. }
  26747. if (checkPicking) {
  26748. var btn = evt.button;
  26749. clickInfo.hasSwiped = _this._isPointerSwiping();
  26750. if (!clickInfo.hasSwiped) {
  26751. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26752. if (!checkSingleClickImmediately) {
  26753. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26754. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26755. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26756. act = _this._initActionManager(act, clickInfo);
  26757. if (act) {
  26758. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26759. }
  26760. }
  26761. }
  26762. if (checkSingleClickImmediately) {
  26763. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26764. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26765. btn !== _this._previousButtonPressed) {
  26766. clickInfo.singleClick = true;
  26767. cb(clickInfo, _this._currentPickResult);
  26768. }
  26769. }
  26770. // at least one double click is required to be check and exclusive double click is enabled
  26771. else {
  26772. // wait that no double click has been raised during the double click delay
  26773. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26774. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26775. }
  26776. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26777. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26778. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26779. act = _this._initActionManager(act, clickInfo);
  26780. if (act) {
  26781. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26782. }
  26783. }
  26784. if (checkDoubleClick) {
  26785. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26786. if (btn === _this._previousButtonPressed &&
  26787. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26788. !_this._doubleClickOccured) {
  26789. // pointer has not moved for 2 clicks, it's a double click
  26790. if (!clickInfo.hasSwiped &&
  26791. !_this._isPointerSwiping()) {
  26792. _this._previousStartingPointerTime = 0;
  26793. _this._doubleClickOccured = true;
  26794. clickInfo.doubleClick = true;
  26795. clickInfo.ignore = false;
  26796. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26797. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26798. }
  26799. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26800. cb(clickInfo, _this._currentPickResult);
  26801. }
  26802. // if the two successive clicks are too far, it's just two simple clicks
  26803. else {
  26804. _this._doubleClickOccured = false;
  26805. _this._previousStartingPointerTime = _this._startingPointerTime;
  26806. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26807. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26808. _this._previousButtonPressed = btn;
  26809. if (Scene.ExclusiveDoubleClickMode) {
  26810. if (_this._previousDelayedSimpleClickTimeout) {
  26811. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26812. }
  26813. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26814. cb(clickInfo, _this._previousPickResult);
  26815. }
  26816. else {
  26817. cb(clickInfo, _this._currentPickResult);
  26818. }
  26819. }
  26820. }
  26821. // just the first click of the double has been raised
  26822. else {
  26823. _this._doubleClickOccured = false;
  26824. _this._previousStartingPointerTime = _this._startingPointerTime;
  26825. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26826. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26827. _this._previousButtonPressed = btn;
  26828. }
  26829. }
  26830. }
  26831. }
  26832. clickInfo.ignore = true;
  26833. cb(clickInfo, _this._currentPickResult);
  26834. };
  26835. this._onPointerMove = function (evt) {
  26836. _this._updatePointerPosition(evt);
  26837. // PreObservable support
  26838. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26839. return;
  26840. }
  26841. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26842. return;
  26843. }
  26844. if (!_this.pointerMovePredicate) {
  26845. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26846. }
  26847. // Meshes
  26848. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26849. _this._processPointerMove(pickResult, evt);
  26850. };
  26851. this._onPointerDown = function (evt) {
  26852. _this._totalPointersPressed++;
  26853. _this._pickedDownMesh = null;
  26854. _this._meshPickProceed = false;
  26855. _this._updatePointerPosition(evt);
  26856. if (_this.preventDefaultOnPointerDown && canvas) {
  26857. evt.preventDefault();
  26858. canvas.focus();
  26859. }
  26860. // PreObservable support
  26861. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26862. return;
  26863. }
  26864. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26865. return;
  26866. }
  26867. _this._pointerCaptures[evt.pointerId] = true;
  26868. _this._startingPointerPosition.x = _this._pointerX;
  26869. _this._startingPointerPosition.y = _this._pointerY;
  26870. _this._startingPointerTime = Date.now();
  26871. if (!_this.pointerDownPredicate) {
  26872. _this.pointerDownPredicate = function (mesh) {
  26873. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26874. };
  26875. }
  26876. // Meshes
  26877. _this._pickedDownMesh = null;
  26878. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26879. _this._processPointerDown(pickResult, evt);
  26880. };
  26881. this._onPointerUp = function (evt) {
  26882. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26883. return; // So we need to test it the pointer down was pressed before.
  26884. }
  26885. _this._totalPointersPressed--;
  26886. _this._pickedUpMesh = null;
  26887. _this._meshPickProceed = false;
  26888. _this._updatePointerPosition(evt);
  26889. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26890. // PreObservable support
  26891. if (_this.onPrePointerObservable.hasObservers()) {
  26892. if (!clickInfo.ignore) {
  26893. if (!clickInfo.hasSwiped) {
  26894. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26895. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26896. return;
  26897. }
  26898. }
  26899. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26900. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26901. return;
  26902. }
  26903. }
  26904. }
  26905. }
  26906. else {
  26907. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26908. return;
  26909. }
  26910. }
  26911. }
  26912. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26913. return;
  26914. }
  26915. _this._pointerCaptures[evt.pointerId] = false;
  26916. if (!_this.pointerUpPredicate) {
  26917. _this.pointerUpPredicate = function (mesh) {
  26918. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26919. };
  26920. }
  26921. // Meshes
  26922. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26923. _this._initActionManager(null, clickInfo);
  26924. }
  26925. if (!pickResult) {
  26926. pickResult = _this._currentPickResult;
  26927. }
  26928. _this._processPointerUp(pickResult, evt, clickInfo);
  26929. _this._previousPickResult = _this._currentPickResult;
  26930. });
  26931. };
  26932. this._onKeyDown = function (evt) {
  26933. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26934. if (_this.onPreKeyboardObservable.hasObservers()) {
  26935. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26936. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26937. if (pi.skipOnPointerObservable) {
  26938. return;
  26939. }
  26940. }
  26941. if (_this.onKeyboardObservable.hasObservers()) {
  26942. var pi = new BABYLON.KeyboardInfo(type, evt);
  26943. _this.onKeyboardObservable.notifyObservers(pi, type);
  26944. }
  26945. if (_this.actionManager) {
  26946. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26947. }
  26948. };
  26949. this._onKeyUp = function (evt) {
  26950. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26951. if (_this.onPreKeyboardObservable.hasObservers()) {
  26952. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26953. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26954. if (pi.skipOnPointerObservable) {
  26955. return;
  26956. }
  26957. }
  26958. if (_this.onKeyboardObservable.hasObservers()) {
  26959. var pi = new BABYLON.KeyboardInfo(type, evt);
  26960. _this.onKeyboardObservable.notifyObservers(pi, type);
  26961. }
  26962. if (_this.actionManager) {
  26963. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26964. }
  26965. };
  26966. var engine = this.getEngine();
  26967. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26968. if (!canvas) {
  26969. return;
  26970. }
  26971. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26972. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26973. });
  26974. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26975. if (!canvas) {
  26976. return;
  26977. }
  26978. canvas.removeEventListener("keydown", _this._onKeyDown);
  26979. canvas.removeEventListener("keyup", _this._onKeyUp);
  26980. });
  26981. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26982. var canvas = this._engine.getRenderingCanvas();
  26983. if (!canvas) {
  26984. return;
  26985. }
  26986. if (attachMove) {
  26987. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26988. // Wheel
  26989. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26990. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26991. }
  26992. if (attachDown) {
  26993. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26994. }
  26995. if (attachUp) {
  26996. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26997. }
  26998. canvas.tabIndex = 1;
  26999. };
  27000. /** Detaches all event handlers*/
  27001. Scene.prototype.detachControl = function () {
  27002. var engine = this.getEngine();
  27003. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27004. var canvas = engine.getRenderingCanvas();
  27005. if (!canvas) {
  27006. return;
  27007. }
  27008. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27009. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27010. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27011. if (this._onCanvasBlurObserver) {
  27012. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27013. }
  27014. if (this._onCanvasFocusObserver) {
  27015. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27016. }
  27017. // Wheel
  27018. canvas.removeEventListener('mousewheel', this._onPointerMove);
  27019. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  27020. // Keyboard
  27021. canvas.removeEventListener("keydown", this._onKeyDown);
  27022. canvas.removeEventListener("keyup", this._onKeyUp);
  27023. // Observables
  27024. this.onKeyboardObservable.clear();
  27025. this.onPreKeyboardObservable.clear();
  27026. this.onPointerObservable.clear();
  27027. this.onPrePointerObservable.clear();
  27028. };
  27029. /**
  27030. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27031. * Delay loaded resources are not taking in account
  27032. * @return true if all required resources are ready
  27033. */
  27034. Scene.prototype.isReady = function () {
  27035. if (this._isDisposed) {
  27036. return false;
  27037. }
  27038. if (this._pendingData.length > 0) {
  27039. return false;
  27040. }
  27041. var index;
  27042. var engine = this.getEngine();
  27043. // Geometries
  27044. for (index = 0; index < this.geometries.length; index++) {
  27045. var geometry = this.geometries[index];
  27046. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27047. return false;
  27048. }
  27049. }
  27050. // Meshes
  27051. for (index = 0; index < this.meshes.length; index++) {
  27052. var mesh = this.meshes[index];
  27053. if (!mesh.isEnabled()) {
  27054. continue;
  27055. }
  27056. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27057. continue;
  27058. }
  27059. if (!mesh.isReady(true)) {
  27060. return false;
  27061. }
  27062. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27063. // Is Ready For Mesh
  27064. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27065. var step = _a[_i];
  27066. if (!step.action(mesh, hardwareInstancedRendering)) {
  27067. return false;
  27068. }
  27069. }
  27070. }
  27071. // Post-processes
  27072. if (this.activeCameras && this.activeCameras.length > 0) {
  27073. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27074. var camera = _c[_b];
  27075. if (!camera.isReady(true)) {
  27076. return false;
  27077. }
  27078. }
  27079. }
  27080. else if (this.activeCamera) {
  27081. if (!this.activeCamera.isReady(true)) {
  27082. return false;
  27083. }
  27084. }
  27085. // Particles
  27086. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27087. var particleSystem = _e[_d];
  27088. if (!particleSystem.isReady()) {
  27089. return false;
  27090. }
  27091. }
  27092. return true;
  27093. };
  27094. /** Resets all cached information relative to material (including effect and visibility) */
  27095. Scene.prototype.resetCachedMaterial = function () {
  27096. this._cachedMaterial = null;
  27097. this._cachedEffect = null;
  27098. this._cachedVisibility = null;
  27099. };
  27100. /**
  27101. * Registers a function to be called before every frame render
  27102. * @param func defines the function to register
  27103. */
  27104. Scene.prototype.registerBeforeRender = function (func) {
  27105. this.onBeforeRenderObservable.add(func);
  27106. };
  27107. /**
  27108. * Unregisters a function called before every frame render
  27109. * @param func defines the function to unregister
  27110. */
  27111. Scene.prototype.unregisterBeforeRender = function (func) {
  27112. this.onBeforeRenderObservable.removeCallback(func);
  27113. };
  27114. /**
  27115. * Registers a function to be called after every frame render
  27116. * @param func defines the function to register
  27117. */
  27118. Scene.prototype.registerAfterRender = function (func) {
  27119. this.onAfterRenderObservable.add(func);
  27120. };
  27121. /**
  27122. * Unregisters a function called after every frame render
  27123. * @param func defines the function to unregister
  27124. */
  27125. Scene.prototype.unregisterAfterRender = function (func) {
  27126. this.onAfterRenderObservable.removeCallback(func);
  27127. };
  27128. Scene.prototype._executeOnceBeforeRender = function (func) {
  27129. var _this = this;
  27130. var execFunc = function () {
  27131. func();
  27132. setTimeout(function () {
  27133. _this.unregisterBeforeRender(execFunc);
  27134. });
  27135. };
  27136. this.registerBeforeRender(execFunc);
  27137. };
  27138. /**
  27139. * The provided function will run before render once and will be disposed afterwards.
  27140. * A timeout delay can be provided so that the function will be executed in N ms.
  27141. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27142. * @param func The function to be executed.
  27143. * @param timeout optional delay in ms
  27144. */
  27145. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27146. var _this = this;
  27147. if (timeout !== undefined) {
  27148. setTimeout(function () {
  27149. _this._executeOnceBeforeRender(func);
  27150. }, timeout);
  27151. }
  27152. else {
  27153. this._executeOnceBeforeRender(func);
  27154. }
  27155. };
  27156. /** @hidden */
  27157. Scene.prototype._addPendingData = function (data) {
  27158. this._pendingData.push(data);
  27159. };
  27160. /** @hidden */
  27161. Scene.prototype._removePendingData = function (data) {
  27162. var wasLoading = this.isLoading;
  27163. var index = this._pendingData.indexOf(data);
  27164. if (index !== -1) {
  27165. this._pendingData.splice(index, 1);
  27166. }
  27167. if (wasLoading && !this.isLoading) {
  27168. this.onDataLoadedObservable.notifyObservers(this);
  27169. }
  27170. };
  27171. /**
  27172. * Returns the number of items waiting to be loaded
  27173. * @returns the number of items waiting to be loaded
  27174. */
  27175. Scene.prototype.getWaitingItemsCount = function () {
  27176. return this._pendingData.length;
  27177. };
  27178. Object.defineProperty(Scene.prototype, "isLoading", {
  27179. /**
  27180. * Returns a boolean indicating if the scene is still loading data
  27181. */
  27182. get: function () {
  27183. return this._pendingData.length > 0;
  27184. },
  27185. enumerable: true,
  27186. configurable: true
  27187. });
  27188. /**
  27189. * Registers a function to be executed when the scene is ready
  27190. * @param {Function} func - the function to be executed
  27191. */
  27192. Scene.prototype.executeWhenReady = function (func) {
  27193. var _this = this;
  27194. this.onReadyObservable.add(func);
  27195. if (this._executeWhenReadyTimeoutId !== -1) {
  27196. return;
  27197. }
  27198. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27199. _this._checkIsReady();
  27200. }, 150);
  27201. };
  27202. /**
  27203. * Returns a promise that resolves when the scene is ready
  27204. * @returns A promise that resolves when the scene is ready
  27205. */
  27206. Scene.prototype.whenReadyAsync = function () {
  27207. var _this = this;
  27208. return new Promise(function (resolve) {
  27209. _this.executeWhenReady(function () {
  27210. resolve();
  27211. });
  27212. });
  27213. };
  27214. /** @hidden */
  27215. Scene.prototype._checkIsReady = function () {
  27216. var _this = this;
  27217. this._registerTransientComponents();
  27218. if (this.isReady()) {
  27219. this.onReadyObservable.notifyObservers(this);
  27220. this.onReadyObservable.clear();
  27221. this._executeWhenReadyTimeoutId = -1;
  27222. return;
  27223. }
  27224. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27225. _this._checkIsReady();
  27226. }, 150);
  27227. };
  27228. // Animations
  27229. /**
  27230. * Will start the animation sequence of a given target
  27231. * @param target defines the target
  27232. * @param from defines from which frame should animation start
  27233. * @param to defines until which frame should animation run.
  27234. * @param weight defines the weight to apply to the animation (1.0 by default)
  27235. * @param loop defines if the animation loops
  27236. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27237. * @param onAnimationEnd defines the function to be executed when the animation ends
  27238. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27239. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27240. * @returns the animatable object created for this animation
  27241. */
  27242. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27243. if (weight === void 0) { weight = 1.0; }
  27244. if (speedRatio === void 0) { speedRatio = 1.0; }
  27245. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27246. returnedAnimatable.weight = weight;
  27247. return returnedAnimatable;
  27248. };
  27249. /**
  27250. * Will start the animation sequence of a given target
  27251. * @param target defines the target
  27252. * @param from defines from which frame should animation start
  27253. * @param to defines until which frame should animation run.
  27254. * @param loop defines if the animation loops
  27255. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27256. * @param onAnimationEnd defines the function to be executed when the animation ends
  27257. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27258. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27259. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27260. * @returns the animatable object created for this animation
  27261. */
  27262. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27263. if (speedRatio === void 0) { speedRatio = 1.0; }
  27264. if (stopCurrent === void 0) { stopCurrent = true; }
  27265. if (from > to && speedRatio > 0) {
  27266. speedRatio *= -1;
  27267. }
  27268. if (stopCurrent) {
  27269. this.stopAnimation(target, undefined, targetMask);
  27270. }
  27271. if (!animatable) {
  27272. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27273. }
  27274. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27275. // Local animations
  27276. if (target.animations && shouldRunTargetAnimations) {
  27277. animatable.appendAnimations(target, target.animations);
  27278. }
  27279. // Children animations
  27280. if (target.getAnimatables) {
  27281. var animatables = target.getAnimatables();
  27282. for (var index = 0; index < animatables.length; index++) {
  27283. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27284. }
  27285. }
  27286. animatable.reset();
  27287. return animatable;
  27288. };
  27289. /**
  27290. * Begin a new animation on a given node
  27291. * @param target defines the target where the animation will take place
  27292. * @param animations defines the list of animations to start
  27293. * @param from defines the initial value
  27294. * @param to defines the final value
  27295. * @param loop defines if you want animation to loop (off by default)
  27296. * @param speedRatio defines the speed ratio to apply to all animations
  27297. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27298. * @returns the list of created animatables
  27299. */
  27300. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27301. if (speedRatio === undefined) {
  27302. speedRatio = 1.0;
  27303. }
  27304. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27305. return animatable;
  27306. };
  27307. /**
  27308. * Begin a new animation on a given node and its hierarchy
  27309. * @param target defines the root node where the animation will take place
  27310. * @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.
  27311. * @param animations defines the list of animations to start
  27312. * @param from defines the initial value
  27313. * @param to defines the final value
  27314. * @param loop defines if you want animation to loop (off by default)
  27315. * @param speedRatio defines the speed ratio to apply to all animations
  27316. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27317. * @returns the list of animatables created for all nodes
  27318. */
  27319. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27320. var children = target.getDescendants(directDescendantsOnly);
  27321. var result = [];
  27322. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27323. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27324. var child = children_1[_i];
  27325. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27326. }
  27327. return result;
  27328. };
  27329. /**
  27330. * Gets the animatable associated with a specific target
  27331. * @param target defines the target of the animatable
  27332. * @returns the required animatable if found
  27333. */
  27334. Scene.prototype.getAnimatableByTarget = function (target) {
  27335. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27336. if (this._activeAnimatables[index].target === target) {
  27337. return this._activeAnimatables[index];
  27338. }
  27339. }
  27340. return null;
  27341. };
  27342. /**
  27343. * Gets all animatables associated with a given target
  27344. * @param target defines the target to look animatables for
  27345. * @returns an array of Animatables
  27346. */
  27347. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27348. var result = [];
  27349. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27350. if (this._activeAnimatables[index].target === target) {
  27351. result.push(this._activeAnimatables[index]);
  27352. }
  27353. }
  27354. return result;
  27355. };
  27356. Object.defineProperty(Scene.prototype, "animatables", {
  27357. /**
  27358. * Gets all animatable attached to the scene
  27359. */
  27360. get: function () {
  27361. return this._activeAnimatables;
  27362. },
  27363. enumerable: true,
  27364. configurable: true
  27365. });
  27366. /**
  27367. * Will stop the animation of the given target
  27368. * @param target - the target
  27369. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27370. * @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)
  27371. */
  27372. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27373. var animatables = this.getAllAnimatablesByTarget(target);
  27374. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27375. var animatable = animatables_1[_i];
  27376. animatable.stop(animationName, targetMask);
  27377. }
  27378. };
  27379. /**
  27380. * Stops and removes all animations that have been applied to the scene
  27381. */
  27382. Scene.prototype.stopAllAnimations = function () {
  27383. if (this._activeAnimatables) {
  27384. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27385. this._activeAnimatables[i].stop();
  27386. }
  27387. this._activeAnimatables = [];
  27388. }
  27389. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27390. var group = _a[_i];
  27391. group.stop();
  27392. }
  27393. };
  27394. Scene.prototype._animate = function () {
  27395. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27396. return;
  27397. }
  27398. // Getting time
  27399. var now = BABYLON.Tools.Now;
  27400. if (!this._animationTimeLast) {
  27401. if (this._pendingData.length > 0) {
  27402. return;
  27403. }
  27404. this._animationTimeLast = now;
  27405. }
  27406. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27407. this._animationTime += deltaTime;
  27408. this._animationTimeLast = now;
  27409. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27410. this._activeAnimatables[index]._animate(this._animationTime);
  27411. }
  27412. // Late animation bindings
  27413. this._processLateAnimationBindings();
  27414. };
  27415. /** @hidden */
  27416. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27417. var target = runtimeAnimation.target;
  27418. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27419. if (!target._lateAnimationHolders) {
  27420. target._lateAnimationHolders = {};
  27421. }
  27422. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27423. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27424. totalWeight: 0,
  27425. animations: [],
  27426. originalValue: originalValue
  27427. };
  27428. }
  27429. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27430. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27431. };
  27432. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27433. var normalizer = 1.0;
  27434. var finalPosition = BABYLON.Tmp.Vector3[0];
  27435. var finalScaling = BABYLON.Tmp.Vector3[1];
  27436. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27437. var startIndex = 0;
  27438. var originalAnimation = holder.animations[0];
  27439. var originalValue = holder.originalValue;
  27440. var scale = 1;
  27441. if (holder.totalWeight < 1.0) {
  27442. // We need to mix the original value in
  27443. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27444. scale = 1.0 - holder.totalWeight;
  27445. }
  27446. else {
  27447. startIndex = 1;
  27448. // We need to normalize the weights
  27449. normalizer = holder.totalWeight;
  27450. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27451. scale = originalAnimation.weight / normalizer;
  27452. if (scale == 1) {
  27453. return originalAnimation.currentValue;
  27454. }
  27455. }
  27456. finalScaling.scaleInPlace(scale);
  27457. finalPosition.scaleInPlace(scale);
  27458. finalQuaternion.scaleInPlace(scale);
  27459. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27460. var runtimeAnimation = holder.animations[animIndex];
  27461. var scale = runtimeAnimation.weight / normalizer;
  27462. var currentPosition = BABYLON.Tmp.Vector3[2];
  27463. var currentScaling = BABYLON.Tmp.Vector3[3];
  27464. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27465. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27466. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27467. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27468. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27469. }
  27470. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27471. return originalAnimation._workValue;
  27472. };
  27473. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27474. var originalAnimation = holder.animations[0];
  27475. var originalValue = holder.originalValue;
  27476. if (holder.animations.length === 1) {
  27477. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27478. return refQuaternion;
  27479. }
  27480. var normalizer = 1.0;
  27481. var quaternions;
  27482. var weights;
  27483. if (holder.totalWeight < 1.0) {
  27484. var scale = 1.0 - holder.totalWeight;
  27485. quaternions = [];
  27486. weights = [];
  27487. quaternions.push(originalValue);
  27488. weights.push(scale);
  27489. }
  27490. else {
  27491. if (holder.animations.length === 2) { // Slerp as soon as we can
  27492. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27493. return refQuaternion;
  27494. }
  27495. quaternions = [];
  27496. weights = [];
  27497. normalizer = holder.totalWeight;
  27498. }
  27499. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27500. var runtimeAnimation = holder.animations[animIndex];
  27501. quaternions.push(runtimeAnimation.currentValue);
  27502. weights.push(runtimeAnimation.weight / normalizer);
  27503. }
  27504. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27505. var cumulativeAmount = 0;
  27506. var cumulativeQuaternion = null;
  27507. for (var index = 0; index < quaternions.length;) {
  27508. if (!cumulativeQuaternion) {
  27509. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27510. cumulativeQuaternion = refQuaternion;
  27511. cumulativeAmount = weights[index] + weights[index + 1];
  27512. index += 2;
  27513. continue;
  27514. }
  27515. cumulativeAmount += weights[index];
  27516. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27517. index++;
  27518. }
  27519. return cumulativeQuaternion;
  27520. };
  27521. Scene.prototype._processLateAnimationBindings = function () {
  27522. if (!this._registeredForLateAnimationBindings.length) {
  27523. return;
  27524. }
  27525. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27526. var target = this._registeredForLateAnimationBindings.data[index];
  27527. for (var path in target._lateAnimationHolders) {
  27528. var holder = target._lateAnimationHolders[path];
  27529. var originalAnimation = holder.animations[0];
  27530. var originalValue = holder.originalValue;
  27531. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27532. var finalValue = target[path];
  27533. if (matrixDecomposeMode) {
  27534. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27535. }
  27536. else {
  27537. var quaternionMode = originalValue.w !== undefined;
  27538. if (quaternionMode) {
  27539. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27540. }
  27541. else {
  27542. var startIndex = 0;
  27543. var normalizer = 1.0;
  27544. if (holder.totalWeight < 1.0) {
  27545. // We need to mix the original value in
  27546. if (originalValue.scale) {
  27547. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27548. }
  27549. else {
  27550. finalValue = originalValue * (1.0 - holder.totalWeight);
  27551. }
  27552. }
  27553. else {
  27554. // We need to normalize the weights
  27555. normalizer = holder.totalWeight;
  27556. var scale_1 = originalAnimation.weight / normalizer;
  27557. if (scale_1 !== 1) {
  27558. if (originalAnimation.currentValue.scale) {
  27559. finalValue = originalAnimation.currentValue.scale(scale_1);
  27560. }
  27561. else {
  27562. finalValue = originalAnimation.currentValue * scale_1;
  27563. }
  27564. }
  27565. else {
  27566. finalValue = originalAnimation.currentValue;
  27567. }
  27568. startIndex = 1;
  27569. }
  27570. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27571. var runtimeAnimation = holder.animations[animIndex];
  27572. var scale = runtimeAnimation.weight / normalizer;
  27573. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27574. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27575. }
  27576. else {
  27577. finalValue += runtimeAnimation.currentValue * scale;
  27578. }
  27579. }
  27580. }
  27581. }
  27582. target[path] = finalValue;
  27583. }
  27584. target._lateAnimationHolders = {};
  27585. }
  27586. this._registeredForLateAnimationBindings.reset();
  27587. };
  27588. // Matrix
  27589. /** @hidden */
  27590. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27591. this._useAlternateCameraConfiguration = active;
  27592. };
  27593. /**
  27594. * Gets the current view matrix
  27595. * @returns a Matrix
  27596. */
  27597. Scene.prototype.getViewMatrix = function () {
  27598. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27599. };
  27600. /**
  27601. * Gets the current projection matrix
  27602. * @returns a Matrix
  27603. */
  27604. Scene.prototype.getProjectionMatrix = function () {
  27605. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27606. };
  27607. /**
  27608. * Gets the current transform matrix
  27609. * @returns a Matrix made of View * Projection
  27610. */
  27611. Scene.prototype.getTransformMatrix = function () {
  27612. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27613. };
  27614. /**
  27615. * Sets the current transform matrix
  27616. * @param view defines the View matrix to use
  27617. * @param projection defines the Projection matrix to use
  27618. */
  27619. Scene.prototype.setTransformMatrix = function (view, projection) {
  27620. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27621. return;
  27622. }
  27623. this._viewUpdateFlag = view.updateFlag;
  27624. this._projectionUpdateFlag = projection.updateFlag;
  27625. this._viewMatrix = view;
  27626. this._projectionMatrix = projection;
  27627. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27628. // Update frustum
  27629. if (!this._frustumPlanes) {
  27630. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27631. }
  27632. else {
  27633. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27634. }
  27635. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27636. var otherCamera = this.activeCamera._alternateCamera;
  27637. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27638. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27639. }
  27640. if (this._sceneUbo.useUbo) {
  27641. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27642. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27643. this._sceneUbo.update();
  27644. }
  27645. };
  27646. /** @hidden */
  27647. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27648. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27649. return;
  27650. }
  27651. this._alternateViewUpdateFlag = view.updateFlag;
  27652. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27653. this._alternateViewMatrix = view;
  27654. this._alternateProjectionMatrix = projection;
  27655. if (!this._alternateTransformMatrix) {
  27656. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27657. }
  27658. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27659. if (!this._alternateSceneUbo) {
  27660. this._createAlternateUbo();
  27661. }
  27662. if (this._alternateSceneUbo.useUbo) {
  27663. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27664. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27665. this._alternateSceneUbo.update();
  27666. }
  27667. };
  27668. /**
  27669. * Gets the uniform buffer used to store scene data
  27670. * @returns a UniformBuffer
  27671. */
  27672. Scene.prototype.getSceneUniformBuffer = function () {
  27673. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27674. };
  27675. /**
  27676. * Gets an unique (relatively to the current scene) Id
  27677. * @returns an unique number for the scene
  27678. */
  27679. Scene.prototype.getUniqueId = function () {
  27680. var result = Scene._uniqueIdCounter;
  27681. Scene._uniqueIdCounter++;
  27682. return result;
  27683. };
  27684. /**
  27685. * Add a mesh to the list of scene's meshes
  27686. * @param newMesh defines the mesh to add
  27687. * @param recursive if all child meshes should also be added to the scene
  27688. */
  27689. Scene.prototype.addMesh = function (newMesh, recursive) {
  27690. var _this = this;
  27691. if (recursive === void 0) { recursive = false; }
  27692. this.meshes.push(newMesh);
  27693. //notify the collision coordinator
  27694. if (this.collisionCoordinator) {
  27695. this.collisionCoordinator.onMeshAdded(newMesh);
  27696. }
  27697. newMesh._resyncLightSources();
  27698. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27699. if (recursive) {
  27700. newMesh.getChildMeshes().forEach(function (m) {
  27701. _this.addMesh(m);
  27702. });
  27703. }
  27704. };
  27705. /**
  27706. * Remove a mesh for the list of scene's meshes
  27707. * @param toRemove defines the mesh to remove
  27708. * @param recursive if all child meshes should also be removed from the scene
  27709. * @returns the index where the mesh was in the mesh list
  27710. */
  27711. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27712. var _this = this;
  27713. if (recursive === void 0) { recursive = false; }
  27714. var index = this.meshes.indexOf(toRemove);
  27715. if (index !== -1) {
  27716. // Remove from the scene if mesh found
  27717. this.meshes.splice(index, 1);
  27718. }
  27719. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27720. if (recursive) {
  27721. toRemove.getChildMeshes().forEach(function (m) {
  27722. _this.removeMesh(m);
  27723. });
  27724. }
  27725. return index;
  27726. };
  27727. /**
  27728. * Add a transform node to the list of scene's transform nodes
  27729. * @param newTransformNode defines the transform node to add
  27730. */
  27731. Scene.prototype.addTransformNode = function (newTransformNode) {
  27732. this.transformNodes.push(newTransformNode);
  27733. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27734. };
  27735. /**
  27736. * Remove a transform node for the list of scene's transform nodes
  27737. * @param toRemove defines the transform node to remove
  27738. * @returns the index where the transform node was in the transform node list
  27739. */
  27740. Scene.prototype.removeTransformNode = function (toRemove) {
  27741. var index = this.transformNodes.indexOf(toRemove);
  27742. if (index !== -1) {
  27743. // Remove from the scene if found
  27744. this.transformNodes.splice(index, 1);
  27745. }
  27746. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27747. return index;
  27748. };
  27749. /**
  27750. * Remove a skeleton for the list of scene's skeletons
  27751. * @param toRemove defines the skeleton to remove
  27752. * @returns the index where the skeleton was in the skeleton list
  27753. */
  27754. Scene.prototype.removeSkeleton = function (toRemove) {
  27755. var index = this.skeletons.indexOf(toRemove);
  27756. if (index !== -1) {
  27757. // Remove from the scene if found
  27758. this.skeletons.splice(index, 1);
  27759. }
  27760. return index;
  27761. };
  27762. /**
  27763. * Remove a morph target for the list of scene's morph targets
  27764. * @param toRemove defines the morph target to remove
  27765. * @returns the index where the morph target was in the morph target list
  27766. */
  27767. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27768. var index = this.morphTargetManagers.indexOf(toRemove);
  27769. if (index !== -1) {
  27770. // Remove from the scene if found
  27771. this.morphTargetManagers.splice(index, 1);
  27772. }
  27773. return index;
  27774. };
  27775. /**
  27776. * Remove a light for the list of scene's lights
  27777. * @param toRemove defines the light to remove
  27778. * @returns the index where the light was in the light list
  27779. */
  27780. Scene.prototype.removeLight = function (toRemove) {
  27781. var index = this.lights.indexOf(toRemove);
  27782. if (index !== -1) {
  27783. // Remove from meshes
  27784. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27785. var mesh = _a[_i];
  27786. mesh._removeLightSource(toRemove);
  27787. }
  27788. // Remove from the scene if mesh found
  27789. this.lights.splice(index, 1);
  27790. this.sortLightsByPriority();
  27791. }
  27792. this.onLightRemovedObservable.notifyObservers(toRemove);
  27793. return index;
  27794. };
  27795. /**
  27796. * Remove a camera for the list of scene's cameras
  27797. * @param toRemove defines the camera to remove
  27798. * @returns the index where the camera was in the camera list
  27799. */
  27800. Scene.prototype.removeCamera = function (toRemove) {
  27801. var index = this.cameras.indexOf(toRemove);
  27802. if (index !== -1) {
  27803. // Remove from the scene if mesh found
  27804. this.cameras.splice(index, 1);
  27805. }
  27806. // Remove from activeCameras
  27807. var index2 = this.activeCameras.indexOf(toRemove);
  27808. if (index2 !== -1) {
  27809. // Remove from the scene if mesh found
  27810. this.activeCameras.splice(index2, 1);
  27811. }
  27812. // Reset the activeCamera
  27813. if (this.activeCamera === toRemove) {
  27814. if (this.cameras.length > 0) {
  27815. this.activeCamera = this.cameras[0];
  27816. }
  27817. else {
  27818. this.activeCamera = null;
  27819. }
  27820. }
  27821. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27822. return index;
  27823. };
  27824. /**
  27825. * Remove a particle system for the list of scene's particle systems
  27826. * @param toRemove defines the particle system to remove
  27827. * @returns the index where the particle system was in the particle system list
  27828. */
  27829. Scene.prototype.removeParticleSystem = function (toRemove) {
  27830. var index = this.particleSystems.indexOf(toRemove);
  27831. if (index !== -1) {
  27832. this.particleSystems.splice(index, 1);
  27833. }
  27834. return index;
  27835. };
  27836. /**
  27837. * Remove a animation for the list of scene's animations
  27838. * @param toRemove defines the animation to remove
  27839. * @returns the index where the animation was in the animation list
  27840. */
  27841. Scene.prototype.removeAnimation = function (toRemove) {
  27842. var index = this.animations.indexOf(toRemove);
  27843. if (index !== -1) {
  27844. this.animations.splice(index, 1);
  27845. }
  27846. return index;
  27847. };
  27848. /**
  27849. * Removes the given animation group from this scene.
  27850. * @param toRemove The animation group to remove
  27851. * @returns The index of the removed animation group
  27852. */
  27853. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27854. var index = this.animationGroups.indexOf(toRemove);
  27855. if (index !== -1) {
  27856. this.animationGroups.splice(index, 1);
  27857. }
  27858. return index;
  27859. };
  27860. /**
  27861. * Removes the given multi-material from this scene.
  27862. * @param toRemove The multi-material to remove
  27863. * @returns The index of the removed multi-material
  27864. */
  27865. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27866. var index = this.multiMaterials.indexOf(toRemove);
  27867. if (index !== -1) {
  27868. this.multiMaterials.splice(index, 1);
  27869. }
  27870. return index;
  27871. };
  27872. /**
  27873. * Removes the given material from this scene.
  27874. * @param toRemove The material to remove
  27875. * @returns The index of the removed material
  27876. */
  27877. Scene.prototype.removeMaterial = function (toRemove) {
  27878. var index = this.materials.indexOf(toRemove);
  27879. if (index !== -1) {
  27880. this.materials.splice(index, 1);
  27881. }
  27882. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27883. return index;
  27884. };
  27885. /**
  27886. * Removes the given action manager from this scene.
  27887. * @param toRemove The action manager to remove
  27888. * @returns The index of the removed action manager
  27889. */
  27890. Scene.prototype.removeActionManager = function (toRemove) {
  27891. var index = this.actionManagers.indexOf(toRemove);
  27892. if (index !== -1) {
  27893. this.actionManagers.splice(index, 1);
  27894. }
  27895. return index;
  27896. };
  27897. /**
  27898. * Removes the given texture from this scene.
  27899. * @param toRemove The texture to remove
  27900. * @returns The index of the removed texture
  27901. */
  27902. Scene.prototype.removeTexture = function (toRemove) {
  27903. var index = this.textures.indexOf(toRemove);
  27904. if (index !== -1) {
  27905. this.textures.splice(index, 1);
  27906. }
  27907. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27908. return index;
  27909. };
  27910. /**
  27911. * Adds the given light to this scene
  27912. * @param newLight The light to add
  27913. */
  27914. Scene.prototype.addLight = function (newLight) {
  27915. this.lights.push(newLight);
  27916. this.sortLightsByPriority();
  27917. // Add light to all meshes (To support if the light is removed and then readded)
  27918. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27919. var mesh = _a[_i];
  27920. if (mesh._lightSources.indexOf(newLight) === -1) {
  27921. mesh._lightSources.push(newLight);
  27922. mesh._resyncLightSources();
  27923. }
  27924. }
  27925. this.onNewLightAddedObservable.notifyObservers(newLight);
  27926. };
  27927. /**
  27928. * Sorts the list list based on light priorities
  27929. */
  27930. Scene.prototype.sortLightsByPriority = function () {
  27931. if (this.requireLightSorting) {
  27932. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27933. }
  27934. };
  27935. /**
  27936. * Adds the given camera to this scene
  27937. * @param newCamera The camera to add
  27938. */
  27939. Scene.prototype.addCamera = function (newCamera) {
  27940. this.cameras.push(newCamera);
  27941. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27942. };
  27943. /**
  27944. * Adds the given skeleton to this scene
  27945. * @param newSkeleton The skeleton to add
  27946. */
  27947. Scene.prototype.addSkeleton = function (newSkeleton) {
  27948. this.skeletons.push(newSkeleton);
  27949. };
  27950. /**
  27951. * Adds the given particle system to this scene
  27952. * @param newParticleSystem The particle system to add
  27953. */
  27954. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27955. this.particleSystems.push(newParticleSystem);
  27956. };
  27957. /**
  27958. * Adds the given animation to this scene
  27959. * @param newAnimation The animation to add
  27960. */
  27961. Scene.prototype.addAnimation = function (newAnimation) {
  27962. this.animations.push(newAnimation);
  27963. };
  27964. /**
  27965. * Adds the given animation group to this scene.
  27966. * @param newAnimationGroup The animation group to add
  27967. */
  27968. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27969. this.animationGroups.push(newAnimationGroup);
  27970. };
  27971. /**
  27972. * Adds the given multi-material to this scene
  27973. * @param newMultiMaterial The multi-material to add
  27974. */
  27975. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27976. this.multiMaterials.push(newMultiMaterial);
  27977. };
  27978. /**
  27979. * Adds the given material to this scene
  27980. * @param newMaterial The material to add
  27981. */
  27982. Scene.prototype.addMaterial = function (newMaterial) {
  27983. this.materials.push(newMaterial);
  27984. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27985. };
  27986. /**
  27987. * Adds the given morph target to this scene
  27988. * @param newMorphTargetManager The morph target to add
  27989. */
  27990. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27991. this.morphTargetManagers.push(newMorphTargetManager);
  27992. };
  27993. /**
  27994. * Adds the given geometry to this scene
  27995. * @param newGeometry The geometry to add
  27996. */
  27997. Scene.prototype.addGeometry = function (newGeometry) {
  27998. this.geometries.push(newGeometry);
  27999. };
  28000. /**
  28001. * Adds the given action manager to this scene
  28002. * @param newActionManager The action manager to add
  28003. */
  28004. Scene.prototype.addActionManager = function (newActionManager) {
  28005. this.actionManagers.push(newActionManager);
  28006. };
  28007. /**
  28008. * Adds the given texture to this scene.
  28009. * @param newTexture The texture to add
  28010. */
  28011. Scene.prototype.addTexture = function (newTexture) {
  28012. this.textures.push(newTexture);
  28013. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28014. };
  28015. /**
  28016. * Switch active camera
  28017. * @param newCamera defines the new active camera
  28018. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28019. */
  28020. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28021. if (attachControl === void 0) { attachControl = true; }
  28022. var canvas = this._engine.getRenderingCanvas();
  28023. if (!canvas) {
  28024. return;
  28025. }
  28026. if (this.activeCamera) {
  28027. this.activeCamera.detachControl(canvas);
  28028. }
  28029. this.activeCamera = newCamera;
  28030. if (attachControl) {
  28031. newCamera.attachControl(canvas);
  28032. }
  28033. };
  28034. /**
  28035. * sets the active camera of the scene using its ID
  28036. * @param id defines the camera's ID
  28037. * @return the new active camera or null if none found.
  28038. */
  28039. Scene.prototype.setActiveCameraByID = function (id) {
  28040. var camera = this.getCameraByID(id);
  28041. if (camera) {
  28042. this.activeCamera = camera;
  28043. return camera;
  28044. }
  28045. return null;
  28046. };
  28047. /**
  28048. * sets the active camera of the scene using its name
  28049. * @param name defines the camera's name
  28050. * @returns the new active camera or null if none found.
  28051. */
  28052. Scene.prototype.setActiveCameraByName = function (name) {
  28053. var camera = this.getCameraByName(name);
  28054. if (camera) {
  28055. this.activeCamera = camera;
  28056. return camera;
  28057. }
  28058. return null;
  28059. };
  28060. /**
  28061. * get an animation group using its name
  28062. * @param name defines the material's name
  28063. * @return the animation group or null if none found.
  28064. */
  28065. Scene.prototype.getAnimationGroupByName = function (name) {
  28066. for (var index = 0; index < this.animationGroups.length; index++) {
  28067. if (this.animationGroups[index].name === name) {
  28068. return this.animationGroups[index];
  28069. }
  28070. }
  28071. return null;
  28072. };
  28073. /**
  28074. * get a material using its id
  28075. * @param id defines the material's ID
  28076. * @return the material or null if none found.
  28077. */
  28078. Scene.prototype.getMaterialByID = function (id) {
  28079. for (var index = 0; index < this.materials.length; index++) {
  28080. if (this.materials[index].id === id) {
  28081. return this.materials[index];
  28082. }
  28083. }
  28084. return null;
  28085. };
  28086. /**
  28087. * Gets a material using its name
  28088. * @param name defines the material's name
  28089. * @return the material or null if none found.
  28090. */
  28091. Scene.prototype.getMaterialByName = function (name) {
  28092. for (var index = 0; index < this.materials.length; index++) {
  28093. if (this.materials[index].name === name) {
  28094. return this.materials[index];
  28095. }
  28096. }
  28097. return null;
  28098. };
  28099. /**
  28100. * Gets a camera using its id
  28101. * @param id defines the id to look for
  28102. * @returns the camera or null if not found
  28103. */
  28104. Scene.prototype.getCameraByID = function (id) {
  28105. for (var index = 0; index < this.cameras.length; index++) {
  28106. if (this.cameras[index].id === id) {
  28107. return this.cameras[index];
  28108. }
  28109. }
  28110. return null;
  28111. };
  28112. /**
  28113. * Gets a camera using its unique id
  28114. * @param uniqueId defines the unique id to look for
  28115. * @returns the camera or null if not found
  28116. */
  28117. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28118. for (var index = 0; index < this.cameras.length; index++) {
  28119. if (this.cameras[index].uniqueId === uniqueId) {
  28120. return this.cameras[index];
  28121. }
  28122. }
  28123. return null;
  28124. };
  28125. /**
  28126. * Gets a camera using its name
  28127. * @param name defines the camera's name
  28128. * @return the camera or null if none found.
  28129. */
  28130. Scene.prototype.getCameraByName = function (name) {
  28131. for (var index = 0; index < this.cameras.length; index++) {
  28132. if (this.cameras[index].name === name) {
  28133. return this.cameras[index];
  28134. }
  28135. }
  28136. return null;
  28137. };
  28138. /**
  28139. * Gets a bone using its id
  28140. * @param id defines the bone's id
  28141. * @return the bone or null if not found
  28142. */
  28143. Scene.prototype.getBoneByID = function (id) {
  28144. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28145. var skeleton = this.skeletons[skeletonIndex];
  28146. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28147. if (skeleton.bones[boneIndex].id === id) {
  28148. return skeleton.bones[boneIndex];
  28149. }
  28150. }
  28151. }
  28152. return null;
  28153. };
  28154. /**
  28155. * Gets a bone using its id
  28156. * @param name defines the bone's name
  28157. * @return the bone or null if not found
  28158. */
  28159. Scene.prototype.getBoneByName = function (name) {
  28160. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28161. var skeleton = this.skeletons[skeletonIndex];
  28162. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28163. if (skeleton.bones[boneIndex].name === name) {
  28164. return skeleton.bones[boneIndex];
  28165. }
  28166. }
  28167. }
  28168. return null;
  28169. };
  28170. /**
  28171. * Gets a light node using its name
  28172. * @param name defines the the light's name
  28173. * @return the light or null if none found.
  28174. */
  28175. Scene.prototype.getLightByName = function (name) {
  28176. for (var index = 0; index < this.lights.length; index++) {
  28177. if (this.lights[index].name === name) {
  28178. return this.lights[index];
  28179. }
  28180. }
  28181. return null;
  28182. };
  28183. /**
  28184. * Gets a light node using its id
  28185. * @param id defines the light's id
  28186. * @return the light or null if none found.
  28187. */
  28188. Scene.prototype.getLightByID = function (id) {
  28189. for (var index = 0; index < this.lights.length; index++) {
  28190. if (this.lights[index].id === id) {
  28191. return this.lights[index];
  28192. }
  28193. }
  28194. return null;
  28195. };
  28196. /**
  28197. * Gets a light node using its scene-generated unique ID
  28198. * @param uniqueId defines the light's unique id
  28199. * @return the light or null if none found.
  28200. */
  28201. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28202. for (var index = 0; index < this.lights.length; index++) {
  28203. if (this.lights[index].uniqueId === uniqueId) {
  28204. return this.lights[index];
  28205. }
  28206. }
  28207. return null;
  28208. };
  28209. /**
  28210. * Gets a particle system by id
  28211. * @param id defines the particle system id
  28212. * @return the corresponding system or null if none found
  28213. */
  28214. Scene.prototype.getParticleSystemByID = function (id) {
  28215. for (var index = 0; index < this.particleSystems.length; index++) {
  28216. if (this.particleSystems[index].id === id) {
  28217. return this.particleSystems[index];
  28218. }
  28219. }
  28220. return null;
  28221. };
  28222. /**
  28223. * Gets a geometry using its ID
  28224. * @param id defines the geometry's id
  28225. * @return the geometry or null if none found.
  28226. */
  28227. Scene.prototype.getGeometryByID = function (id) {
  28228. for (var index = 0; index < this.geometries.length; index++) {
  28229. if (this.geometries[index].id === id) {
  28230. return this.geometries[index];
  28231. }
  28232. }
  28233. return null;
  28234. };
  28235. /**
  28236. * Add a new geometry to this scene
  28237. * @param geometry defines the geometry to be added to the scene.
  28238. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28239. * @return a boolean defining if the geometry was added or not
  28240. */
  28241. Scene.prototype.pushGeometry = function (geometry, force) {
  28242. if (!force && this.getGeometryByID(geometry.id)) {
  28243. return false;
  28244. }
  28245. this.geometries.push(geometry);
  28246. //notify the collision coordinator
  28247. if (this.collisionCoordinator) {
  28248. this.collisionCoordinator.onGeometryAdded(geometry);
  28249. }
  28250. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28251. return true;
  28252. };
  28253. /**
  28254. * Removes an existing geometry
  28255. * @param geometry defines the geometry to be removed from the scene
  28256. * @return a boolean defining if the geometry was removed or not
  28257. */
  28258. Scene.prototype.removeGeometry = function (geometry) {
  28259. var index = this.geometries.indexOf(geometry);
  28260. if (index > -1) {
  28261. this.geometries.splice(index, 1);
  28262. //notify the collision coordinator
  28263. if (this.collisionCoordinator) {
  28264. this.collisionCoordinator.onGeometryDeleted(geometry);
  28265. }
  28266. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28267. return true;
  28268. }
  28269. return false;
  28270. };
  28271. /**
  28272. * Gets the list of geometries attached to the scene
  28273. * @returns an array of Geometry
  28274. */
  28275. Scene.prototype.getGeometries = function () {
  28276. return this.geometries;
  28277. };
  28278. /**
  28279. * Gets the first added mesh found of a given ID
  28280. * @param id defines the id to search for
  28281. * @return the mesh found or null if not found at all
  28282. */
  28283. Scene.prototype.getMeshByID = function (id) {
  28284. for (var index = 0; index < this.meshes.length; index++) {
  28285. if (this.meshes[index].id === id) {
  28286. return this.meshes[index];
  28287. }
  28288. }
  28289. return null;
  28290. };
  28291. /**
  28292. * Gets a list of meshes using their id
  28293. * @param id defines the id to search for
  28294. * @returns a list of meshes
  28295. */
  28296. Scene.prototype.getMeshesByID = function (id) {
  28297. return this.meshes.filter(function (m) {
  28298. return m.id === id;
  28299. });
  28300. };
  28301. /**
  28302. * Gets the first added transform node found of a given ID
  28303. * @param id defines the id to search for
  28304. * @return the found transform node or null if not found at all.
  28305. */
  28306. Scene.prototype.getTransformNodeByID = function (id) {
  28307. for (var index = 0; index < this.transformNodes.length; index++) {
  28308. if (this.transformNodes[index].id === id) {
  28309. return this.transformNodes[index];
  28310. }
  28311. }
  28312. return null;
  28313. };
  28314. /**
  28315. * Gets a list of transform nodes using their id
  28316. * @param id defines the id to search for
  28317. * @returns a list of transform nodes
  28318. */
  28319. Scene.prototype.getTransformNodesByID = function (id) {
  28320. return this.transformNodes.filter(function (m) {
  28321. return m.id === id;
  28322. });
  28323. };
  28324. /**
  28325. * Gets a mesh with its auto-generated unique id
  28326. * @param uniqueId defines the unique id to search for
  28327. * @return the found mesh or null if not found at all.
  28328. */
  28329. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28330. for (var index = 0; index < this.meshes.length; index++) {
  28331. if (this.meshes[index].uniqueId === uniqueId) {
  28332. return this.meshes[index];
  28333. }
  28334. }
  28335. return null;
  28336. };
  28337. /**
  28338. * Gets a the last added mesh using a given id
  28339. * @param id defines the id to search for
  28340. * @return the found mesh or null if not found at all.
  28341. */
  28342. Scene.prototype.getLastMeshByID = function (id) {
  28343. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28344. if (this.meshes[index].id === id) {
  28345. return this.meshes[index];
  28346. }
  28347. }
  28348. return null;
  28349. };
  28350. /**
  28351. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28352. * @param id defines the id to search for
  28353. * @return the found node or null if not found at all
  28354. */
  28355. Scene.prototype.getLastEntryByID = function (id) {
  28356. var index;
  28357. for (index = this.meshes.length - 1; index >= 0; index--) {
  28358. if (this.meshes[index].id === id) {
  28359. return this.meshes[index];
  28360. }
  28361. }
  28362. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28363. if (this.transformNodes[index].id === id) {
  28364. return this.transformNodes[index];
  28365. }
  28366. }
  28367. for (index = this.cameras.length - 1; index >= 0; index--) {
  28368. if (this.cameras[index].id === id) {
  28369. return this.cameras[index];
  28370. }
  28371. }
  28372. for (index = this.lights.length - 1; index >= 0; index--) {
  28373. if (this.lights[index].id === id) {
  28374. return this.lights[index];
  28375. }
  28376. }
  28377. return null;
  28378. };
  28379. /**
  28380. * Gets a node (Mesh, Camera, Light) using a given id
  28381. * @param id defines the id to search for
  28382. * @return the found node or null if not found at all
  28383. */
  28384. Scene.prototype.getNodeByID = function (id) {
  28385. var mesh = this.getMeshByID(id);
  28386. if (mesh) {
  28387. return mesh;
  28388. }
  28389. var light = this.getLightByID(id);
  28390. if (light) {
  28391. return light;
  28392. }
  28393. var camera = this.getCameraByID(id);
  28394. if (camera) {
  28395. return camera;
  28396. }
  28397. var bone = this.getBoneByID(id);
  28398. return bone;
  28399. };
  28400. /**
  28401. * Gets a node (Mesh, Camera, Light) using a given name
  28402. * @param name defines the name to search for
  28403. * @return the found node or null if not found at all.
  28404. */
  28405. Scene.prototype.getNodeByName = function (name) {
  28406. var mesh = this.getMeshByName(name);
  28407. if (mesh) {
  28408. return mesh;
  28409. }
  28410. var light = this.getLightByName(name);
  28411. if (light) {
  28412. return light;
  28413. }
  28414. var camera = this.getCameraByName(name);
  28415. if (camera) {
  28416. return camera;
  28417. }
  28418. var bone = this.getBoneByName(name);
  28419. return bone;
  28420. };
  28421. /**
  28422. * Gets a mesh using a given name
  28423. * @param name defines the name to search for
  28424. * @return the found mesh or null if not found at all.
  28425. */
  28426. Scene.prototype.getMeshByName = function (name) {
  28427. for (var index = 0; index < this.meshes.length; index++) {
  28428. if (this.meshes[index].name === name) {
  28429. return this.meshes[index];
  28430. }
  28431. }
  28432. return null;
  28433. };
  28434. /**
  28435. * Gets a transform node using a given name
  28436. * @param name defines the name to search for
  28437. * @return the found transform node or null if not found at all.
  28438. */
  28439. Scene.prototype.getTransformNodeByName = function (name) {
  28440. for (var index = 0; index < this.transformNodes.length; index++) {
  28441. if (this.transformNodes[index].name === name) {
  28442. return this.transformNodes[index];
  28443. }
  28444. }
  28445. return null;
  28446. };
  28447. /**
  28448. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28449. * @param id defines the id to search for
  28450. * @return the found skeleton or null if not found at all.
  28451. */
  28452. Scene.prototype.getLastSkeletonByID = function (id) {
  28453. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28454. if (this.skeletons[index].id === id) {
  28455. return this.skeletons[index];
  28456. }
  28457. }
  28458. return null;
  28459. };
  28460. /**
  28461. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28462. * @param id defines the id to search for
  28463. * @return the found skeleton or null if not found at all.
  28464. */
  28465. Scene.prototype.getSkeletonById = function (id) {
  28466. for (var index = 0; index < this.skeletons.length; index++) {
  28467. if (this.skeletons[index].id === id) {
  28468. return this.skeletons[index];
  28469. }
  28470. }
  28471. return null;
  28472. };
  28473. /**
  28474. * Gets a skeleton using a given name
  28475. * @param name defines the name to search for
  28476. * @return the found skeleton or null if not found at all.
  28477. */
  28478. Scene.prototype.getSkeletonByName = function (name) {
  28479. for (var index = 0; index < this.skeletons.length; index++) {
  28480. if (this.skeletons[index].name === name) {
  28481. return this.skeletons[index];
  28482. }
  28483. }
  28484. return null;
  28485. };
  28486. /**
  28487. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28488. * @param id defines the id to search for
  28489. * @return the found morph target manager or null if not found at all.
  28490. */
  28491. Scene.prototype.getMorphTargetManagerById = function (id) {
  28492. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28493. if (this.morphTargetManagers[index].uniqueId === id) {
  28494. return this.morphTargetManagers[index];
  28495. }
  28496. }
  28497. return null;
  28498. };
  28499. /**
  28500. * Gets a boolean indicating if the given mesh is active
  28501. * @param mesh defines the mesh to look for
  28502. * @returns true if the mesh is in the active list
  28503. */
  28504. Scene.prototype.isActiveMesh = function (mesh) {
  28505. return (this._activeMeshes.indexOf(mesh) !== -1);
  28506. };
  28507. Object.defineProperty(Scene.prototype, "uid", {
  28508. /**
  28509. * Return a unique id as a string which can serve as an identifier for the scene
  28510. */
  28511. get: function () {
  28512. if (!this._uid) {
  28513. this._uid = BABYLON.Tools.RandomId();
  28514. }
  28515. return this._uid;
  28516. },
  28517. enumerable: true,
  28518. configurable: true
  28519. });
  28520. /**
  28521. * Add an externaly attached data from its key.
  28522. * This method call will fail and return false, if such key already exists.
  28523. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28524. * @param key the unique key that identifies the data
  28525. * @param data the data object to associate to the key for this Engine instance
  28526. * @return true if no such key were already present and the data was added successfully, false otherwise
  28527. */
  28528. Scene.prototype.addExternalData = function (key, data) {
  28529. if (!this._externalData) {
  28530. this._externalData = new BABYLON.StringDictionary();
  28531. }
  28532. return this._externalData.add(key, data);
  28533. };
  28534. /**
  28535. * Get an externaly attached data from its key
  28536. * @param key the unique key that identifies the data
  28537. * @return the associated data, if present (can be null), or undefined if not present
  28538. */
  28539. Scene.prototype.getExternalData = function (key) {
  28540. if (!this._externalData) {
  28541. return null;
  28542. }
  28543. return this._externalData.get(key);
  28544. };
  28545. /**
  28546. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28547. * @param key the unique key that identifies the data
  28548. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28549. * @return the associated data, can be null if the factory returned null.
  28550. */
  28551. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28552. if (!this._externalData) {
  28553. this._externalData = new BABYLON.StringDictionary();
  28554. }
  28555. return this._externalData.getOrAddWithFactory(key, factory);
  28556. };
  28557. /**
  28558. * Remove an externaly attached data from the Engine instance
  28559. * @param key the unique key that identifies the data
  28560. * @return true if the data was successfully removed, false if it doesn't exist
  28561. */
  28562. Scene.prototype.removeExternalData = function (key) {
  28563. return this._externalData.remove(key);
  28564. };
  28565. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28566. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28567. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28568. var step = _a[_i];
  28569. step.action(mesh, subMesh);
  28570. }
  28571. var material = subMesh.getMaterial();
  28572. if (material !== null && material !== undefined) {
  28573. // Render targets
  28574. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28575. if (this._processedMaterials.indexOf(material) === -1) {
  28576. this._processedMaterials.push(material);
  28577. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28578. }
  28579. }
  28580. // Dispatch
  28581. this._activeIndices.addCount(subMesh.indexCount, false);
  28582. this._renderingManager.dispatch(subMesh, mesh, material);
  28583. }
  28584. }
  28585. };
  28586. /**
  28587. * Clear the processed materials smart array preventing retention point in material dispose.
  28588. */
  28589. Scene.prototype.freeProcessedMaterials = function () {
  28590. this._processedMaterials.dispose();
  28591. };
  28592. /**
  28593. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28594. */
  28595. Scene.prototype.freeActiveMeshes = function () {
  28596. this._activeMeshes.dispose();
  28597. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28598. this.activeCamera._activeMeshes.dispose();
  28599. }
  28600. if (this.activeCameras) {
  28601. for (var i = 0; i < this.activeCameras.length; i++) {
  28602. var activeCamera = this.activeCameras[i];
  28603. if (activeCamera && activeCamera._activeMeshes) {
  28604. activeCamera._activeMeshes.dispose();
  28605. }
  28606. }
  28607. }
  28608. };
  28609. /**
  28610. * Clear the info related to rendering groups preventing retention points during dispose.
  28611. */
  28612. Scene.prototype.freeRenderingGroups = function () {
  28613. if (this._renderingManager) {
  28614. this._renderingManager.freeRenderingGroups();
  28615. }
  28616. if (this.textures) {
  28617. for (var i = 0; i < this.textures.length; i++) {
  28618. var texture = this.textures[i];
  28619. if (texture && texture.renderList) {
  28620. texture.freeRenderingGroups();
  28621. }
  28622. }
  28623. }
  28624. };
  28625. /** @hidden */
  28626. Scene.prototype._isInIntermediateRendering = function () {
  28627. return this._intermediateRendering;
  28628. };
  28629. /**
  28630. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28631. * @returns the current scene
  28632. */
  28633. Scene.prototype.freezeActiveMeshes = function () {
  28634. if (!this.activeCamera) {
  28635. return this;
  28636. }
  28637. if (!this._frustumPlanes) {
  28638. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28639. }
  28640. this._evaluateActiveMeshes();
  28641. this._activeMeshesFrozen = true;
  28642. return this;
  28643. };
  28644. /**
  28645. * Use this function to restart evaluating active meshes on every frame
  28646. * @returns the current scene
  28647. */
  28648. Scene.prototype.unfreezeActiveMeshes = function () {
  28649. this._activeMeshesFrozen = false;
  28650. return this;
  28651. };
  28652. Scene.prototype._evaluateActiveMeshes = function () {
  28653. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28654. return;
  28655. }
  28656. if (!this.activeCamera) {
  28657. return;
  28658. }
  28659. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28660. this.activeCamera._activeMeshes.reset();
  28661. this._activeMeshes.reset();
  28662. this._renderingManager.reset();
  28663. this._processedMaterials.reset();
  28664. this._activeParticleSystems.reset();
  28665. this._activeSkeletons.reset();
  28666. this._softwareSkinnedMeshes.reset();
  28667. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28668. var step = _a[_i];
  28669. step.action();
  28670. }
  28671. // Determine mesh candidates
  28672. var meshes = this.getActiveMeshCandidates();
  28673. // Check each mesh
  28674. var len = meshes.length;
  28675. for (var i = 0; i < len; i++) {
  28676. var mesh = meshes.data[i];
  28677. if (mesh.isBlocked) {
  28678. continue;
  28679. }
  28680. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28681. if (!mesh.isReady() || !mesh.isEnabled()) {
  28682. continue;
  28683. }
  28684. mesh.computeWorldMatrix();
  28685. // Intersections
  28686. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28687. this._meshesForIntersections.pushNoDuplicate(mesh);
  28688. }
  28689. // Switch to current LOD
  28690. var meshLOD = mesh.getLOD(this.activeCamera);
  28691. if (meshLOD === undefined || meshLOD === null) {
  28692. continue;
  28693. }
  28694. mesh._preActivate();
  28695. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28696. this._activeMeshes.push(mesh);
  28697. this.activeCamera._activeMeshes.push(mesh);
  28698. mesh._activate(this._renderId);
  28699. if (meshLOD !== mesh) {
  28700. meshLOD._activate(this._renderId);
  28701. }
  28702. this._activeMesh(mesh, meshLOD);
  28703. }
  28704. }
  28705. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28706. // Particle systems
  28707. if (this.particlesEnabled) {
  28708. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28709. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28710. var particleSystem = this.particleSystems[particleIndex];
  28711. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28712. continue;
  28713. }
  28714. var emitter = particleSystem.emitter;
  28715. if (!emitter.position || emitter.isEnabled()) {
  28716. this._activeParticleSystems.push(particleSystem);
  28717. particleSystem.animate();
  28718. this._renderingManager.dispatchParticles(particleSystem);
  28719. }
  28720. }
  28721. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28722. }
  28723. };
  28724. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28725. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28726. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28727. mesh.skeleton.prepare();
  28728. }
  28729. if (!mesh.computeBonesUsingShaders) {
  28730. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28731. }
  28732. }
  28733. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28734. var step = _a[_i];
  28735. step.action(sourceMesh, mesh);
  28736. }
  28737. if (mesh !== undefined && mesh !== null
  28738. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28739. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28740. var len = subMeshes.length;
  28741. for (var i = 0; i < len; i++) {
  28742. var subMesh = subMeshes.data[i];
  28743. this._evaluateSubMesh(subMesh, mesh);
  28744. }
  28745. }
  28746. };
  28747. /**
  28748. * Update the transform matrix to update from the current active camera
  28749. * @param force defines a boolean used to force the update even if cache is up to date
  28750. */
  28751. Scene.prototype.updateTransformMatrix = function (force) {
  28752. if (!this.activeCamera) {
  28753. return;
  28754. }
  28755. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28756. };
  28757. /**
  28758. * 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)
  28759. * @param alternateCamera defines the camera to use
  28760. */
  28761. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28762. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28763. };
  28764. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28765. if (camera && camera._skipRendering) {
  28766. return;
  28767. }
  28768. var engine = this._engine;
  28769. this.activeCamera = camera;
  28770. if (!this.activeCamera) {
  28771. throw new Error("Active camera not set");
  28772. }
  28773. // Viewport
  28774. engine.setViewport(this.activeCamera.viewport);
  28775. // Camera
  28776. this.resetCachedMaterial();
  28777. this._renderId++;
  28778. this.updateTransformMatrix();
  28779. if (camera._alternateCamera) {
  28780. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28781. this._alternateRendering = true;
  28782. }
  28783. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28784. // Meshes
  28785. this._evaluateActiveMeshes();
  28786. // Software skinning
  28787. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28788. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28789. mesh.applySkeleton(mesh.skeleton);
  28790. }
  28791. // Render targets
  28792. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28793. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28794. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28795. }
  28796. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28797. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28798. }
  28799. // Collects render targets from external components.
  28800. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28801. var step = _a[_i];
  28802. step.action(this._renderTargets);
  28803. }
  28804. if (this.renderTargetsEnabled) {
  28805. this._intermediateRendering = true;
  28806. if (this._renderTargets.length > 0) {
  28807. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28808. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28809. var renderTarget = this._renderTargets.data[renderIndex];
  28810. if (renderTarget._shouldRender()) {
  28811. this._renderId++;
  28812. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28813. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28814. }
  28815. }
  28816. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28817. this._renderId++;
  28818. }
  28819. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28820. var step = _c[_b];
  28821. step.action(this.activeCamera);
  28822. }
  28823. this._intermediateRendering = false;
  28824. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28825. }
  28826. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28827. // Prepare Frame
  28828. if (this.postProcessManager) {
  28829. this.postProcessManager._prepareFrame();
  28830. }
  28831. // Before Camera Draw
  28832. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28833. var step = _e[_d];
  28834. step.action(this.activeCamera);
  28835. }
  28836. // Render
  28837. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28838. this._renderingManager.render(null, null, true, true);
  28839. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28840. // After Camera Draw
  28841. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28842. var step = _g[_f];
  28843. step.action(this.activeCamera);
  28844. }
  28845. // Finalize frame
  28846. if (this.postProcessManager) {
  28847. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28848. }
  28849. // Reset some special arrays
  28850. this._renderTargets.reset();
  28851. this._alternateRendering = false;
  28852. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28853. };
  28854. Scene.prototype._processSubCameras = function (camera) {
  28855. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28856. this._renderForCamera(camera);
  28857. return;
  28858. }
  28859. // rig cameras
  28860. for (var index = 0; index < camera._rigCameras.length; index++) {
  28861. this._renderForCamera(camera._rigCameras[index], camera);
  28862. }
  28863. this.activeCamera = camera;
  28864. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28865. };
  28866. Scene.prototype._checkIntersections = function () {
  28867. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28868. var sourceMesh = this._meshesForIntersections.data[index];
  28869. if (!sourceMesh.actionManager) {
  28870. continue;
  28871. }
  28872. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28873. var action = sourceMesh.actionManager.actions[actionIndex];
  28874. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28875. var parameters = action.getTriggerParameter();
  28876. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28877. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28878. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28879. if (areIntersecting && currentIntersectionInProgress === -1) {
  28880. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28881. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28882. sourceMesh._intersectionsInProgress.push(otherMesh);
  28883. }
  28884. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28885. sourceMesh._intersectionsInProgress.push(otherMesh);
  28886. }
  28887. }
  28888. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28889. //They intersected, and now they don't.
  28890. //is this trigger an exit trigger? execute an event.
  28891. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28892. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28893. }
  28894. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28895. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28896. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28897. return otherMesh === parameterMesh;
  28898. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28899. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28900. }
  28901. }
  28902. }
  28903. }
  28904. }
  28905. };
  28906. /** @hidden */
  28907. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28908. // Do nothing. Code will be replaced if physics engine component is referenced
  28909. };
  28910. /**
  28911. * Render the scene
  28912. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28913. */
  28914. Scene.prototype.render = function (updateCameras) {
  28915. if (updateCameras === void 0) { updateCameras = true; }
  28916. if (this.isDisposed) {
  28917. return;
  28918. }
  28919. this._frameId++;
  28920. // Register components that have been associated lately to the scene.
  28921. this._registerTransientComponents();
  28922. this._activeParticles.fetchNewFrame();
  28923. this._totalVertices.fetchNewFrame();
  28924. this._activeIndices.fetchNewFrame();
  28925. this._activeBones.fetchNewFrame();
  28926. this._meshesForIntersections.reset();
  28927. this.resetCachedMaterial();
  28928. this.onBeforeAnimationsObservable.notifyObservers(this);
  28929. // Actions
  28930. if (this.actionManager) {
  28931. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28932. }
  28933. if (this._engine.isDeterministicLockStep()) {
  28934. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28935. var defaultFPS = (60.0 / 1000.0);
  28936. var defaultFrameTime = this.getDeterministicFrameTime();
  28937. var stepsTaken = 0;
  28938. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28939. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28940. internalSteps = Math.min(internalSteps, maxSubSteps);
  28941. do {
  28942. this.onBeforeStepObservable.notifyObservers(this);
  28943. // Animations
  28944. this._animationRatio = defaultFrameTime * defaultFPS;
  28945. this._animate();
  28946. this.onAfterAnimationsObservable.notifyObservers(this);
  28947. // Physics
  28948. this._advancePhysicsEngineStep(defaultFrameTime);
  28949. this.onAfterStepObservable.notifyObservers(this);
  28950. this._currentStepId++;
  28951. stepsTaken++;
  28952. deltaTime -= defaultFrameTime;
  28953. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28954. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28955. }
  28956. else {
  28957. // Animations
  28958. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28959. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28960. this._animate();
  28961. this.onAfterAnimationsObservable.notifyObservers(this);
  28962. // Physics
  28963. this._advancePhysicsEngineStep(deltaTime);
  28964. }
  28965. // Before camera update steps
  28966. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28967. var step = _a[_i];
  28968. step.action();
  28969. }
  28970. // Update Cameras
  28971. if (updateCameras) {
  28972. if (this.activeCameras.length > 0) {
  28973. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28974. var camera = this.activeCameras[cameraIndex];
  28975. camera.update();
  28976. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28977. // rig cameras
  28978. for (var index = 0; index < camera._rigCameras.length; index++) {
  28979. camera._rigCameras[index].update();
  28980. }
  28981. }
  28982. }
  28983. }
  28984. else if (this.activeCamera) {
  28985. this.activeCamera.update();
  28986. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28987. // rig cameras
  28988. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28989. this.activeCamera._rigCameras[index].update();
  28990. }
  28991. }
  28992. }
  28993. }
  28994. // Before render
  28995. this.onBeforeRenderObservable.notifyObservers(this);
  28996. // Customs render targets
  28997. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28998. var engine = this.getEngine();
  28999. var currentActiveCamera = this.activeCamera;
  29000. if (this.renderTargetsEnabled) {
  29001. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29002. this._intermediateRendering = true;
  29003. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29004. var renderTarget = this.customRenderTargets[customIndex];
  29005. if (renderTarget._shouldRender()) {
  29006. this._renderId++;
  29007. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29008. if (!this.activeCamera) {
  29009. throw new Error("Active camera not set");
  29010. }
  29011. // Viewport
  29012. engine.setViewport(this.activeCamera.viewport);
  29013. // Camera
  29014. this.updateTransformMatrix();
  29015. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29016. }
  29017. }
  29018. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29019. this._intermediateRendering = false;
  29020. this._renderId++;
  29021. }
  29022. // Restore back buffer
  29023. if (this.customRenderTargets.length > 0) {
  29024. engine.restoreDefaultFramebuffer();
  29025. }
  29026. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29027. this.activeCamera = currentActiveCamera;
  29028. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29029. var step = _c[_b];
  29030. step.action();
  29031. }
  29032. // Clear
  29033. if (this.autoClearDepthAndStencil || this.autoClear) {
  29034. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29035. }
  29036. // Collects render targets from external components.
  29037. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29038. var step = _e[_d];
  29039. step.action(this._renderTargets);
  29040. }
  29041. // Multi-cameras?
  29042. if (this.activeCameras.length > 0) {
  29043. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29044. if (cameraIndex > 0) {
  29045. this._engine.clear(null, false, true, true);
  29046. }
  29047. this._processSubCameras(this.activeCameras[cameraIndex]);
  29048. }
  29049. }
  29050. else {
  29051. if (!this.activeCamera) {
  29052. throw new Error("No camera defined");
  29053. }
  29054. this._processSubCameras(this.activeCamera);
  29055. }
  29056. // Intersection checks
  29057. this._checkIntersections();
  29058. // Executes the after render stage actions.
  29059. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29060. var step = _g[_f];
  29061. step.action();
  29062. }
  29063. // After render
  29064. if (this.afterRender) {
  29065. this.afterRender();
  29066. }
  29067. this.onAfterRenderObservable.notifyObservers(this);
  29068. // Cleaning
  29069. if (this._toBeDisposed.length) {
  29070. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29071. var data = this._toBeDisposed[index];
  29072. if (data) {
  29073. data.dispose();
  29074. }
  29075. }
  29076. this._toBeDisposed = [];
  29077. }
  29078. if (this.dumpNextRenderTargets) {
  29079. this.dumpNextRenderTargets = false;
  29080. }
  29081. this._activeBones.addCount(0, true);
  29082. this._activeIndices.addCount(0, true);
  29083. this._activeParticles.addCount(0, true);
  29084. };
  29085. /**
  29086. * Freeze all materials
  29087. * A frozen material will not be updatable but should be faster to render
  29088. */
  29089. Scene.prototype.freezeMaterials = function () {
  29090. for (var i = 0; i < this.materials.length; i++) {
  29091. this.materials[i].freeze();
  29092. }
  29093. };
  29094. /**
  29095. * Unfreeze all materials
  29096. * A frozen material will not be updatable but should be faster to render
  29097. */
  29098. Scene.prototype.unfreezeMaterials = function () {
  29099. for (var i = 0; i < this.materials.length; i++) {
  29100. this.materials[i].unfreeze();
  29101. }
  29102. };
  29103. /**
  29104. * Releases all held ressources
  29105. */
  29106. Scene.prototype.dispose = function () {
  29107. this.beforeRender = null;
  29108. this.afterRender = null;
  29109. this.skeletons = [];
  29110. this.morphTargetManagers = [];
  29111. this._transientComponents = [];
  29112. this._isReadyForMeshStage.clear();
  29113. this._beforeEvaluateActiveMeshStage.clear();
  29114. this._evaluateSubMeshStage.clear();
  29115. this._activeMeshStage.clear();
  29116. this._cameraDrawRenderTargetStage.clear();
  29117. this._beforeCameraDrawStage.clear();
  29118. this._beforeRenderingGroupDrawStage.clear();
  29119. this._beforeRenderingMeshStage.clear();
  29120. this._afterRenderingMeshStage.clear();
  29121. this._afterRenderingGroupDrawStage.clear();
  29122. this._afterCameraDrawStage.clear();
  29123. this._afterRenderStage.clear();
  29124. this._beforeCameraUpdateStage.clear();
  29125. this._beforeClearStage.clear();
  29126. this._gatherRenderTargetsStage.clear();
  29127. this._gatherActiveCameraRenderTargetsStage.clear();
  29128. this._pointerMoveStage.clear();
  29129. this._pointerDownStage.clear();
  29130. this._pointerUpStage.clear();
  29131. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29132. var component = _a[_i];
  29133. component.dispose();
  29134. }
  29135. this.importedMeshesFiles = new Array();
  29136. this.stopAllAnimations();
  29137. this.resetCachedMaterial();
  29138. // Smart arrays
  29139. if (this.activeCamera) {
  29140. this.activeCamera._activeMeshes.dispose();
  29141. this.activeCamera = null;
  29142. }
  29143. this._activeMeshes.dispose();
  29144. this._renderingManager.dispose();
  29145. this._processedMaterials.dispose();
  29146. this._activeParticleSystems.dispose();
  29147. this._activeSkeletons.dispose();
  29148. this._softwareSkinnedMeshes.dispose();
  29149. this._renderTargets.dispose();
  29150. this._registeredForLateAnimationBindings.dispose();
  29151. this._meshesForIntersections.dispose();
  29152. this._toBeDisposed = [];
  29153. // Abort active requests
  29154. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29155. var request = _c[_b];
  29156. request.abort();
  29157. }
  29158. // Events
  29159. this.onDisposeObservable.notifyObservers(this);
  29160. this.onDisposeObservable.clear();
  29161. this.onBeforeRenderObservable.clear();
  29162. this.onAfterRenderObservable.clear();
  29163. this.onBeforeRenderTargetsRenderObservable.clear();
  29164. this.onAfterRenderTargetsRenderObservable.clear();
  29165. this.onAfterStepObservable.clear();
  29166. this.onBeforeStepObservable.clear();
  29167. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29168. this.onAfterActiveMeshesEvaluationObservable.clear();
  29169. this.onBeforeParticlesRenderingObservable.clear();
  29170. this.onAfterParticlesRenderingObservable.clear();
  29171. this.onBeforeDrawPhaseObservable.clear();
  29172. this.onAfterDrawPhaseObservable.clear();
  29173. this.onBeforeAnimationsObservable.clear();
  29174. this.onAfterAnimationsObservable.clear();
  29175. this.onDataLoadedObservable.clear();
  29176. this.onBeforeRenderingGroupObservable.clear();
  29177. this.onAfterRenderingGroupObservable.clear();
  29178. this.onMeshImportedObservable.clear();
  29179. this.onBeforeCameraRenderObservable.clear();
  29180. this.onAfterCameraRenderObservable.clear();
  29181. this.onReadyObservable.clear();
  29182. this.onNewCameraAddedObservable.clear();
  29183. this.onCameraRemovedObservable.clear();
  29184. this.onNewLightAddedObservable.clear();
  29185. this.onLightRemovedObservable.clear();
  29186. this.onNewGeometryAddedObservable.clear();
  29187. this.onGeometryRemovedObservable.clear();
  29188. this.onNewTransformNodeAddedObservable.clear();
  29189. this.onTransformNodeRemovedObservable.clear();
  29190. this.onNewMeshAddedObservable.clear();
  29191. this.onMeshRemovedObservable.clear();
  29192. this.onNewMaterialAddedObservable.clear();
  29193. this.onMaterialRemovedObservable.clear();
  29194. this.onNewTextureAddedObservable.clear();
  29195. this.onTextureRemovedObservable.clear();
  29196. this.onPrePointerObservable.clear();
  29197. this.onPointerObservable.clear();
  29198. this.onPreKeyboardObservable.clear();
  29199. this.onKeyboardObservable.clear();
  29200. this.detachControl();
  29201. // Detach cameras
  29202. var canvas = this._engine.getRenderingCanvas();
  29203. if (canvas) {
  29204. var index;
  29205. for (index = 0; index < this.cameras.length; index++) {
  29206. this.cameras[index].detachControl(canvas);
  29207. }
  29208. }
  29209. // Release animation groups
  29210. while (this.animationGroups.length) {
  29211. this.animationGroups[0].dispose();
  29212. }
  29213. // Release lights
  29214. while (this.lights.length) {
  29215. this.lights[0].dispose();
  29216. }
  29217. // Release meshes
  29218. while (this.meshes.length) {
  29219. this.meshes[0].dispose(true);
  29220. }
  29221. while (this.transformNodes.length) {
  29222. this.removeTransformNode(this.transformNodes[0]);
  29223. }
  29224. // Release cameras
  29225. while (this.cameras.length) {
  29226. this.cameras[0].dispose();
  29227. }
  29228. // Release materials
  29229. if (this.defaultMaterial) {
  29230. this.defaultMaterial.dispose();
  29231. }
  29232. while (this.multiMaterials.length) {
  29233. this.multiMaterials[0].dispose();
  29234. }
  29235. while (this.materials.length) {
  29236. this.materials[0].dispose();
  29237. }
  29238. // Release particles
  29239. while (this.particleSystems.length) {
  29240. this.particleSystems[0].dispose();
  29241. }
  29242. // Release postProcesses
  29243. while (this.postProcesses.length) {
  29244. this.postProcesses[0].dispose();
  29245. }
  29246. // Release textures
  29247. while (this.textures.length) {
  29248. this.textures[0].dispose();
  29249. }
  29250. // Release UBO
  29251. this._sceneUbo.dispose();
  29252. if (this._alternateSceneUbo) {
  29253. this._alternateSceneUbo.dispose();
  29254. }
  29255. // Post-processes
  29256. this.postProcessManager.dispose();
  29257. // Remove from engine
  29258. index = this._engine.scenes.indexOf(this);
  29259. if (index > -1) {
  29260. this._engine.scenes.splice(index, 1);
  29261. }
  29262. this._engine.wipeCaches(true);
  29263. this._isDisposed = true;
  29264. };
  29265. Object.defineProperty(Scene.prototype, "isDisposed", {
  29266. /**
  29267. * Gets if the scene is already disposed
  29268. */
  29269. get: function () {
  29270. return this._isDisposed;
  29271. },
  29272. enumerable: true,
  29273. configurable: true
  29274. });
  29275. /**
  29276. * Call this function to reduce memory footprint of the scene.
  29277. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29278. */
  29279. Scene.prototype.clearCachedVertexData = function () {
  29280. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29281. var mesh = this.meshes[meshIndex];
  29282. var geometry = mesh.geometry;
  29283. if (geometry) {
  29284. geometry._indices = [];
  29285. for (var vbName in geometry._vertexBuffers) {
  29286. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29287. continue;
  29288. }
  29289. geometry._vertexBuffers[vbName]._buffer._data = null;
  29290. }
  29291. }
  29292. }
  29293. };
  29294. /**
  29295. * This function will remove the local cached buffer data from texture.
  29296. * It will save memory but will prevent the texture from being rebuilt
  29297. */
  29298. Scene.prototype.cleanCachedTextureBuffer = function () {
  29299. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29300. var baseTexture = _a[_i];
  29301. var buffer = baseTexture._buffer;
  29302. if (buffer) {
  29303. baseTexture._buffer = null;
  29304. }
  29305. }
  29306. };
  29307. /**
  29308. * Get the world extend vectors with an optional filter
  29309. *
  29310. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29311. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29312. */
  29313. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29314. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29315. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29316. filterPredicate = filterPredicate || (function () { return true; });
  29317. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29318. mesh.computeWorldMatrix(true);
  29319. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29320. return;
  29321. }
  29322. var boundingInfo = mesh.getBoundingInfo();
  29323. var minBox = boundingInfo.boundingBox.minimumWorld;
  29324. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29325. BABYLON.Tools.CheckExtends(minBox, min, max);
  29326. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29327. });
  29328. return {
  29329. min: min,
  29330. max: max
  29331. };
  29332. };
  29333. // Picking
  29334. /**
  29335. * Creates a ray that can be used to pick in the scene
  29336. * @param x defines the x coordinate of the origin (on-screen)
  29337. * @param y defines the y coordinate of the origin (on-screen)
  29338. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29339. * @param camera defines the camera to use for the picking
  29340. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29341. * @returns a Ray
  29342. */
  29343. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29344. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29345. var result = BABYLON.Ray.Zero();
  29346. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29347. return result;
  29348. };
  29349. /**
  29350. * Creates a ray that can be used to pick in the scene
  29351. * @param x defines the x coordinate of the origin (on-screen)
  29352. * @param y defines the y coordinate of the origin (on-screen)
  29353. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29354. * @param result defines the ray where to store the picking ray
  29355. * @param camera defines the camera to use for the picking
  29356. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29357. * @returns the current scene
  29358. */
  29359. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29360. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29361. var engine = this._engine;
  29362. if (!camera) {
  29363. if (!this.activeCamera) {
  29364. throw new Error("Active camera not set");
  29365. }
  29366. camera = this.activeCamera;
  29367. }
  29368. var cameraViewport = camera.viewport;
  29369. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29370. // Moving coordinates to local viewport world
  29371. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29372. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29373. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29374. return this;
  29375. };
  29376. /**
  29377. * Creates a ray that can be used to pick in the scene
  29378. * @param x defines the x coordinate of the origin (on-screen)
  29379. * @param y defines the y coordinate of the origin (on-screen)
  29380. * @param camera defines the camera to use for the picking
  29381. * @returns a Ray
  29382. */
  29383. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29384. var result = BABYLON.Ray.Zero();
  29385. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29386. return result;
  29387. };
  29388. /**
  29389. * Creates a ray that can be used to pick in the scene
  29390. * @param x defines the x coordinate of the origin (on-screen)
  29391. * @param y defines the y coordinate of the origin (on-screen)
  29392. * @param result defines the ray where to store the picking ray
  29393. * @param camera defines the camera to use for the picking
  29394. * @returns the current scene
  29395. */
  29396. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29397. if (!BABYLON.PickingInfo) {
  29398. return this;
  29399. }
  29400. var engine = this._engine;
  29401. if (!camera) {
  29402. if (!this.activeCamera) {
  29403. throw new Error("Active camera not set");
  29404. }
  29405. camera = this.activeCamera;
  29406. }
  29407. var cameraViewport = camera.viewport;
  29408. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29409. var identity = BABYLON.Matrix.Identity();
  29410. // Moving coordinates to local viewport world
  29411. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29412. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29413. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29414. return this;
  29415. };
  29416. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29417. if (!BABYLON.PickingInfo) {
  29418. return null;
  29419. }
  29420. var pickingInfo = null;
  29421. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29422. var mesh = this.meshes[meshIndex];
  29423. if (predicate) {
  29424. if (!predicate(mesh)) {
  29425. continue;
  29426. }
  29427. }
  29428. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29429. continue;
  29430. }
  29431. var world = mesh.getWorldMatrix();
  29432. var ray = rayFunction(world);
  29433. var result = mesh.intersects(ray, fastCheck);
  29434. if (!result || !result.hit) {
  29435. continue;
  29436. }
  29437. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29438. continue;
  29439. }
  29440. pickingInfo = result;
  29441. if (fastCheck) {
  29442. break;
  29443. }
  29444. }
  29445. return pickingInfo || new BABYLON.PickingInfo();
  29446. };
  29447. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29448. if (!BABYLON.PickingInfo) {
  29449. return null;
  29450. }
  29451. var pickingInfos = new Array();
  29452. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29453. var mesh = this.meshes[meshIndex];
  29454. if (predicate) {
  29455. if (!predicate(mesh)) {
  29456. continue;
  29457. }
  29458. }
  29459. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29460. continue;
  29461. }
  29462. var world = mesh.getWorldMatrix();
  29463. var ray = rayFunction(world);
  29464. var result = mesh.intersects(ray, false);
  29465. if (!result || !result.hit) {
  29466. continue;
  29467. }
  29468. pickingInfos.push(result);
  29469. }
  29470. return pickingInfos;
  29471. };
  29472. /** Launch a ray to try to pick a mesh in the scene
  29473. * @param x position on screen
  29474. * @param y position on screen
  29475. * @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
  29476. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29477. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29478. * @returns a PickingInfo
  29479. */
  29480. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29481. var _this = this;
  29482. if (!BABYLON.PickingInfo) {
  29483. return null;
  29484. }
  29485. var result = this._internalPick(function (world) {
  29486. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29487. return _this._tempPickingRay;
  29488. }, predicate, fastCheck);
  29489. if (result) {
  29490. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29491. }
  29492. return result;
  29493. };
  29494. /** Use the given ray to pick a mesh in the scene
  29495. * @param ray The ray to use to pick meshes
  29496. * @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
  29497. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29498. * @returns a PickingInfo
  29499. */
  29500. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29501. var _this = this;
  29502. var result = this._internalPick(function (world) {
  29503. if (!_this._pickWithRayInverseMatrix) {
  29504. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29505. }
  29506. world.invertToRef(_this._pickWithRayInverseMatrix);
  29507. if (!_this._cachedRayForTransform) {
  29508. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29509. }
  29510. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29511. return _this._cachedRayForTransform;
  29512. }, predicate, fastCheck);
  29513. if (result) {
  29514. result.ray = ray;
  29515. }
  29516. return result;
  29517. };
  29518. /**
  29519. * Launch a ray to try to pick a mesh in the scene
  29520. * @param x X position on screen
  29521. * @param y Y position on screen
  29522. * @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
  29523. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29524. * @returns an array of PickingInfo
  29525. */
  29526. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29527. var _this = this;
  29528. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29529. };
  29530. /**
  29531. * Launch a ray to try to pick a mesh in the scene
  29532. * @param ray Ray to use
  29533. * @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
  29534. * @returns an array of PickingInfo
  29535. */
  29536. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29537. var _this = this;
  29538. return this._internalMultiPick(function (world) {
  29539. if (!_this._pickWithRayInverseMatrix) {
  29540. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29541. }
  29542. world.invertToRef(_this._pickWithRayInverseMatrix);
  29543. if (!_this._cachedRayForTransform) {
  29544. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29545. }
  29546. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29547. return _this._cachedRayForTransform;
  29548. }, predicate);
  29549. };
  29550. /**
  29551. * Force the value of meshUnderPointer
  29552. * @param mesh defines the mesh to use
  29553. */
  29554. Scene.prototype.setPointerOverMesh = function (mesh) {
  29555. if (this._pointerOverMesh === mesh) {
  29556. return;
  29557. }
  29558. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29559. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29560. }
  29561. this._pointerOverMesh = mesh;
  29562. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29563. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29564. }
  29565. };
  29566. /**
  29567. * Gets the mesh under the pointer
  29568. * @returns a Mesh or null if no mesh is under the pointer
  29569. */
  29570. Scene.prototype.getPointerOverMesh = function () {
  29571. return this._pointerOverMesh;
  29572. };
  29573. // Misc.
  29574. /** @hidden */
  29575. Scene.prototype._rebuildGeometries = function () {
  29576. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29577. var geometry = _a[_i];
  29578. geometry._rebuild();
  29579. }
  29580. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29581. var mesh = _c[_b];
  29582. mesh._rebuild();
  29583. }
  29584. if (this.postProcessManager) {
  29585. this.postProcessManager._rebuild();
  29586. }
  29587. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29588. var component = _e[_d];
  29589. component.rebuild();
  29590. }
  29591. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29592. var system = _g[_f];
  29593. system.rebuild();
  29594. }
  29595. };
  29596. /** @hidden */
  29597. Scene.prototype._rebuildTextures = function () {
  29598. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29599. var texture = _a[_i];
  29600. texture._rebuild();
  29601. }
  29602. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29603. };
  29604. // Tags
  29605. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29606. if (tagsQuery === undefined) {
  29607. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29608. return list;
  29609. }
  29610. var listByTags = [];
  29611. forEach = forEach || (function (item) { return; });
  29612. for (var i in list) {
  29613. var item = list[i];
  29614. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29615. listByTags.push(item);
  29616. forEach(item);
  29617. }
  29618. }
  29619. return listByTags;
  29620. };
  29621. /**
  29622. * Get a list of meshes by tags
  29623. * @param tagsQuery defines the tags query to use
  29624. * @param forEach defines a predicate used to filter results
  29625. * @returns an array of Mesh
  29626. */
  29627. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29628. return this._getByTags(this.meshes, tagsQuery, forEach);
  29629. };
  29630. /**
  29631. * Get a list of cameras by tags
  29632. * @param tagsQuery defines the tags query to use
  29633. * @param forEach defines a predicate used to filter results
  29634. * @returns an array of Camera
  29635. */
  29636. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29637. return this._getByTags(this.cameras, tagsQuery, forEach);
  29638. };
  29639. /**
  29640. * Get a list of lights by tags
  29641. * @param tagsQuery defines the tags query to use
  29642. * @param forEach defines a predicate used to filter results
  29643. * @returns an array of Light
  29644. */
  29645. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29646. return this._getByTags(this.lights, tagsQuery, forEach);
  29647. };
  29648. /**
  29649. * Get a list of materials by tags
  29650. * @param tagsQuery defines the tags query to use
  29651. * @param forEach defines a predicate used to filter results
  29652. * @returns an array of Material
  29653. */
  29654. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29655. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29656. };
  29657. /**
  29658. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29659. * This allowed control for front to back rendering or reversly depending of the special needs.
  29660. *
  29661. * @param renderingGroupId The rendering group id corresponding to its index
  29662. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29663. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29664. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29665. */
  29666. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29667. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29668. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29669. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29670. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29671. };
  29672. /**
  29673. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29674. *
  29675. * @param renderingGroupId The rendering group id corresponding to its index
  29676. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29677. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29678. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29679. */
  29680. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29681. if (depth === void 0) { depth = true; }
  29682. if (stencil === void 0) { stencil = true; }
  29683. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29684. };
  29685. /**
  29686. * Gets the current auto clear configuration for one rendering group of the rendering
  29687. * manager.
  29688. * @param index the rendering group index to get the information for
  29689. * @returns The auto clear setup for the requested rendering group
  29690. */
  29691. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29692. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29693. };
  29694. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29695. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29696. get: function () {
  29697. return this._blockMaterialDirtyMechanism;
  29698. },
  29699. set: function (value) {
  29700. if (this._blockMaterialDirtyMechanism === value) {
  29701. return;
  29702. }
  29703. this._blockMaterialDirtyMechanism = value;
  29704. if (!value) { // Do a complete update
  29705. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29706. }
  29707. },
  29708. enumerable: true,
  29709. configurable: true
  29710. });
  29711. /**
  29712. * Will flag all materials as dirty to trigger new shader compilation
  29713. * @param flag defines the flag used to specify which material part must be marked as dirty
  29714. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29715. */
  29716. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29717. if (this._blockMaterialDirtyMechanism) {
  29718. return;
  29719. }
  29720. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29721. var material = _a[_i];
  29722. if (predicate && !predicate(material)) {
  29723. continue;
  29724. }
  29725. material.markAsDirty(flag);
  29726. }
  29727. };
  29728. /** @hidden */
  29729. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29730. var _this = this;
  29731. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29732. this._activeRequests.push(request);
  29733. request.onCompleteObservable.add(function (request) {
  29734. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29735. });
  29736. return request;
  29737. };
  29738. /** @hidden */
  29739. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29740. var _this = this;
  29741. return new Promise(function (resolve, reject) {
  29742. _this._loadFile(url, function (data) {
  29743. resolve(data);
  29744. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29745. reject(exception);
  29746. });
  29747. });
  29748. };
  29749. // Statics
  29750. Scene._uniqueIdCounter = 0;
  29751. /** The fog is deactivated */
  29752. Scene.FOGMODE_NONE = 0;
  29753. /** The fog density is following an exponential function */
  29754. Scene.FOGMODE_EXP = 1;
  29755. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29756. Scene.FOGMODE_EXP2 = 2;
  29757. /** The fog density is following a linear function. */
  29758. Scene.FOGMODE_LINEAR = 3;
  29759. /**
  29760. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29761. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29762. */
  29763. Scene.MinDeltaTime = 1.0;
  29764. /**
  29765. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29766. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29767. */
  29768. Scene.MaxDeltaTime = 1000.0;
  29769. /** The distance in pixel that you have to move to prevent some events */
  29770. Scene.DragMovementThreshold = 10; // in pixels
  29771. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29772. Scene.LongPressDelay = 500; // in milliseconds
  29773. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29774. Scene.DoubleClickDelay = 300; // in milliseconds
  29775. /** If you need to check double click without raising a single click at first click, enable this flag */
  29776. Scene.ExclusiveDoubleClickMode = false;
  29777. return Scene;
  29778. }(BABYLON.AbstractScene));
  29779. BABYLON.Scene = Scene;
  29780. })(BABYLON || (BABYLON = {}));
  29781. //# sourceMappingURL=babylon.scene.js.map
  29782. var BABYLON;
  29783. (function (BABYLON) {
  29784. /**
  29785. * Set of assets to keep when moving a scene into an asset container.
  29786. */
  29787. var KeepAssets = /** @class */ (function (_super) {
  29788. __extends(KeepAssets, _super);
  29789. function KeepAssets() {
  29790. return _super !== null && _super.apply(this, arguments) || this;
  29791. }
  29792. return KeepAssets;
  29793. }(BABYLON.AbstractScene));
  29794. BABYLON.KeepAssets = KeepAssets;
  29795. /**
  29796. * Container with a set of assets that can be added or removed from a scene.
  29797. */
  29798. var AssetContainer = /** @class */ (function (_super) {
  29799. __extends(AssetContainer, _super);
  29800. /**
  29801. * Instantiates an AssetContainer.
  29802. * @param scene The scene the AssetContainer belongs to.
  29803. */
  29804. function AssetContainer(scene) {
  29805. var _this = _super.call(this) || this;
  29806. _this.scene = scene;
  29807. return _this;
  29808. }
  29809. /**
  29810. * Adds all the assets from the container to the scene.
  29811. */
  29812. AssetContainer.prototype.addAllToScene = function () {
  29813. var _this = this;
  29814. this.cameras.forEach(function (o) {
  29815. _this.scene.addCamera(o);
  29816. });
  29817. this.lights.forEach(function (o) {
  29818. _this.scene.addLight(o);
  29819. });
  29820. this.meshes.forEach(function (o) {
  29821. _this.scene.addMesh(o);
  29822. });
  29823. this.skeletons.forEach(function (o) {
  29824. _this.scene.addSkeleton(o);
  29825. });
  29826. this.animations.forEach(function (o) {
  29827. _this.scene.addAnimation(o);
  29828. });
  29829. this.animationGroups.forEach(function (o) {
  29830. _this.scene.addAnimationGroup(o);
  29831. });
  29832. this.multiMaterials.forEach(function (o) {
  29833. _this.scene.addMultiMaterial(o);
  29834. });
  29835. this.materials.forEach(function (o) {
  29836. _this.scene.addMaterial(o);
  29837. });
  29838. this.morphTargetManagers.forEach(function (o) {
  29839. _this.scene.addMorphTargetManager(o);
  29840. });
  29841. this.geometries.forEach(function (o) {
  29842. _this.scene.addGeometry(o);
  29843. });
  29844. this.transformNodes.forEach(function (o) {
  29845. _this.scene.addTransformNode(o);
  29846. });
  29847. this.actionManagers.forEach(function (o) {
  29848. _this.scene.addActionManager(o);
  29849. });
  29850. this.textures.forEach(function (o) {
  29851. _this.scene.addTexture(o);
  29852. });
  29853. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29854. var component = _a[_i];
  29855. component.addFromContainer(this.scene);
  29856. }
  29857. };
  29858. /**
  29859. * Removes all the assets in the container from the scene
  29860. */
  29861. AssetContainer.prototype.removeAllFromScene = function () {
  29862. var _this = this;
  29863. this.cameras.forEach(function (o) {
  29864. _this.scene.removeCamera(o);
  29865. });
  29866. this.lights.forEach(function (o) {
  29867. _this.scene.removeLight(o);
  29868. });
  29869. this.meshes.forEach(function (o) {
  29870. _this.scene.removeMesh(o);
  29871. });
  29872. this.skeletons.forEach(function (o) {
  29873. _this.scene.removeSkeleton(o);
  29874. });
  29875. this.animations.forEach(function (o) {
  29876. _this.scene.removeAnimation(o);
  29877. });
  29878. this.animationGroups.forEach(function (o) {
  29879. _this.scene.removeAnimationGroup(o);
  29880. });
  29881. this.multiMaterials.forEach(function (o) {
  29882. _this.scene.removeMultiMaterial(o);
  29883. });
  29884. this.materials.forEach(function (o) {
  29885. _this.scene.removeMaterial(o);
  29886. });
  29887. this.morphTargetManagers.forEach(function (o) {
  29888. _this.scene.removeMorphTargetManager(o);
  29889. });
  29890. this.geometries.forEach(function (o) {
  29891. _this.scene.removeGeometry(o);
  29892. });
  29893. this.transformNodes.forEach(function (o) {
  29894. _this.scene.removeTransformNode(o);
  29895. });
  29896. this.actionManagers.forEach(function (o) {
  29897. _this.scene.removeActionManager(o);
  29898. });
  29899. this.textures.forEach(function (o) {
  29900. _this.scene.removeTexture(o);
  29901. });
  29902. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29903. var component = _a[_i];
  29904. component.removeFromContainer(this.scene);
  29905. }
  29906. };
  29907. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29908. if (!sourceAssets) {
  29909. return;
  29910. }
  29911. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29912. var asset = sourceAssets_1[_i];
  29913. var move = true;
  29914. if (keepAssets) {
  29915. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29916. var keepAsset = keepAssets_1[_a];
  29917. if (asset === keepAsset) {
  29918. move = false;
  29919. break;
  29920. }
  29921. }
  29922. }
  29923. if (move) {
  29924. targetAssets.push(asset);
  29925. }
  29926. }
  29927. };
  29928. /**
  29929. * Removes all the assets contained in the scene and adds them to the container.
  29930. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29931. */
  29932. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29933. if (keepAssets === undefined) {
  29934. keepAssets = new KeepAssets();
  29935. }
  29936. for (var key in this) {
  29937. if (this.hasOwnProperty(key)) {
  29938. this[key] = this[key] || [];
  29939. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29940. }
  29941. }
  29942. this.removeAllFromScene();
  29943. };
  29944. /**
  29945. * 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.
  29946. * @returns the root mesh
  29947. */
  29948. AssetContainer.prototype.createRootMesh = function () {
  29949. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29950. this.meshes.forEach(function (m) {
  29951. if (!m.parent) {
  29952. rootMesh.addChild(m);
  29953. }
  29954. });
  29955. this.meshes.unshift(rootMesh);
  29956. return rootMesh;
  29957. };
  29958. return AssetContainer;
  29959. }(BABYLON.AbstractScene));
  29960. BABYLON.AssetContainer = AssetContainer;
  29961. })(BABYLON || (BABYLON = {}));
  29962. //# sourceMappingURL=babylon.assetContainer.js.map
  29963. var BABYLON;
  29964. (function (BABYLON) {
  29965. /**
  29966. * Class used to store data that will be store in GPU memory
  29967. */
  29968. var Buffer = /** @class */ (function () {
  29969. /**
  29970. * Constructor
  29971. * @param engine the engine
  29972. * @param data the data to use for this buffer
  29973. * @param updatable whether the data is updatable
  29974. * @param stride the stride (optional)
  29975. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29976. * @param instanced whether the buffer is instanced (optional)
  29977. * @param useBytes set to true if the stride in in bytes (optional)
  29978. */
  29979. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29980. if (stride === void 0) { stride = 0; }
  29981. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29982. if (instanced === void 0) { instanced = false; }
  29983. if (useBytes === void 0) { useBytes = false; }
  29984. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29985. this._engine = engine.getScene().getEngine();
  29986. }
  29987. else {
  29988. this._engine = engine;
  29989. }
  29990. this._updatable = updatable;
  29991. this._instanced = instanced;
  29992. this._data = data;
  29993. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29994. if (!postponeInternalCreation) { // by default
  29995. this.create();
  29996. }
  29997. }
  29998. /**
  29999. * Create a new VertexBuffer based on the current buffer
  30000. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30001. * @param offset defines offset in the buffer (0 by default)
  30002. * @param size defines the size in floats of attributes (position is 3 for instance)
  30003. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30004. * @param instanced defines if the vertex buffer contains indexed data
  30005. * @param useBytes defines if the offset and stride are in bytes
  30006. * @returns the new vertex buffer
  30007. */
  30008. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30009. if (useBytes === void 0) { useBytes = false; }
  30010. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30011. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30012. // a lot of these parameters are ignored as they are overriden by the buffer
  30013. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30014. };
  30015. // Properties
  30016. /**
  30017. * Gets a boolean indicating if the Buffer is updatable?
  30018. * @returns true if the buffer is updatable
  30019. */
  30020. Buffer.prototype.isUpdatable = function () {
  30021. return this._updatable;
  30022. };
  30023. /**
  30024. * Gets current buffer's data
  30025. * @returns a DataArray or null
  30026. */
  30027. Buffer.prototype.getData = function () {
  30028. return this._data;
  30029. };
  30030. /**
  30031. * Gets underlying native buffer
  30032. * @returns underlying native buffer
  30033. */
  30034. Buffer.prototype.getBuffer = function () {
  30035. return this._buffer;
  30036. };
  30037. /**
  30038. * Gets the stride in float32 units (i.e. byte stride / 4).
  30039. * May not be an integer if the byte stride is not divisible by 4.
  30040. * DEPRECATED. Use byteStride instead.
  30041. * @returns the stride in float32 units
  30042. */
  30043. Buffer.prototype.getStrideSize = function () {
  30044. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30045. };
  30046. // Methods
  30047. /**
  30048. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30049. * @param data defines the data to store
  30050. */
  30051. Buffer.prototype.create = function (data) {
  30052. if (data === void 0) { data = null; }
  30053. if (!data && this._buffer) {
  30054. return; // nothing to do
  30055. }
  30056. data = data || this._data;
  30057. if (!data) {
  30058. return;
  30059. }
  30060. if (!this._buffer) { // create buffer
  30061. if (this._updatable) {
  30062. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30063. this._data = data;
  30064. }
  30065. else {
  30066. this._buffer = this._engine.createVertexBuffer(data);
  30067. }
  30068. }
  30069. else if (this._updatable) { // update buffer
  30070. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30071. this._data = data;
  30072. }
  30073. };
  30074. /** @hidden */
  30075. Buffer.prototype._rebuild = function () {
  30076. this._buffer = null;
  30077. this.create(this._data);
  30078. };
  30079. /**
  30080. * Update current buffer data
  30081. * @param data defines the data to store
  30082. */
  30083. Buffer.prototype.update = function (data) {
  30084. this.create(data);
  30085. };
  30086. /**
  30087. * Updates the data directly.
  30088. * @param data the new data
  30089. * @param offset the new offset
  30090. * @param vertexCount the vertex count (optional)
  30091. * @param useBytes set to true if the offset is in bytes
  30092. */
  30093. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30094. if (useBytes === void 0) { useBytes = false; }
  30095. if (!this._buffer) {
  30096. return;
  30097. }
  30098. if (this._updatable) { // update buffer
  30099. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30100. this._data = null;
  30101. }
  30102. };
  30103. /**
  30104. * Release all resources
  30105. */
  30106. Buffer.prototype.dispose = function () {
  30107. if (!this._buffer) {
  30108. return;
  30109. }
  30110. if (this._engine._releaseBuffer(this._buffer)) {
  30111. this._buffer = null;
  30112. }
  30113. };
  30114. return Buffer;
  30115. }());
  30116. BABYLON.Buffer = Buffer;
  30117. })(BABYLON || (BABYLON = {}));
  30118. //# sourceMappingURL=babylon.buffer.js.map
  30119. var BABYLON;
  30120. (function (BABYLON) {
  30121. /**
  30122. * Specialized buffer used to store vertex data
  30123. */
  30124. var VertexBuffer = /** @class */ (function () {
  30125. /**
  30126. * Constructor
  30127. * @param engine the engine
  30128. * @param data the data to use for this vertex buffer
  30129. * @param kind the vertex buffer kind
  30130. * @param updatable whether the data is updatable
  30131. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30132. * @param stride the stride (optional)
  30133. * @param instanced whether the buffer is instanced (optional)
  30134. * @param offset the offset of the data (optional)
  30135. * @param size the number of components (optional)
  30136. * @param type the type of the component (optional)
  30137. * @param normalized whether the data contains normalized data (optional)
  30138. * @param useBytes set to true if stride and offset are in bytes (optional)
  30139. */
  30140. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30141. if (normalized === void 0) { normalized = false; }
  30142. if (useBytes === void 0) { useBytes = false; }
  30143. if (data instanceof BABYLON.Buffer) {
  30144. this._buffer = data;
  30145. this._ownsBuffer = false;
  30146. }
  30147. else {
  30148. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30149. this._ownsBuffer = true;
  30150. }
  30151. this._kind = kind;
  30152. if (type == undefined) {
  30153. var data_1 = this.getData();
  30154. this.type = VertexBuffer.FLOAT;
  30155. if (data_1 instanceof Int8Array) {
  30156. this.type = VertexBuffer.BYTE;
  30157. }
  30158. else if (data_1 instanceof Uint8Array) {
  30159. this.type = VertexBuffer.UNSIGNED_BYTE;
  30160. }
  30161. else if (data_1 instanceof Int16Array) {
  30162. this.type = VertexBuffer.SHORT;
  30163. }
  30164. else if (data_1 instanceof Uint16Array) {
  30165. this.type = VertexBuffer.UNSIGNED_SHORT;
  30166. }
  30167. else if (data_1 instanceof Int32Array) {
  30168. this.type = VertexBuffer.INT;
  30169. }
  30170. else if (data_1 instanceof Uint32Array) {
  30171. this.type = VertexBuffer.UNSIGNED_INT;
  30172. }
  30173. }
  30174. else {
  30175. this.type = type;
  30176. }
  30177. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30178. if (useBytes) {
  30179. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30180. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30181. this.byteOffset = offset || 0;
  30182. }
  30183. else {
  30184. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30185. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30186. this.byteOffset = (offset || 0) * typeByteLength;
  30187. }
  30188. this.normalized = normalized;
  30189. this._instanced = instanced !== undefined ? instanced : false;
  30190. this._instanceDivisor = instanced ? 1 : 0;
  30191. }
  30192. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30193. /**
  30194. * Gets or sets the instance divisor when in instanced mode
  30195. */
  30196. get: function () {
  30197. return this._instanceDivisor;
  30198. },
  30199. set: function (value) {
  30200. this._instanceDivisor = value;
  30201. if (value == 0) {
  30202. this._instanced = false;
  30203. }
  30204. else {
  30205. this._instanced = true;
  30206. }
  30207. },
  30208. enumerable: true,
  30209. configurable: true
  30210. });
  30211. /** @hidden */
  30212. VertexBuffer.prototype._rebuild = function () {
  30213. if (!this._buffer) {
  30214. return;
  30215. }
  30216. this._buffer._rebuild();
  30217. };
  30218. /**
  30219. * Returns the kind of the VertexBuffer (string)
  30220. * @returns a string
  30221. */
  30222. VertexBuffer.prototype.getKind = function () {
  30223. return this._kind;
  30224. };
  30225. // Properties
  30226. /**
  30227. * Gets a boolean indicating if the VertexBuffer is updatable?
  30228. * @returns true if the buffer is updatable
  30229. */
  30230. VertexBuffer.prototype.isUpdatable = function () {
  30231. return this._buffer.isUpdatable();
  30232. };
  30233. /**
  30234. * Gets current buffer's data
  30235. * @returns a DataArray or null
  30236. */
  30237. VertexBuffer.prototype.getData = function () {
  30238. return this._buffer.getData();
  30239. };
  30240. /**
  30241. * Gets underlying native buffer
  30242. * @returns underlying native buffer
  30243. */
  30244. VertexBuffer.prototype.getBuffer = function () {
  30245. return this._buffer.getBuffer();
  30246. };
  30247. /**
  30248. * Gets the stride in float32 units (i.e. byte stride / 4).
  30249. * May not be an integer if the byte stride is not divisible by 4.
  30250. * DEPRECATED. Use byteStride instead.
  30251. * @returns the stride in float32 units
  30252. */
  30253. VertexBuffer.prototype.getStrideSize = function () {
  30254. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30255. };
  30256. /**
  30257. * Returns the offset as a multiple of the type byte length.
  30258. * DEPRECATED. Use byteOffset instead.
  30259. * @returns the offset in bytes
  30260. */
  30261. VertexBuffer.prototype.getOffset = function () {
  30262. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30263. };
  30264. /**
  30265. * Returns the number of components per vertex attribute (integer)
  30266. * @returns the size in float
  30267. */
  30268. VertexBuffer.prototype.getSize = function () {
  30269. return this._size;
  30270. };
  30271. /**
  30272. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30273. * @returns true if this buffer is instanced
  30274. */
  30275. VertexBuffer.prototype.getIsInstanced = function () {
  30276. return this._instanced;
  30277. };
  30278. /**
  30279. * Returns the instancing divisor, zero for non-instanced (integer).
  30280. * @returns a number
  30281. */
  30282. VertexBuffer.prototype.getInstanceDivisor = function () {
  30283. return this._instanceDivisor;
  30284. };
  30285. // Methods
  30286. /**
  30287. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30288. * @param data defines the data to store
  30289. */
  30290. VertexBuffer.prototype.create = function (data) {
  30291. this._buffer.create(data);
  30292. };
  30293. /**
  30294. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30295. * This function will create a new buffer if the current one is not updatable
  30296. * @param data defines the data to store
  30297. */
  30298. VertexBuffer.prototype.update = function (data) {
  30299. this._buffer.update(data);
  30300. };
  30301. /**
  30302. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30303. * Returns the directly updated WebGLBuffer.
  30304. * @param data the new data
  30305. * @param offset the new offset
  30306. * @param useBytes set to true if the offset is in bytes
  30307. */
  30308. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30309. if (useBytes === void 0) { useBytes = false; }
  30310. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30311. };
  30312. /**
  30313. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30314. */
  30315. VertexBuffer.prototype.dispose = function () {
  30316. if (this._ownsBuffer) {
  30317. this._buffer.dispose();
  30318. }
  30319. };
  30320. /**
  30321. * Enumerates each value of this vertex buffer as numbers.
  30322. * @param count the number of values to enumerate
  30323. * @param callback the callback function called for each value
  30324. */
  30325. VertexBuffer.prototype.forEach = function (count, callback) {
  30326. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30327. };
  30328. /**
  30329. * Deduces the stride given a kind.
  30330. * @param kind The kind string to deduce
  30331. * @returns The deduced stride
  30332. */
  30333. VertexBuffer.DeduceStride = function (kind) {
  30334. switch (kind) {
  30335. case VertexBuffer.UVKind:
  30336. case VertexBuffer.UV2Kind:
  30337. case VertexBuffer.UV3Kind:
  30338. case VertexBuffer.UV4Kind:
  30339. case VertexBuffer.UV5Kind:
  30340. case VertexBuffer.UV6Kind:
  30341. return 2;
  30342. case VertexBuffer.NormalKind:
  30343. case VertexBuffer.PositionKind:
  30344. return 3;
  30345. case VertexBuffer.ColorKind:
  30346. case VertexBuffer.MatricesIndicesKind:
  30347. case VertexBuffer.MatricesIndicesExtraKind:
  30348. case VertexBuffer.MatricesWeightsKind:
  30349. case VertexBuffer.MatricesWeightsExtraKind:
  30350. case VertexBuffer.TangentKind:
  30351. return 4;
  30352. default:
  30353. throw new Error("Invalid kind '" + kind + "'");
  30354. }
  30355. };
  30356. /**
  30357. * Gets the byte length of the given type.
  30358. * @param type the type
  30359. * @returns the number of bytes
  30360. */
  30361. VertexBuffer.GetTypeByteLength = function (type) {
  30362. switch (type) {
  30363. case VertexBuffer.BYTE:
  30364. case VertexBuffer.UNSIGNED_BYTE:
  30365. return 1;
  30366. case VertexBuffer.SHORT:
  30367. case VertexBuffer.UNSIGNED_SHORT:
  30368. return 2;
  30369. case VertexBuffer.INT:
  30370. case VertexBuffer.FLOAT:
  30371. return 4;
  30372. default:
  30373. throw new Error("Invalid type '" + type + "'");
  30374. }
  30375. };
  30376. /**
  30377. * Enumerates each value of the given parameters as numbers.
  30378. * @param data the data to enumerate
  30379. * @param byteOffset the byte offset of the data
  30380. * @param byteStride the byte stride of the data
  30381. * @param componentCount the number of components per element
  30382. * @param componentType the type of the component
  30383. * @param count the total number of components
  30384. * @param normalized whether the data is normalized
  30385. * @param callback the callback function called for each value
  30386. */
  30387. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30388. if (data instanceof Array) {
  30389. var offset = byteOffset / 4;
  30390. var stride = byteStride / 4;
  30391. for (var index = 0; index < count; index += componentCount) {
  30392. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30393. callback(data[offset + componentIndex], index + componentIndex);
  30394. }
  30395. offset += stride;
  30396. }
  30397. }
  30398. else {
  30399. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30400. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30401. for (var index = 0; index < count; index += componentCount) {
  30402. var componentByteOffset = byteOffset;
  30403. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30404. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30405. callback(value, index + componentIndex);
  30406. componentByteOffset += componentByteLength;
  30407. }
  30408. byteOffset += byteStride;
  30409. }
  30410. }
  30411. };
  30412. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30413. switch (type) {
  30414. case VertexBuffer.BYTE: {
  30415. var value = dataView.getInt8(byteOffset);
  30416. if (normalized) {
  30417. value = Math.max(value / 127, -1);
  30418. }
  30419. return value;
  30420. }
  30421. case VertexBuffer.UNSIGNED_BYTE: {
  30422. var value = dataView.getUint8(byteOffset);
  30423. if (normalized) {
  30424. value = value / 255;
  30425. }
  30426. return value;
  30427. }
  30428. case VertexBuffer.SHORT: {
  30429. var value = dataView.getInt16(byteOffset, true);
  30430. if (normalized) {
  30431. value = Math.max(value / 16383, -1);
  30432. }
  30433. return value;
  30434. }
  30435. case VertexBuffer.UNSIGNED_SHORT: {
  30436. var value = dataView.getUint16(byteOffset, true);
  30437. if (normalized) {
  30438. value = value / 65535;
  30439. }
  30440. return value;
  30441. }
  30442. case VertexBuffer.FLOAT: {
  30443. return dataView.getFloat32(byteOffset, true);
  30444. }
  30445. default: {
  30446. throw new Error("Invalid component type " + type);
  30447. }
  30448. }
  30449. };
  30450. /**
  30451. * The byte type.
  30452. */
  30453. VertexBuffer.BYTE = 5120;
  30454. /**
  30455. * The unsigned byte type.
  30456. */
  30457. VertexBuffer.UNSIGNED_BYTE = 5121;
  30458. /**
  30459. * The short type.
  30460. */
  30461. VertexBuffer.SHORT = 5122;
  30462. /**
  30463. * The unsigned short type.
  30464. */
  30465. VertexBuffer.UNSIGNED_SHORT = 5123;
  30466. /**
  30467. * The integer type.
  30468. */
  30469. VertexBuffer.INT = 5124;
  30470. /**
  30471. * The unsigned integer type.
  30472. */
  30473. VertexBuffer.UNSIGNED_INT = 5125;
  30474. /**
  30475. * The float type.
  30476. */
  30477. VertexBuffer.FLOAT = 5126;
  30478. // Enums
  30479. /**
  30480. * Positions
  30481. */
  30482. VertexBuffer.PositionKind = "position";
  30483. /**
  30484. * Normals
  30485. */
  30486. VertexBuffer.NormalKind = "normal";
  30487. /**
  30488. * Tangents
  30489. */
  30490. VertexBuffer.TangentKind = "tangent";
  30491. /**
  30492. * Texture coordinates
  30493. */
  30494. VertexBuffer.UVKind = "uv";
  30495. /**
  30496. * Texture coordinates 2
  30497. */
  30498. VertexBuffer.UV2Kind = "uv2";
  30499. /**
  30500. * Texture coordinates 3
  30501. */
  30502. VertexBuffer.UV3Kind = "uv3";
  30503. /**
  30504. * Texture coordinates 4
  30505. */
  30506. VertexBuffer.UV4Kind = "uv4";
  30507. /**
  30508. * Texture coordinates 5
  30509. */
  30510. VertexBuffer.UV5Kind = "uv5";
  30511. /**
  30512. * Texture coordinates 6
  30513. */
  30514. VertexBuffer.UV6Kind = "uv6";
  30515. /**
  30516. * Colors
  30517. */
  30518. VertexBuffer.ColorKind = "color";
  30519. /**
  30520. * Matrix indices (for bones)
  30521. */
  30522. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30523. /**
  30524. * Matrix weights (for bones)
  30525. */
  30526. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30527. /**
  30528. * Additional matrix indices (for bones)
  30529. */
  30530. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30531. /**
  30532. * Additional matrix weights (for bones)
  30533. */
  30534. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30535. return VertexBuffer;
  30536. }());
  30537. BABYLON.VertexBuffer = VertexBuffer;
  30538. })(BABYLON || (BABYLON = {}));
  30539. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30540. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30541. var BABYLON;
  30542. (function (BABYLON) {
  30543. /**
  30544. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30545. */
  30546. var DummyInternalTextureTracker = /** @class */ (function () {
  30547. function DummyInternalTextureTracker() {
  30548. /**
  30549. * Gets or set the previous tracker in the list
  30550. */
  30551. this.previous = null;
  30552. /**
  30553. * Gets or set the next tracker in the list
  30554. */
  30555. this.next = null;
  30556. }
  30557. return DummyInternalTextureTracker;
  30558. }());
  30559. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30560. })(BABYLON || (BABYLON = {}));
  30561. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30562. var BABYLON;
  30563. (function (BABYLON) {
  30564. /**
  30565. * Class used to store data associated with WebGL texture data for the engine
  30566. * This class should not be used directly
  30567. */
  30568. var InternalTexture = /** @class */ (function () {
  30569. /**
  30570. * Creates a new InternalTexture
  30571. * @param engine defines the engine to use
  30572. * @param dataSource defines the type of data that will be used
  30573. */
  30574. function InternalTexture(engine, dataSource) {
  30575. /**
  30576. * Observable called when the texture is loaded
  30577. */
  30578. this.onLoadedObservable = new BABYLON.Observable();
  30579. /**
  30580. * Gets or set the previous tracker in the list
  30581. */
  30582. this.previous = null;
  30583. /**
  30584. * Gets or set the next tracker in the list
  30585. */
  30586. this.next = null;
  30587. // Private
  30588. /** @hidden */
  30589. this._initialSlot = -1;
  30590. /** @hidden */
  30591. this._designatedSlot = -1;
  30592. /** @hidden */
  30593. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30594. /** @hidden */
  30595. this._comparisonFunction = 0;
  30596. /** @hidden */
  30597. this._sphericalPolynomial = null;
  30598. /** @hidden */
  30599. this._lodGenerationScale = 0;
  30600. /** @hidden */
  30601. this._lodGenerationOffset = 0;
  30602. /** @hidden */
  30603. this._isRGBD = false;
  30604. /** @hidden */
  30605. this._references = 1;
  30606. this._engine = engine;
  30607. this._dataSource = dataSource;
  30608. this._webGLTexture = engine._createTexture();
  30609. }
  30610. /**
  30611. * Gets the Engine the texture belongs to.
  30612. * @returns The babylon engine
  30613. */
  30614. InternalTexture.prototype.getEngine = function () {
  30615. return this._engine;
  30616. };
  30617. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30618. /**
  30619. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30620. */
  30621. get: function () {
  30622. return this._dataSource;
  30623. },
  30624. enumerable: true,
  30625. configurable: true
  30626. });
  30627. /**
  30628. * Increments the number of references (ie. the number of Texture that point to it)
  30629. */
  30630. InternalTexture.prototype.incrementReferences = function () {
  30631. this._references++;
  30632. };
  30633. /**
  30634. * Change the size of the texture (not the size of the content)
  30635. * @param width defines the new width
  30636. * @param height defines the new height
  30637. * @param depth defines the new depth (1 by default)
  30638. */
  30639. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30640. if (depth === void 0) { depth = 1; }
  30641. this.width = width;
  30642. this.height = height;
  30643. this.depth = depth;
  30644. this.baseWidth = width;
  30645. this.baseHeight = height;
  30646. this.baseDepth = depth;
  30647. this._size = width * height * depth;
  30648. };
  30649. /** @hidden */
  30650. InternalTexture.prototype._rebuild = function () {
  30651. var _this = this;
  30652. var proxy;
  30653. this.isReady = false;
  30654. this._cachedCoordinatesMode = null;
  30655. this._cachedWrapU = null;
  30656. this._cachedWrapV = null;
  30657. this._cachedAnisotropicFilteringLevel = null;
  30658. switch (this._dataSource) {
  30659. case InternalTexture.DATASOURCE_TEMP:
  30660. return;
  30661. case InternalTexture.DATASOURCE_URL:
  30662. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30663. _this.isReady = true;
  30664. }, null, this._buffer, undefined, this.format);
  30665. proxy._swapAndDie(this);
  30666. return;
  30667. case InternalTexture.DATASOURCE_RAW:
  30668. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30669. proxy._swapAndDie(this);
  30670. this.isReady = true;
  30671. return;
  30672. case InternalTexture.DATASOURCE_RAW3D:
  30673. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30674. proxy._swapAndDie(this);
  30675. this.isReady = true;
  30676. return;
  30677. case InternalTexture.DATASOURCE_DYNAMIC:
  30678. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30679. proxy._swapAndDie(this);
  30680. // The engine will make sure to update content so no need to flag it as isReady = true
  30681. return;
  30682. case InternalTexture.DATASOURCE_RENDERTARGET:
  30683. var options = new BABYLON.RenderTargetCreationOptions();
  30684. options.generateDepthBuffer = this._generateDepthBuffer;
  30685. options.generateMipMaps = this.generateMipMaps;
  30686. options.generateStencilBuffer = this._generateStencilBuffer;
  30687. options.samplingMode = this.samplingMode;
  30688. options.type = this.type;
  30689. if (this.isCube) {
  30690. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30691. }
  30692. else {
  30693. var size = {
  30694. width: this.width,
  30695. height: this.height
  30696. };
  30697. proxy = this._engine.createRenderTargetTexture(size, options);
  30698. }
  30699. proxy._swapAndDie(this);
  30700. this.isReady = true;
  30701. return;
  30702. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30703. var depthTextureOptions = {
  30704. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30705. comparisonFunction: this._comparisonFunction,
  30706. generateStencil: this._generateStencilBuffer,
  30707. isCube: this.isCube
  30708. };
  30709. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30710. proxy._swapAndDie(this);
  30711. this.isReady = true;
  30712. return;
  30713. case InternalTexture.DATASOURCE_CUBE:
  30714. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30715. _this.isReady = true;
  30716. }, null, this.format, this._extension);
  30717. proxy._swapAndDie(this);
  30718. return;
  30719. case InternalTexture.DATASOURCE_CUBERAW:
  30720. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30721. proxy._swapAndDie(this);
  30722. this.isReady = true;
  30723. return;
  30724. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30725. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30726. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30727. _this.isReady = true;
  30728. });
  30729. proxy._swapAndDie(this);
  30730. return;
  30731. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30732. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30733. if (proxy) {
  30734. proxy._swapAndDie(_this);
  30735. }
  30736. _this.isReady = true;
  30737. }, null, this.format, this._extension);
  30738. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30739. return;
  30740. }
  30741. };
  30742. /** @hidden */
  30743. InternalTexture.prototype._swapAndDie = function (target) {
  30744. target._webGLTexture = this._webGLTexture;
  30745. if (this._framebuffer) {
  30746. target._framebuffer = this._framebuffer;
  30747. }
  30748. if (this._depthStencilBuffer) {
  30749. target._depthStencilBuffer = this._depthStencilBuffer;
  30750. }
  30751. if (this._lodTextureHigh) {
  30752. if (target._lodTextureHigh) {
  30753. target._lodTextureHigh.dispose();
  30754. }
  30755. target._lodTextureHigh = this._lodTextureHigh;
  30756. }
  30757. if (this._lodTextureMid) {
  30758. if (target._lodTextureMid) {
  30759. target._lodTextureMid.dispose();
  30760. }
  30761. target._lodTextureMid = this._lodTextureMid;
  30762. }
  30763. if (this._lodTextureLow) {
  30764. if (target._lodTextureLow) {
  30765. target._lodTextureLow.dispose();
  30766. }
  30767. target._lodTextureLow = this._lodTextureLow;
  30768. }
  30769. var cache = this._engine.getLoadedTexturesCache();
  30770. var index = cache.indexOf(this);
  30771. if (index !== -1) {
  30772. cache.splice(index, 1);
  30773. }
  30774. };
  30775. /**
  30776. * Dispose the current allocated resources
  30777. */
  30778. InternalTexture.prototype.dispose = function () {
  30779. if (!this._webGLTexture) {
  30780. return;
  30781. }
  30782. this._references--;
  30783. if (this._references === 0) {
  30784. this._engine._releaseTexture(this);
  30785. this._webGLTexture = null;
  30786. this.previous = null;
  30787. this.next = null;
  30788. }
  30789. };
  30790. /**
  30791. * The source of the texture data is unknown
  30792. */
  30793. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30794. /**
  30795. * Texture data comes from an URL
  30796. */
  30797. InternalTexture.DATASOURCE_URL = 1;
  30798. /**
  30799. * Texture data is only used for temporary storage
  30800. */
  30801. InternalTexture.DATASOURCE_TEMP = 2;
  30802. /**
  30803. * Texture data comes from raw data (ArrayBuffer)
  30804. */
  30805. InternalTexture.DATASOURCE_RAW = 3;
  30806. /**
  30807. * Texture content is dynamic (video or dynamic texture)
  30808. */
  30809. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30810. /**
  30811. * Texture content is generated by rendering to it
  30812. */
  30813. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30814. /**
  30815. * Texture content is part of a multi render target process
  30816. */
  30817. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30818. /**
  30819. * Texture data comes from a cube data file
  30820. */
  30821. InternalTexture.DATASOURCE_CUBE = 7;
  30822. /**
  30823. * Texture data comes from a raw cube data
  30824. */
  30825. InternalTexture.DATASOURCE_CUBERAW = 8;
  30826. /**
  30827. * Texture data come from a prefiltered cube data file
  30828. */
  30829. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30830. /**
  30831. * Texture content is raw 3D data
  30832. */
  30833. InternalTexture.DATASOURCE_RAW3D = 10;
  30834. /**
  30835. * Texture content is a depth texture
  30836. */
  30837. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30838. /**
  30839. * Texture data comes from a raw cube data encoded with RGBD
  30840. */
  30841. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30842. return InternalTexture;
  30843. }());
  30844. BABYLON.InternalTexture = InternalTexture;
  30845. })(BABYLON || (BABYLON = {}));
  30846. //# sourceMappingURL=babylon.internalTexture.js.map
  30847. var BABYLON;
  30848. (function (BABYLON) {
  30849. /**
  30850. * Base class of all the textures in babylon.
  30851. * It groups all the common properties the materials, post process, lights... might need
  30852. * in order to make a correct use of the texture.
  30853. */
  30854. var BaseTexture = /** @class */ (function () {
  30855. /**
  30856. * Instantiates a new BaseTexture.
  30857. * Base class of all the textures in babylon.
  30858. * It groups all the common properties the materials, post process, lights... might need
  30859. * in order to make a correct use of the texture.
  30860. * @param scene Define the scene the texture blongs to
  30861. */
  30862. function BaseTexture(scene) {
  30863. this._hasAlpha = false;
  30864. /**
  30865. * Defines if the alpha value should be determined via the rgb values.
  30866. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30867. */
  30868. this.getAlphaFromRGB = false;
  30869. /**
  30870. * Intensity or strength of the texture.
  30871. * It is commonly used by materials to fine tune the intensity of the texture
  30872. */
  30873. this.level = 1;
  30874. /**
  30875. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30876. * This is part of the texture as textures usually maps to one uv set.
  30877. */
  30878. this.coordinatesIndex = 0;
  30879. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30880. /**
  30881. * | Value | Type | Description |
  30882. * | ----- | ------------------ | ----------- |
  30883. * | 0 | CLAMP_ADDRESSMODE | |
  30884. * | 1 | WRAP_ADDRESSMODE | |
  30885. * | 2 | MIRROR_ADDRESSMODE | |
  30886. */
  30887. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30888. /**
  30889. * | Value | Type | Description |
  30890. * | ----- | ------------------ | ----------- |
  30891. * | 0 | CLAMP_ADDRESSMODE | |
  30892. * | 1 | WRAP_ADDRESSMODE | |
  30893. * | 2 | MIRROR_ADDRESSMODE | |
  30894. */
  30895. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30896. /**
  30897. * | Value | Type | Description |
  30898. * | ----- | ------------------ | ----------- |
  30899. * | 0 | CLAMP_ADDRESSMODE | |
  30900. * | 1 | WRAP_ADDRESSMODE | |
  30901. * | 2 | MIRROR_ADDRESSMODE | |
  30902. */
  30903. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30904. /**
  30905. * With compliant hardware and browser (supporting anisotropic filtering)
  30906. * this defines the level of anisotropic filtering in the texture.
  30907. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30908. */
  30909. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30910. /**
  30911. * Define if the texture is a cube texture or if false a 2d texture.
  30912. */
  30913. this.isCube = false;
  30914. /**
  30915. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30916. */
  30917. this.is3D = false;
  30918. /**
  30919. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30920. * HDR texture are usually stored in linear space.
  30921. * This only impacts the PBR and Background materials
  30922. */
  30923. this.gammaSpace = true;
  30924. /**
  30925. * Is Z inverted in the texture (useful in a cube texture).
  30926. */
  30927. this.invertZ = false;
  30928. /**
  30929. * @hidden
  30930. */
  30931. this.lodLevelInAlpha = false;
  30932. /**
  30933. * Define if the texture is a render target.
  30934. */
  30935. this.isRenderTarget = false;
  30936. /**
  30937. * Define the list of animation attached to the texture.
  30938. */
  30939. this.animations = new Array();
  30940. /**
  30941. * An event triggered when the texture is disposed.
  30942. */
  30943. this.onDisposeObservable = new BABYLON.Observable();
  30944. /**
  30945. * Define the current state of the loading sequence when in delayed load mode.
  30946. */
  30947. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30948. this._cachedSize = BABYLON.Size.Zero();
  30949. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30950. if (this._scene) {
  30951. this._scene.textures.push(this);
  30952. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30953. }
  30954. this._uid = null;
  30955. }
  30956. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30957. get: function () {
  30958. return this._hasAlpha;
  30959. },
  30960. /**
  30961. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30962. */
  30963. set: function (value) {
  30964. if (this._hasAlpha === value) {
  30965. return;
  30966. }
  30967. this._hasAlpha = value;
  30968. if (this._scene) {
  30969. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30970. }
  30971. },
  30972. enumerable: true,
  30973. configurable: true
  30974. });
  30975. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30976. get: function () {
  30977. return this._coordinatesMode;
  30978. },
  30979. /**
  30980. * How a texture is mapped.
  30981. *
  30982. * | Value | Type | Description |
  30983. * | ----- | ----------------------------------- | ----------- |
  30984. * | 0 | EXPLICIT_MODE | |
  30985. * | 1 | SPHERICAL_MODE | |
  30986. * | 2 | PLANAR_MODE | |
  30987. * | 3 | CUBIC_MODE | |
  30988. * | 4 | PROJECTION_MODE | |
  30989. * | 5 | SKYBOX_MODE | |
  30990. * | 6 | INVCUBIC_MODE | |
  30991. * | 7 | EQUIRECTANGULAR_MODE | |
  30992. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30993. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30994. */
  30995. set: function (value) {
  30996. if (this._coordinatesMode === value) {
  30997. return;
  30998. }
  30999. this._coordinatesMode = value;
  31000. if (this._scene) {
  31001. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31002. }
  31003. },
  31004. enumerable: true,
  31005. configurable: true
  31006. });
  31007. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31008. /**
  31009. * Gets whether or not the texture contains RGBD data.
  31010. */
  31011. get: function () {
  31012. return this._texture != null && this._texture._isRGBD;
  31013. },
  31014. enumerable: true,
  31015. configurable: true
  31016. });
  31017. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31018. /**
  31019. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31020. */
  31021. get: function () {
  31022. if (this._texture) {
  31023. return this._texture._lodGenerationOffset;
  31024. }
  31025. return 0.0;
  31026. },
  31027. set: function (value) {
  31028. if (this._texture) {
  31029. this._texture._lodGenerationOffset = value;
  31030. }
  31031. },
  31032. enumerable: true,
  31033. configurable: true
  31034. });
  31035. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31036. /**
  31037. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31038. */
  31039. get: function () {
  31040. if (this._texture) {
  31041. return this._texture._lodGenerationScale;
  31042. }
  31043. return 0.0;
  31044. },
  31045. set: function (value) {
  31046. if (this._texture) {
  31047. this._texture._lodGenerationScale = value;
  31048. }
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. Object.defineProperty(BaseTexture.prototype, "uid", {
  31054. /**
  31055. * Define the unique id of the texture in the scene.
  31056. */
  31057. get: function () {
  31058. if (!this._uid) {
  31059. this._uid = BABYLON.Tools.RandomId();
  31060. }
  31061. return this._uid;
  31062. },
  31063. enumerable: true,
  31064. configurable: true
  31065. });
  31066. /**
  31067. * Return a string representation of the texture.
  31068. * @returns the texture as a string
  31069. */
  31070. BaseTexture.prototype.toString = function () {
  31071. return this.name;
  31072. };
  31073. /**
  31074. * Get the class name of the texture.
  31075. * @returns "BaseTexture"
  31076. */
  31077. BaseTexture.prototype.getClassName = function () {
  31078. return "BaseTexture";
  31079. };
  31080. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31081. /**
  31082. * Callback triggered when the texture has been disposed.
  31083. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31084. */
  31085. set: function (callback) {
  31086. if (this._onDisposeObserver) {
  31087. this.onDisposeObservable.remove(this._onDisposeObserver);
  31088. }
  31089. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31090. },
  31091. enumerable: true,
  31092. configurable: true
  31093. });
  31094. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31095. /**
  31096. * Define if the texture is preventinga material to render or not.
  31097. * If not and the texture is not ready, the engine will use a default black texture instead.
  31098. */
  31099. get: function () {
  31100. return true;
  31101. },
  31102. enumerable: true,
  31103. configurable: true
  31104. });
  31105. /**
  31106. * Get the scene the texture belongs to.
  31107. * @returns the scene or null if undefined
  31108. */
  31109. BaseTexture.prototype.getScene = function () {
  31110. return this._scene;
  31111. };
  31112. /**
  31113. * Get the texture transform matrix used to offset tile the texture for istance.
  31114. * @returns the transformation matrix
  31115. */
  31116. BaseTexture.prototype.getTextureMatrix = function () {
  31117. return BABYLON.Matrix.IdentityReadOnly;
  31118. };
  31119. /**
  31120. * Get the texture reflection matrix used to rotate/transform the reflection.
  31121. * @returns the reflection matrix
  31122. */
  31123. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31124. return BABYLON.Matrix.IdentityReadOnly;
  31125. };
  31126. /**
  31127. * Get the underlying lower level texture from Babylon.
  31128. * @returns the insternal texture
  31129. */
  31130. BaseTexture.prototype.getInternalTexture = function () {
  31131. return this._texture;
  31132. };
  31133. /**
  31134. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31135. * @returns true if ready or not blocking
  31136. */
  31137. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31138. return !this.isBlocking || this.isReady();
  31139. };
  31140. /**
  31141. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31142. * @returns true if fully ready
  31143. */
  31144. BaseTexture.prototype.isReady = function () {
  31145. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31146. this.delayLoad();
  31147. return false;
  31148. }
  31149. if (this._texture) {
  31150. return this._texture.isReady;
  31151. }
  31152. return false;
  31153. };
  31154. /**
  31155. * Get the size of the texture.
  31156. * @returns the texture size.
  31157. */
  31158. BaseTexture.prototype.getSize = function () {
  31159. if (this._texture) {
  31160. if (this._texture.width) {
  31161. this._cachedSize.width = this._texture.width;
  31162. this._cachedSize.height = this._texture.height;
  31163. return this._cachedSize;
  31164. }
  31165. if (this._texture._size) {
  31166. this._cachedSize.width = this._texture._size;
  31167. this._cachedSize.height = this._texture._size;
  31168. return this._cachedSize;
  31169. }
  31170. }
  31171. return this._cachedSize;
  31172. };
  31173. /**
  31174. * Get the base size of the texture.
  31175. * It can be different from the size if the texture has been resized for POT for instance
  31176. * @returns the base size
  31177. */
  31178. BaseTexture.prototype.getBaseSize = function () {
  31179. if (!this.isReady() || !this._texture) {
  31180. return BABYLON.Size.Zero();
  31181. }
  31182. if (this._texture._size) {
  31183. return new BABYLON.Size(this._texture._size, this._texture._size);
  31184. }
  31185. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31186. };
  31187. /**
  31188. * Scales the texture if is `canRescale()`
  31189. * @param ratio the resize factor we want to use to rescale
  31190. */
  31191. BaseTexture.prototype.scale = function (ratio) {
  31192. };
  31193. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31194. /**
  31195. * Get if the texture can rescale.
  31196. */
  31197. get: function () {
  31198. return false;
  31199. },
  31200. enumerable: true,
  31201. configurable: true
  31202. });
  31203. /** @hidden */
  31204. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31205. if (!this._scene) {
  31206. return null;
  31207. }
  31208. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31209. for (var index = 0; index < texturesCache.length; index++) {
  31210. var texturesCacheEntry = texturesCache[index];
  31211. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31212. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31213. texturesCacheEntry.incrementReferences();
  31214. return texturesCacheEntry;
  31215. }
  31216. }
  31217. }
  31218. return null;
  31219. };
  31220. /** @hidden */
  31221. BaseTexture.prototype._rebuild = function () {
  31222. };
  31223. /**
  31224. * Triggers the load sequence in delayed load mode.
  31225. */
  31226. BaseTexture.prototype.delayLoad = function () {
  31227. };
  31228. /**
  31229. * Clones the texture.
  31230. * @returns the cloned texture
  31231. */
  31232. BaseTexture.prototype.clone = function () {
  31233. return null;
  31234. };
  31235. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31236. /**
  31237. * Get the texture underlying type (INT, FLOAT...)
  31238. */
  31239. get: function () {
  31240. if (!this._texture) {
  31241. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31242. }
  31243. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31249. /**
  31250. * Get the texture underlying format (RGB, RGBA...)
  31251. */
  31252. get: function () {
  31253. if (!this._texture) {
  31254. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31255. }
  31256. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31257. },
  31258. enumerable: true,
  31259. configurable: true
  31260. });
  31261. /**
  31262. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31263. * This will returns an RGBA array buffer containing either in values (0-255) or
  31264. * float values (0-1) depending of the underlying buffer type.
  31265. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31266. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31267. * @param buffer defines a user defined buffer to fill with data (can be null)
  31268. * @returns The Array buffer containing the pixels data.
  31269. */
  31270. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31271. if (faceIndex === void 0) { faceIndex = 0; }
  31272. if (level === void 0) { level = 0; }
  31273. if (buffer === void 0) { buffer = null; }
  31274. if (!this._texture) {
  31275. return null;
  31276. }
  31277. var size = this.getSize();
  31278. var width = size.width;
  31279. var height = size.height;
  31280. var scene = this.getScene();
  31281. if (!scene) {
  31282. return null;
  31283. }
  31284. var engine = scene.getEngine();
  31285. if (level != 0) {
  31286. width = width / Math.pow(2, level);
  31287. height = height / Math.pow(2, level);
  31288. width = Math.round(width);
  31289. height = Math.round(height);
  31290. }
  31291. if (this._texture.isCube) {
  31292. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31293. }
  31294. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31295. };
  31296. /**
  31297. * Release and destroy the underlying lower level texture aka internalTexture.
  31298. */
  31299. BaseTexture.prototype.releaseInternalTexture = function () {
  31300. if (this._texture) {
  31301. this._texture.dispose();
  31302. this._texture = null;
  31303. }
  31304. };
  31305. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31306. /**
  31307. * Get the polynomial representation of the texture data.
  31308. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31309. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31310. */
  31311. get: function () {
  31312. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31313. return null;
  31314. }
  31315. if (!this._texture._sphericalPolynomial) {
  31316. this._texture._sphericalPolynomial =
  31317. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31318. }
  31319. return this._texture._sphericalPolynomial;
  31320. },
  31321. set: function (value) {
  31322. if (this._texture) {
  31323. this._texture._sphericalPolynomial = value;
  31324. }
  31325. },
  31326. enumerable: true,
  31327. configurable: true
  31328. });
  31329. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31330. /** @hidden */
  31331. get: function () {
  31332. if (this._texture) {
  31333. return this._texture._lodTextureHigh;
  31334. }
  31335. return null;
  31336. },
  31337. enumerable: true,
  31338. configurable: true
  31339. });
  31340. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31341. /** @hidden */
  31342. get: function () {
  31343. if (this._texture) {
  31344. return this._texture._lodTextureMid;
  31345. }
  31346. return null;
  31347. },
  31348. enumerable: true,
  31349. configurable: true
  31350. });
  31351. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31352. /** @hidden */
  31353. get: function () {
  31354. if (this._texture) {
  31355. return this._texture._lodTextureLow;
  31356. }
  31357. return null;
  31358. },
  31359. enumerable: true,
  31360. configurable: true
  31361. });
  31362. /**
  31363. * Dispose the texture and release its associated resources.
  31364. */
  31365. BaseTexture.prototype.dispose = function () {
  31366. if (!this._scene) {
  31367. return;
  31368. }
  31369. // Animations
  31370. this._scene.stopAnimation(this);
  31371. // Remove from scene
  31372. this._scene._removePendingData(this);
  31373. var index = this._scene.textures.indexOf(this);
  31374. if (index >= 0) {
  31375. this._scene.textures.splice(index, 1);
  31376. }
  31377. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31378. if (this._texture === undefined) {
  31379. return;
  31380. }
  31381. // Release
  31382. this.releaseInternalTexture();
  31383. // Callback
  31384. this.onDisposeObservable.notifyObservers(this);
  31385. this.onDisposeObservable.clear();
  31386. };
  31387. /**
  31388. * Serialize the texture into a JSON representation that can be parsed later on.
  31389. * @returns the JSON representation of the texture
  31390. */
  31391. BaseTexture.prototype.serialize = function () {
  31392. if (!this.name) {
  31393. return null;
  31394. }
  31395. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31396. // Animations
  31397. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31398. return serializationObject;
  31399. };
  31400. /**
  31401. * Helper function to be called back once a list of texture contains only ready textures.
  31402. * @param textures Define the list of textures to wait for
  31403. * @param callback Define the callback triggered once the entire list will be ready
  31404. */
  31405. BaseTexture.WhenAllReady = function (textures, callback) {
  31406. var numRemaining = textures.length;
  31407. if (numRemaining === 0) {
  31408. callback();
  31409. return;
  31410. }
  31411. var _loop_1 = function () {
  31412. texture = textures[i];
  31413. if (texture.isReady()) {
  31414. if (--numRemaining === 0) {
  31415. callback();
  31416. }
  31417. }
  31418. else {
  31419. onLoadObservable = texture.onLoadObservable;
  31420. var onLoadCallback_1 = function () {
  31421. onLoadObservable.removeCallback(onLoadCallback_1);
  31422. if (--numRemaining === 0) {
  31423. callback();
  31424. }
  31425. };
  31426. onLoadObservable.add(onLoadCallback_1);
  31427. }
  31428. };
  31429. var texture, onLoadObservable;
  31430. for (var i = 0; i < textures.length; i++) {
  31431. _loop_1();
  31432. }
  31433. };
  31434. /**
  31435. * Default anisotropic filtering level for the application.
  31436. * It is set to 4 as a good tradeoff between perf and quality.
  31437. */
  31438. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31439. __decorate([
  31440. BABYLON.serialize()
  31441. ], BaseTexture.prototype, "name", void 0);
  31442. __decorate([
  31443. BABYLON.serialize("hasAlpha")
  31444. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31445. __decorate([
  31446. BABYLON.serialize()
  31447. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31448. __decorate([
  31449. BABYLON.serialize()
  31450. ], BaseTexture.prototype, "level", void 0);
  31451. __decorate([
  31452. BABYLON.serialize()
  31453. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31454. __decorate([
  31455. BABYLON.serialize("coordinatesMode")
  31456. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31457. __decorate([
  31458. BABYLON.serialize()
  31459. ], BaseTexture.prototype, "wrapU", void 0);
  31460. __decorate([
  31461. BABYLON.serialize()
  31462. ], BaseTexture.prototype, "wrapV", void 0);
  31463. __decorate([
  31464. BABYLON.serialize()
  31465. ], BaseTexture.prototype, "wrapR", void 0);
  31466. __decorate([
  31467. BABYLON.serialize()
  31468. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31469. __decorate([
  31470. BABYLON.serialize()
  31471. ], BaseTexture.prototype, "isCube", void 0);
  31472. __decorate([
  31473. BABYLON.serialize()
  31474. ], BaseTexture.prototype, "is3D", void 0);
  31475. __decorate([
  31476. BABYLON.serialize()
  31477. ], BaseTexture.prototype, "gammaSpace", void 0);
  31478. __decorate([
  31479. BABYLON.serialize()
  31480. ], BaseTexture.prototype, "invertZ", void 0);
  31481. __decorate([
  31482. BABYLON.serialize()
  31483. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31484. __decorate([
  31485. BABYLON.serialize()
  31486. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31487. __decorate([
  31488. BABYLON.serialize()
  31489. ], BaseTexture.prototype, "lodGenerationScale", null);
  31490. __decorate([
  31491. BABYLON.serialize()
  31492. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31493. return BaseTexture;
  31494. }());
  31495. BABYLON.BaseTexture = BaseTexture;
  31496. })(BABYLON || (BABYLON = {}));
  31497. //# sourceMappingURL=babylon.baseTexture.js.map
  31498. var BABYLON;
  31499. (function (BABYLON) {
  31500. /**
  31501. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31502. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31503. */
  31504. var Texture = /** @class */ (function (_super) {
  31505. __extends(Texture, _super);
  31506. /**
  31507. * Instantiates a new texture.
  31508. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31509. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31510. * @param url define the url of the picture to load as a texture
  31511. * @param scene define the scene the texture will belong to
  31512. * @param noMipmap define if the texture will require mip maps or not
  31513. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31514. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31515. * @param onLoad define a callback triggered when the texture has been loaded
  31516. * @param onError define a callback triggered when an error occurred during the loading session
  31517. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31518. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31519. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31520. */
  31521. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31522. if (noMipmap === void 0) { noMipmap = false; }
  31523. if (invertY === void 0) { invertY = true; }
  31524. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31525. if (onLoad === void 0) { onLoad = null; }
  31526. if (onError === void 0) { onError = null; }
  31527. if (buffer === void 0) { buffer = null; }
  31528. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31529. var _this = _super.call(this, scene) || this;
  31530. /**
  31531. * Define an offset on the texture to offset the u coordinates of the UVs
  31532. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31533. */
  31534. _this.uOffset = 0;
  31535. /**
  31536. * Define an offset on the texture to offset the v coordinates of the UVs
  31537. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31538. */
  31539. _this.vOffset = 0;
  31540. /**
  31541. * Define an offset on the texture to scale the u coordinates of the UVs
  31542. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31543. */
  31544. _this.uScale = 1.0;
  31545. /**
  31546. * Define an offset on the texture to scale the v coordinates of the UVs
  31547. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31548. */
  31549. _this.vScale = 1.0;
  31550. /**
  31551. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31552. * @see http://doc.babylonjs.com/how_to/more_materials
  31553. */
  31554. _this.uAng = 0;
  31555. /**
  31556. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31557. * @see http://doc.babylonjs.com/how_to/more_materials
  31558. */
  31559. _this.vAng = 0;
  31560. /**
  31561. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31562. * @see http://doc.babylonjs.com/how_to/more_materials
  31563. */
  31564. _this.wAng = 0;
  31565. /**
  31566. * Defines the center of rotation (U)
  31567. */
  31568. _this.uRotationCenter = 0.5;
  31569. /**
  31570. * Defines the center of rotation (V)
  31571. */
  31572. _this.vRotationCenter = 0.5;
  31573. /**
  31574. * Defines the center of rotation (W)
  31575. */
  31576. _this.wRotationCenter = 0.5;
  31577. /**
  31578. * Observable triggered once the texture has been loaded.
  31579. */
  31580. _this.onLoadObservable = new BABYLON.Observable();
  31581. _this._isBlocking = true;
  31582. _this.name = url || "";
  31583. _this.url = url;
  31584. _this._noMipmap = noMipmap;
  31585. _this._invertY = invertY;
  31586. _this._samplingMode = samplingMode;
  31587. _this._buffer = buffer;
  31588. _this._deleteBuffer = deleteBuffer;
  31589. if (format) {
  31590. _this._format = format;
  31591. }
  31592. scene = _this.getScene();
  31593. if (!scene) {
  31594. return _this;
  31595. }
  31596. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31597. var load = function () {
  31598. if (_this.onLoadObservable.hasObservers()) {
  31599. _this.onLoadObservable.notifyObservers(_this);
  31600. }
  31601. if (onLoad) {
  31602. onLoad();
  31603. }
  31604. if (!_this.isBlocking && scene) {
  31605. scene.resetCachedMaterial();
  31606. }
  31607. };
  31608. if (!_this.url) {
  31609. _this._delayedOnLoad = load;
  31610. _this._delayedOnError = onError;
  31611. return _this;
  31612. }
  31613. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31614. if (!_this._texture) {
  31615. if (!scene.useDelayedTextureLoading) {
  31616. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31617. if (deleteBuffer) {
  31618. delete _this._buffer;
  31619. }
  31620. }
  31621. else {
  31622. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31623. _this._delayedOnLoad = load;
  31624. _this._delayedOnError = onError;
  31625. }
  31626. }
  31627. else {
  31628. if (_this._texture.isReady) {
  31629. BABYLON.Tools.SetImmediate(function () { return load(); });
  31630. }
  31631. else {
  31632. _this._texture.onLoadedObservable.add(load);
  31633. }
  31634. }
  31635. return _this;
  31636. }
  31637. Object.defineProperty(Texture.prototype, "noMipmap", {
  31638. /**
  31639. * Are mip maps generated for this texture or not.
  31640. */
  31641. get: function () {
  31642. return this._noMipmap;
  31643. },
  31644. enumerable: true,
  31645. configurable: true
  31646. });
  31647. Object.defineProperty(Texture.prototype, "isBlocking", {
  31648. get: function () {
  31649. return this._isBlocking;
  31650. },
  31651. /**
  31652. * Is the texture preventing material to render while loading.
  31653. * If false, a default texture will be used instead of the loading one during the preparation step.
  31654. */
  31655. set: function (value) {
  31656. this._isBlocking = value;
  31657. },
  31658. enumerable: true,
  31659. configurable: true
  31660. });
  31661. Object.defineProperty(Texture.prototype, "samplingMode", {
  31662. /**
  31663. * Get the current sampling mode associated with the texture.
  31664. */
  31665. get: function () {
  31666. return this._samplingMode;
  31667. },
  31668. enumerable: true,
  31669. configurable: true
  31670. });
  31671. /**
  31672. * Update the url (and optional buffer) of this texture if url was null during construction.
  31673. * @param url the url of the texture
  31674. * @param buffer the buffer of the texture (defaults to null)
  31675. */
  31676. Texture.prototype.updateURL = function (url, buffer) {
  31677. if (buffer === void 0) { buffer = null; }
  31678. if (this.url) {
  31679. throw new Error("URL is already set");
  31680. }
  31681. this.url = url;
  31682. this._buffer = buffer;
  31683. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31684. this.delayLoad();
  31685. };
  31686. /**
  31687. * Finish the loading sequence of a texture flagged as delayed load.
  31688. * @hidden
  31689. */
  31690. Texture.prototype.delayLoad = function () {
  31691. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31692. return;
  31693. }
  31694. var scene = this.getScene();
  31695. if (!scene) {
  31696. return;
  31697. }
  31698. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31699. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31700. if (!this._texture) {
  31701. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31702. if (this._deleteBuffer) {
  31703. delete this._buffer;
  31704. }
  31705. }
  31706. else {
  31707. if (this._delayedOnLoad) {
  31708. if (this._texture.isReady) {
  31709. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31710. }
  31711. else {
  31712. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31713. }
  31714. }
  31715. }
  31716. this._delayedOnLoad = null;
  31717. this._delayedOnError = null;
  31718. };
  31719. /**
  31720. * Update the sampling mode of the texture.
  31721. * Default is Trilinear mode.
  31722. *
  31723. * | Value | Type | Description |
  31724. * | ----- | ------------------ | ----------- |
  31725. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31726. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31727. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31728. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31729. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31730. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31731. * | 7 | NEAREST_LINEAR | |
  31732. * | 8 | NEAREST_NEAREST | |
  31733. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31734. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31735. * | 11 | LINEAR_LINEAR | |
  31736. * | 12 | LINEAR_NEAREST | |
  31737. *
  31738. * > _mag_: magnification filter (close to the viewer)
  31739. * > _min_: minification filter (far from the viewer)
  31740. * > _mip_: filter used between mip map levels
  31741. *@param samplingMode Define the new sampling mode of the texture
  31742. */
  31743. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31744. if (!this._texture) {
  31745. return;
  31746. }
  31747. var scene = this.getScene();
  31748. if (!scene) {
  31749. return;
  31750. }
  31751. this._samplingMode = samplingMode;
  31752. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31753. };
  31754. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31755. x *= this.uScale;
  31756. y *= this.vScale;
  31757. x -= this.uRotationCenter * this.uScale;
  31758. y -= this.vRotationCenter * this.vScale;
  31759. z -= this.wRotationCenter;
  31760. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31761. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31762. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31763. t.z += this.wRotationCenter;
  31764. };
  31765. /**
  31766. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31767. * @returns the transform matrix of the texture.
  31768. */
  31769. Texture.prototype.getTextureMatrix = function () {
  31770. var _this = this;
  31771. if (this.uOffset === this._cachedUOffset &&
  31772. this.vOffset === this._cachedVOffset &&
  31773. this.uScale === this._cachedUScale &&
  31774. this.vScale === this._cachedVScale &&
  31775. this.uAng === this._cachedUAng &&
  31776. this.vAng === this._cachedVAng &&
  31777. this.wAng === this._cachedWAng) {
  31778. return this._cachedTextureMatrix;
  31779. }
  31780. this._cachedUOffset = this.uOffset;
  31781. this._cachedVOffset = this.vOffset;
  31782. this._cachedUScale = this.uScale;
  31783. this._cachedVScale = this.vScale;
  31784. this._cachedUAng = this.uAng;
  31785. this._cachedVAng = this.vAng;
  31786. this._cachedWAng = this.wAng;
  31787. if (!this._cachedTextureMatrix) {
  31788. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31789. this._rowGenerationMatrix = new BABYLON.Matrix();
  31790. this._t0 = BABYLON.Vector3.Zero();
  31791. this._t1 = BABYLON.Vector3.Zero();
  31792. this._t2 = BABYLON.Vector3.Zero();
  31793. }
  31794. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31795. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31796. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31797. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31798. this._t1.subtractInPlace(this._t0);
  31799. this._t2.subtractInPlace(this._t0);
  31800. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31801. this._cachedTextureMatrix.m[0] = this._t1.x;
  31802. this._cachedTextureMatrix.m[1] = this._t1.y;
  31803. this._cachedTextureMatrix.m[2] = this._t1.z;
  31804. this._cachedTextureMatrix.m[4] = this._t2.x;
  31805. this._cachedTextureMatrix.m[5] = this._t2.y;
  31806. this._cachedTextureMatrix.m[6] = this._t2.z;
  31807. this._cachedTextureMatrix.m[8] = this._t0.x;
  31808. this._cachedTextureMatrix.m[9] = this._t0.y;
  31809. this._cachedTextureMatrix.m[10] = this._t0.z;
  31810. var scene = this.getScene();
  31811. if (!scene) {
  31812. return this._cachedTextureMatrix;
  31813. }
  31814. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31815. return mat.hasTexture(_this);
  31816. });
  31817. return this._cachedTextureMatrix;
  31818. };
  31819. /**
  31820. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31821. * @returns The reflection texture transform
  31822. */
  31823. Texture.prototype.getReflectionTextureMatrix = function () {
  31824. var _this = this;
  31825. var scene = this.getScene();
  31826. if (!scene) {
  31827. return this._cachedTextureMatrix;
  31828. }
  31829. if (this.uOffset === this._cachedUOffset &&
  31830. this.vOffset === this._cachedVOffset &&
  31831. this.uScale === this._cachedUScale &&
  31832. this.vScale === this._cachedVScale &&
  31833. this.coordinatesMode === this._cachedCoordinatesMode) {
  31834. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31835. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31836. return this._cachedTextureMatrix;
  31837. }
  31838. }
  31839. else {
  31840. return this._cachedTextureMatrix;
  31841. }
  31842. }
  31843. if (!this._cachedTextureMatrix) {
  31844. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31845. }
  31846. if (!this._projectionModeMatrix) {
  31847. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31848. }
  31849. this._cachedUOffset = this.uOffset;
  31850. this._cachedVOffset = this.vOffset;
  31851. this._cachedUScale = this.uScale;
  31852. this._cachedVScale = this.vScale;
  31853. this._cachedCoordinatesMode = this.coordinatesMode;
  31854. switch (this.coordinatesMode) {
  31855. case Texture.PLANAR_MODE:
  31856. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31857. this._cachedTextureMatrix[0] = this.uScale;
  31858. this._cachedTextureMatrix[5] = this.vScale;
  31859. this._cachedTextureMatrix[12] = this.uOffset;
  31860. this._cachedTextureMatrix[13] = this.vOffset;
  31861. break;
  31862. case Texture.PROJECTION_MODE:
  31863. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31864. this._projectionModeMatrix.m[0] = 0.5;
  31865. this._projectionModeMatrix.m[5] = -0.5;
  31866. this._projectionModeMatrix.m[10] = 0.0;
  31867. this._projectionModeMatrix.m[12] = 0.5;
  31868. this._projectionModeMatrix.m[13] = 0.5;
  31869. this._projectionModeMatrix.m[14] = 1.0;
  31870. this._projectionModeMatrix.m[15] = 1.0;
  31871. var projectionMatrix = scene.getProjectionMatrix();
  31872. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31873. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31874. break;
  31875. default:
  31876. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31877. break;
  31878. }
  31879. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31880. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31881. });
  31882. return this._cachedTextureMatrix;
  31883. };
  31884. /**
  31885. * Clones the texture.
  31886. * @returns the cloned texture
  31887. */
  31888. Texture.prototype.clone = function () {
  31889. var _this = this;
  31890. return BABYLON.SerializationHelper.Clone(function () {
  31891. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31892. }, this);
  31893. };
  31894. /**
  31895. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  31896. * @returns The JSON representation of the texture
  31897. */
  31898. Texture.prototype.serialize = function () {
  31899. var serializationObject = _super.prototype.serialize.call(this);
  31900. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31901. serializationObject.base64String = this._buffer;
  31902. serializationObject.name = serializationObject.name.replace("data:", "");
  31903. }
  31904. serializationObject.invertY = this._invertY;
  31905. serializationObject.samplingMode = this.samplingMode;
  31906. return serializationObject;
  31907. };
  31908. /**
  31909. * Get the current class name of the texture usefull for serialization or dynamic coding.
  31910. * @returns "Texture"
  31911. */
  31912. Texture.prototype.getClassName = function () {
  31913. return "Texture";
  31914. };
  31915. /**
  31916. * Dispose the texture and release its associated resources.
  31917. */
  31918. Texture.prototype.dispose = function () {
  31919. _super.prototype.dispose.call(this);
  31920. this.onLoadObservable.clear();
  31921. this._delayedOnLoad = null;
  31922. this._delayedOnError = null;
  31923. };
  31924. /**
  31925. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  31926. * @param parsedTexture Define the JSON representation of the texture
  31927. * @param scene Define the scene the parsed texture should be instantiated in
  31928. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  31929. * @returns The parsed texture if successful
  31930. */
  31931. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31932. if (parsedTexture.customType) {
  31933. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31934. // Update Sampling Mode
  31935. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31936. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31937. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31938. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31939. }
  31940. }
  31941. return parsedCustomTexture;
  31942. }
  31943. if (parsedTexture.isCube) {
  31944. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31945. }
  31946. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31947. return null;
  31948. }
  31949. var texture = BABYLON.SerializationHelper.Parse(function () {
  31950. var generateMipMaps = true;
  31951. if (parsedTexture.noMipmap) {
  31952. generateMipMaps = false;
  31953. }
  31954. if (parsedTexture.mirrorPlane) {
  31955. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31956. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31957. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31958. return mirrorTexture;
  31959. }
  31960. else if (parsedTexture.isRenderTarget) {
  31961. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31962. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31963. return renderTargetTexture;
  31964. }
  31965. else {
  31966. var texture;
  31967. if (parsedTexture.base64String) {
  31968. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31969. }
  31970. else {
  31971. var url = rootUrl + parsedTexture.name;
  31972. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31973. url = parsedTexture.url;
  31974. }
  31975. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31976. }
  31977. return texture;
  31978. }
  31979. }, parsedTexture, scene);
  31980. // Update Sampling Mode
  31981. if (parsedTexture.samplingMode) {
  31982. var sampling = parsedTexture.samplingMode;
  31983. if (texture._samplingMode !== sampling) {
  31984. texture.updateSamplingMode(sampling);
  31985. }
  31986. }
  31987. // Animations
  31988. if (parsedTexture.animations) {
  31989. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31990. var parsedAnimation = parsedTexture.animations[animationIndex];
  31991. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31992. }
  31993. }
  31994. return texture;
  31995. };
  31996. /**
  31997. * Creates a texture from its base 64 representation.
  31998. * @param data Define the base64 payload without the data: prefix
  31999. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32000. * @param scene Define the scene the texture should belong to
  32001. * @param noMipmap Forces the texture to not create mip map information if true
  32002. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32003. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32004. * @param onLoad define a callback triggered when the texture has been loaded
  32005. * @param onError define a callback triggered when an error occurred during the loading session
  32006. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32007. * @returns the created texture
  32008. */
  32009. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32010. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32011. if (onLoad === void 0) { onLoad = null; }
  32012. if (onError === void 0) { onError = null; }
  32013. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32014. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32015. };
  32016. /**
  32017. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32018. * @param data Define the base64 payload without the data: prefix
  32019. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32020. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32021. * @param scene Define the scene the texture should belong to
  32022. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32023. * @param noMipmap Forces the texture to not create mip map information if true
  32024. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32025. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32026. * @param onLoad define a callback triggered when the texture has been loaded
  32027. * @param onError define a callback triggered when an error occurred during the loading session
  32028. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32029. * @returns the created texture
  32030. */
  32031. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32032. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32033. if (noMipmap === void 0) { noMipmap = false; }
  32034. if (invertY === void 0) { invertY = true; }
  32035. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32036. if (onLoad === void 0) { onLoad = null; }
  32037. if (onError === void 0) { onError = null; }
  32038. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32039. if (name.substr(0, 5) !== "data:") {
  32040. name = "data:" + name;
  32041. }
  32042. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32043. };
  32044. /** nearest is mag = nearest and min = nearest and mip = linear */
  32045. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32046. /** nearest is mag = nearest and min = nearest and mip = linear */
  32047. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32048. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32049. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32050. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32051. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32052. /** Trilinear is mag = linear and min = linear and mip = linear */
  32053. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32054. /** Trilinear is mag = linear and min = linear and mip = linear */
  32055. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32056. /** mag = nearest and min = nearest and mip = nearest */
  32057. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32058. /** mag = nearest and min = linear and mip = nearest */
  32059. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32060. /** mag = nearest and min = linear and mip = linear */
  32061. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32062. /** mag = nearest and min = linear and mip = none */
  32063. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32064. /** mag = nearest and min = nearest and mip = none */
  32065. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32066. /** mag = linear and min = nearest and mip = nearest */
  32067. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32068. /** mag = linear and min = nearest and mip = linear */
  32069. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32070. /** mag = linear and min = linear and mip = none */
  32071. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32072. /** mag = linear and min = nearest and mip = none */
  32073. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32074. /** Explicit coordinates mode */
  32075. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32076. /** Spherical coordinates mode */
  32077. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32078. /** Planar coordinates mode */
  32079. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32080. /** Cubic coordinates mode */
  32081. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32082. /** Projection coordinates mode */
  32083. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32084. /** Inverse Cubic coordinates mode */
  32085. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32086. /** Inverse Cubic coordinates mode */
  32087. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32088. /** Equirectangular coordinates mode */
  32089. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32090. /** Equirectangular Fixed coordinates mode */
  32091. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32092. /** Equirectangular Fixed Mirrored coordinates mode */
  32093. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32094. /** Texture is not repeating outside of 0..1 UVs */
  32095. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32096. /** Texture is repeating outside of 0..1 UVs */
  32097. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32098. /** Texture is repeating and mirrored */
  32099. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32100. /**
  32101. * 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
  32102. */
  32103. Texture.UseSerializedUrlIfAny = false;
  32104. __decorate([
  32105. BABYLON.serialize()
  32106. ], Texture.prototype, "url", void 0);
  32107. __decorate([
  32108. BABYLON.serialize()
  32109. ], Texture.prototype, "uOffset", void 0);
  32110. __decorate([
  32111. BABYLON.serialize()
  32112. ], Texture.prototype, "vOffset", void 0);
  32113. __decorate([
  32114. BABYLON.serialize()
  32115. ], Texture.prototype, "uScale", void 0);
  32116. __decorate([
  32117. BABYLON.serialize()
  32118. ], Texture.prototype, "vScale", void 0);
  32119. __decorate([
  32120. BABYLON.serialize()
  32121. ], Texture.prototype, "uAng", void 0);
  32122. __decorate([
  32123. BABYLON.serialize()
  32124. ], Texture.prototype, "vAng", void 0);
  32125. __decorate([
  32126. BABYLON.serialize()
  32127. ], Texture.prototype, "wAng", void 0);
  32128. __decorate([
  32129. BABYLON.serialize()
  32130. ], Texture.prototype, "uRotationCenter", void 0);
  32131. __decorate([
  32132. BABYLON.serialize()
  32133. ], Texture.prototype, "vRotationCenter", void 0);
  32134. __decorate([
  32135. BABYLON.serialize()
  32136. ], Texture.prototype, "wRotationCenter", void 0);
  32137. __decorate([
  32138. BABYLON.serialize()
  32139. ], Texture.prototype, "isBlocking", null);
  32140. return Texture;
  32141. }(BABYLON.BaseTexture));
  32142. BABYLON.Texture = Texture;
  32143. })(BABYLON || (BABYLON = {}));
  32144. //# sourceMappingURL=babylon.texture.js.map
  32145. var BABYLON;
  32146. (function (BABYLON) {
  32147. /**
  32148. * @hidden
  32149. **/
  32150. var _CreationDataStorage = /** @class */ (function () {
  32151. function _CreationDataStorage() {
  32152. }
  32153. return _CreationDataStorage;
  32154. }());
  32155. BABYLON._CreationDataStorage = _CreationDataStorage;
  32156. /**
  32157. * @hidden
  32158. **/
  32159. var _InstanceDataStorage = /** @class */ (function () {
  32160. function _InstanceDataStorage() {
  32161. this.visibleInstances = {};
  32162. this.renderIdForInstances = new Array();
  32163. this.batchCache = new _InstancesBatch();
  32164. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32165. }
  32166. return _InstanceDataStorage;
  32167. }());
  32168. /**
  32169. * @hidden
  32170. **/
  32171. var _InstancesBatch = /** @class */ (function () {
  32172. function _InstancesBatch() {
  32173. this.mustReturn = false;
  32174. this.visibleInstances = new Array();
  32175. this.renderSelf = new Array();
  32176. }
  32177. return _InstancesBatch;
  32178. }());
  32179. BABYLON._InstancesBatch = _InstancesBatch;
  32180. /**
  32181. * Class used to represent renderable models
  32182. */
  32183. var Mesh = /** @class */ (function (_super) {
  32184. __extends(Mesh, _super);
  32185. /**
  32186. * @constructor
  32187. * @param name The value used by scene.getMeshByName() to do a lookup.
  32188. * @param scene The scene to add this mesh to.
  32189. * @param parent The parent of this mesh, if it has one
  32190. * @param source An optional Mesh from which geometry is shared, cloned.
  32191. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32192. * When false, achieved by calling a clone(), also passing False.
  32193. * This will make creation of children, recursive.
  32194. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32195. */
  32196. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32197. if (scene === void 0) { scene = null; }
  32198. if (parent === void 0) { parent = null; }
  32199. if (source === void 0) { source = null; }
  32200. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32201. var _this = _super.call(this, name, scene) || this;
  32202. // Members
  32203. /**
  32204. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32205. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32206. */
  32207. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32208. /**
  32209. * Gets the list of instances created from this mesh
  32210. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32211. */
  32212. _this.instances = new Array();
  32213. _this._LODLevels = new Array();
  32214. /** @hidden */
  32215. _this._instanceDataStorage = new _InstanceDataStorage();
  32216. // Use by builder only to know what orientation were the mesh build in.
  32217. /** @hidden */
  32218. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32219. /**
  32220. * Use this property to change the original side orientation defined at construction time
  32221. */
  32222. _this.overrideMaterialSideOrientation = null;
  32223. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32224. // Will be used to save a source mesh reference, If any
  32225. _this._source = null;
  32226. scene = _this.getScene();
  32227. if (source) {
  32228. // Geometry
  32229. if (source._geometry) {
  32230. source._geometry.applyToMesh(_this);
  32231. }
  32232. // Deep copy
  32233. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32234. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32235. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32236. ], ["_poseMatrix"]);
  32237. // Source mesh
  32238. _this._source = source;
  32239. // Construction Params
  32240. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32241. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32242. _this._creationDataStorage = source._creationDataStorage;
  32243. // Animation ranges
  32244. if (_this._source._ranges) {
  32245. var ranges = _this._source._ranges;
  32246. for (var name in ranges) {
  32247. if (!ranges.hasOwnProperty(name)) {
  32248. continue;
  32249. }
  32250. if (!ranges[name]) {
  32251. continue;
  32252. }
  32253. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32254. }
  32255. }
  32256. // Metadata
  32257. if (source.metadata && source.metadata.clone) {
  32258. _this.metadata = source.metadata.clone();
  32259. }
  32260. else {
  32261. _this.metadata = source.metadata;
  32262. }
  32263. // Tags
  32264. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32265. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32266. }
  32267. // Parent
  32268. _this.parent = source.parent;
  32269. // Pivot
  32270. _this.setPivotMatrix(source.getPivotMatrix());
  32271. _this.id = name + "." + source.id;
  32272. // Material
  32273. _this.material = source.material;
  32274. var index;
  32275. if (!doNotCloneChildren) {
  32276. // Children
  32277. var directDescendants = source.getDescendants(true);
  32278. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32279. var child = directDescendants[index_1];
  32280. if (child.clone) {
  32281. child.clone(name + "." + child.name, _this);
  32282. }
  32283. }
  32284. }
  32285. // Physics clone
  32286. var physicsEngine = _this.getScene().getPhysicsEngine();
  32287. if (clonePhysicsImpostor && physicsEngine) {
  32288. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32289. if (impostor) {
  32290. _this.physicsImpostor = impostor.clone(_this);
  32291. }
  32292. }
  32293. // Particles
  32294. for (index = 0; index < scene.particleSystems.length; index++) {
  32295. var system = scene.particleSystems[index];
  32296. if (system.emitter === source) {
  32297. system.clone(system.name, _this);
  32298. }
  32299. }
  32300. _this.refreshBoundingInfo();
  32301. _this.computeWorldMatrix(true);
  32302. }
  32303. // Parent
  32304. if (parent !== null) {
  32305. _this.parent = parent;
  32306. }
  32307. return _this;
  32308. }
  32309. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32310. /**
  32311. * An event triggered before rendering the mesh
  32312. */
  32313. get: function () {
  32314. if (!this._onBeforeRenderObservable) {
  32315. this._onBeforeRenderObservable = new BABYLON.Observable();
  32316. }
  32317. return this._onBeforeRenderObservable;
  32318. },
  32319. enumerable: true,
  32320. configurable: true
  32321. });
  32322. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32323. /**
  32324. * An event triggered after rendering the mesh
  32325. */
  32326. get: function () {
  32327. if (!this._onAfterRenderObservable) {
  32328. this._onAfterRenderObservable = new BABYLON.Observable();
  32329. }
  32330. return this._onAfterRenderObservable;
  32331. },
  32332. enumerable: true,
  32333. configurable: true
  32334. });
  32335. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32336. /**
  32337. * An event triggered before drawing the mesh
  32338. */
  32339. get: function () {
  32340. if (!this._onBeforeDrawObservable) {
  32341. this._onBeforeDrawObservable = new BABYLON.Observable();
  32342. }
  32343. return this._onBeforeDrawObservable;
  32344. },
  32345. enumerable: true,
  32346. configurable: true
  32347. });
  32348. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32349. /**
  32350. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32351. */
  32352. set: function (callback) {
  32353. if (this._onBeforeDrawObserver) {
  32354. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32355. }
  32356. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32357. },
  32358. enumerable: true,
  32359. configurable: true
  32360. });
  32361. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32362. /**
  32363. * Gets or sets the morph target manager
  32364. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32365. */
  32366. get: function () {
  32367. return this._morphTargetManager;
  32368. },
  32369. set: function (value) {
  32370. if (this._morphTargetManager === value) {
  32371. return;
  32372. }
  32373. this._morphTargetManager = value;
  32374. this._syncGeometryWithMorphTargetManager();
  32375. },
  32376. enumerable: true,
  32377. configurable: true
  32378. });
  32379. Object.defineProperty(Mesh.prototype, "source", {
  32380. /**
  32381. * Gets the source mesh (the one used to clone this one from)
  32382. */
  32383. get: function () {
  32384. return this._source;
  32385. },
  32386. enumerable: true,
  32387. configurable: true
  32388. });
  32389. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32390. /**
  32391. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32392. */
  32393. get: function () {
  32394. return this._unIndexed;
  32395. },
  32396. set: function (value) {
  32397. if (this._unIndexed !== value) {
  32398. this._unIndexed = value;
  32399. this._markSubMeshesAsAttributesDirty();
  32400. }
  32401. },
  32402. enumerable: true,
  32403. configurable: true
  32404. });
  32405. // Methods
  32406. /**
  32407. * Gets the class name
  32408. * @returns the string "Mesh".
  32409. */
  32410. Mesh.prototype.getClassName = function () {
  32411. return "Mesh";
  32412. };
  32413. /**
  32414. * Returns a description of this mesh
  32415. * @param fullDetails define if full details about this mesh must be used
  32416. * @returns a descriptive string representing this mesh
  32417. */
  32418. Mesh.prototype.toString = function (fullDetails) {
  32419. var ret = _super.prototype.toString.call(this, fullDetails);
  32420. ret += ", n vertices: " + this.getTotalVertices();
  32421. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32422. if (this.animations) {
  32423. for (var i = 0; i < this.animations.length; i++) {
  32424. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32425. }
  32426. }
  32427. if (fullDetails) {
  32428. if (this._geometry) {
  32429. var ib = this.getIndices();
  32430. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32431. if (vb && ib) {
  32432. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32433. }
  32434. }
  32435. else {
  32436. ret += ", flat shading: UNKNOWN";
  32437. }
  32438. }
  32439. return ret;
  32440. };
  32441. /** @hidden */
  32442. Mesh.prototype._unBindEffect = function () {
  32443. _super.prototype._unBindEffect.call(this);
  32444. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32445. var instance = _a[_i];
  32446. instance._unBindEffect();
  32447. }
  32448. };
  32449. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32450. /**
  32451. * Gets a boolean indicating if this mesh has LOD
  32452. */
  32453. get: function () {
  32454. return this._LODLevels.length > 0;
  32455. },
  32456. enumerable: true,
  32457. configurable: true
  32458. });
  32459. /**
  32460. * Gets the list of MeshLODLevel associated with the current mesh
  32461. * @returns an array of MeshLODLevel
  32462. */
  32463. Mesh.prototype.getLODLevels = function () {
  32464. return this._LODLevels;
  32465. };
  32466. Mesh.prototype._sortLODLevels = function () {
  32467. this._LODLevels.sort(function (a, b) {
  32468. if (a.distance < b.distance) {
  32469. return 1;
  32470. }
  32471. if (a.distance > b.distance) {
  32472. return -1;
  32473. }
  32474. return 0;
  32475. });
  32476. };
  32477. /**
  32478. * Add a mesh as LOD level triggered at the given distance.
  32479. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32480. * @param distance The distance from the center of the object to show this level
  32481. * @param mesh The mesh to be added as LOD level (can be null)
  32482. * @return This mesh (for chaining)
  32483. */
  32484. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32485. if (mesh && mesh._masterMesh) {
  32486. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32487. return this;
  32488. }
  32489. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32490. this._LODLevels.push(level);
  32491. if (mesh) {
  32492. mesh._masterMesh = this;
  32493. }
  32494. this._sortLODLevels();
  32495. return this;
  32496. };
  32497. /**
  32498. * Returns the LOD level mesh at the passed distance or null if not found.
  32499. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32500. * @param distance The distance from the center of the object to show this level
  32501. * @returns a Mesh or `null`
  32502. */
  32503. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32504. for (var index = 0; index < this._LODLevels.length; index++) {
  32505. var level = this._LODLevels[index];
  32506. if (level.distance === distance) {
  32507. return level.mesh;
  32508. }
  32509. }
  32510. return null;
  32511. };
  32512. /**
  32513. * Remove a mesh from the LOD array
  32514. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32515. * @param mesh defines the mesh to be removed
  32516. * @return This mesh (for chaining)
  32517. */
  32518. Mesh.prototype.removeLODLevel = function (mesh) {
  32519. for (var index = 0; index < this._LODLevels.length; index++) {
  32520. if (this._LODLevels[index].mesh === mesh) {
  32521. this._LODLevels.splice(index, 1);
  32522. if (mesh) {
  32523. mesh._masterMesh = null;
  32524. }
  32525. }
  32526. }
  32527. this._sortLODLevels();
  32528. return this;
  32529. };
  32530. /**
  32531. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32532. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32533. * @param camera defines the camera to use to compute distance
  32534. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32535. * @return This mesh (for chaining)
  32536. */
  32537. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32538. if (!this._LODLevels || this._LODLevels.length === 0) {
  32539. return this;
  32540. }
  32541. var bSphere;
  32542. if (boundingSphere) {
  32543. bSphere = boundingSphere;
  32544. }
  32545. else {
  32546. var boundingInfo = this.getBoundingInfo();
  32547. bSphere = boundingInfo.boundingSphere;
  32548. }
  32549. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32550. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32551. if (this.onLODLevelSelection) {
  32552. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32553. }
  32554. return this;
  32555. }
  32556. for (var index = 0; index < this._LODLevels.length; index++) {
  32557. var level = this._LODLevels[index];
  32558. if (level.distance < distanceToCamera) {
  32559. if (level.mesh) {
  32560. level.mesh._preActivate();
  32561. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32562. }
  32563. if (this.onLODLevelSelection) {
  32564. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32565. }
  32566. return level.mesh;
  32567. }
  32568. }
  32569. if (this.onLODLevelSelection) {
  32570. this.onLODLevelSelection(distanceToCamera, this, this);
  32571. }
  32572. return this;
  32573. };
  32574. Object.defineProperty(Mesh.prototype, "geometry", {
  32575. /**
  32576. * Gets the mesh internal Geometry object
  32577. */
  32578. get: function () {
  32579. return this._geometry;
  32580. },
  32581. enumerable: true,
  32582. configurable: true
  32583. });
  32584. /**
  32585. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32586. * @returns the total number of vertices
  32587. */
  32588. Mesh.prototype.getTotalVertices = function () {
  32589. if (this._geometry === null || this._geometry === undefined) {
  32590. return 0;
  32591. }
  32592. return this._geometry.getTotalVertices();
  32593. };
  32594. /**
  32595. * Returns the content of an associated vertex buffer
  32596. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32597. * - BABYLON.VertexBuffer.PositionKind
  32598. * - BABYLON.VertexBuffer.UVKind
  32599. * - BABYLON.VertexBuffer.UV2Kind
  32600. * - BABYLON.VertexBuffer.UV3Kind
  32601. * - BABYLON.VertexBuffer.UV4Kind
  32602. * - BABYLON.VertexBuffer.UV5Kind
  32603. * - BABYLON.VertexBuffer.UV6Kind
  32604. * - BABYLON.VertexBuffer.ColorKind
  32605. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32606. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32607. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32608. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32609. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  32610. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32611. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32612. */
  32613. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32614. if (!this._geometry) {
  32615. return null;
  32616. }
  32617. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32618. };
  32619. /**
  32620. * Returns the mesh VertexBuffer object from the requested `kind`
  32621. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32622. * - BABYLON.VertexBuffer.PositionKind
  32623. * - BABYLON.VertexBuffer.UVKind
  32624. * - BABYLON.VertexBuffer.UV2Kind
  32625. * - BABYLON.VertexBuffer.UV3Kind
  32626. * - BABYLON.VertexBuffer.UV4Kind
  32627. * - BABYLON.VertexBuffer.UV5Kind
  32628. * - BABYLON.VertexBuffer.UV6Kind
  32629. * - BABYLON.VertexBuffer.ColorKind
  32630. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32631. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32632. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32633. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32634. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32635. */
  32636. Mesh.prototype.getVertexBuffer = function (kind) {
  32637. if (!this._geometry) {
  32638. return null;
  32639. }
  32640. return this._geometry.getVertexBuffer(kind);
  32641. };
  32642. /**
  32643. * Tests if a specific vertex buffer is associated with this mesh
  32644. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32645. * - BABYLON.VertexBuffer.PositionKind
  32646. * - BABYLON.VertexBuffer.UVKind
  32647. * - BABYLON.VertexBuffer.UV2Kind
  32648. * - BABYLON.VertexBuffer.UV3Kind
  32649. * - BABYLON.VertexBuffer.UV4Kind
  32650. * - BABYLON.VertexBuffer.UV5Kind
  32651. * - BABYLON.VertexBuffer.UV6Kind
  32652. * - BABYLON.VertexBuffer.ColorKind
  32653. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32654. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32655. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32656. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32657. * @returns a boolean
  32658. */
  32659. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32660. if (!this._geometry) {
  32661. if (this._delayInfo) {
  32662. return this._delayInfo.indexOf(kind) !== -1;
  32663. }
  32664. return false;
  32665. }
  32666. return this._geometry.isVerticesDataPresent(kind);
  32667. };
  32668. /**
  32669. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32670. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32671. * - BABYLON.VertexBuffer.PositionKind
  32672. * - BABYLON.VertexBuffer.UVKind
  32673. * - BABYLON.VertexBuffer.UV2Kind
  32674. * - BABYLON.VertexBuffer.UV3Kind
  32675. * - BABYLON.VertexBuffer.UV4Kind
  32676. * - BABYLON.VertexBuffer.UV5Kind
  32677. * - BABYLON.VertexBuffer.UV6Kind
  32678. * - BABYLON.VertexBuffer.ColorKind
  32679. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32680. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32681. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32682. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32683. * @returns a boolean
  32684. */
  32685. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32686. if (!this._geometry) {
  32687. if (this._delayInfo) {
  32688. return this._delayInfo.indexOf(kind) !== -1;
  32689. }
  32690. return false;
  32691. }
  32692. return this._geometry.isVertexBufferUpdatable(kind);
  32693. };
  32694. /**
  32695. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32696. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32697. * - BABYLON.VertexBuffer.PositionKind
  32698. * - BABYLON.VertexBuffer.UVKind
  32699. * - BABYLON.VertexBuffer.UV2Kind
  32700. * - BABYLON.VertexBuffer.UV3Kind
  32701. * - BABYLON.VertexBuffer.UV4Kind
  32702. * - BABYLON.VertexBuffer.UV5Kind
  32703. * - BABYLON.VertexBuffer.UV6Kind
  32704. * - BABYLON.VertexBuffer.ColorKind
  32705. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32706. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32707. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32708. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32709. * @returns an array of strings
  32710. */
  32711. Mesh.prototype.getVerticesDataKinds = function () {
  32712. if (!this._geometry) {
  32713. var result = new Array();
  32714. if (this._delayInfo) {
  32715. this._delayInfo.forEach(function (kind, index, array) {
  32716. result.push(kind);
  32717. });
  32718. }
  32719. return result;
  32720. }
  32721. return this._geometry.getVerticesDataKinds();
  32722. };
  32723. /**
  32724. * Returns a positive integer : the total number of indices in this mesh geometry.
  32725. * @returns the numner of indices or zero if the mesh has no geometry.
  32726. */
  32727. Mesh.prototype.getTotalIndices = function () {
  32728. if (!this._geometry) {
  32729. return 0;
  32730. }
  32731. return this._geometry.getTotalIndices();
  32732. };
  32733. /**
  32734. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32735. * @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.
  32736. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32737. * @returns the indices array or an empty array if the mesh has no geometry
  32738. */
  32739. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32740. if (!this._geometry) {
  32741. return [];
  32742. }
  32743. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32744. };
  32745. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32746. get: function () {
  32747. return this._masterMesh !== null && this._masterMesh !== undefined;
  32748. },
  32749. enumerable: true,
  32750. configurable: true
  32751. });
  32752. /**
  32753. * Determine if the current mesh is ready to be rendered
  32754. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32755. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32756. * @returns true if all associated assets are ready (material, textures, shaders)
  32757. */
  32758. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32759. if (completeCheck === void 0) { completeCheck = false; }
  32760. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32761. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32762. return false;
  32763. }
  32764. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32765. return false;
  32766. }
  32767. if (!this.subMeshes || this.subMeshes.length === 0) {
  32768. return true;
  32769. }
  32770. if (!completeCheck) {
  32771. return true;
  32772. }
  32773. var engine = this.getEngine();
  32774. var scene = this.getScene();
  32775. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32776. this.computeWorldMatrix();
  32777. var mat = this.material || scene.defaultMaterial;
  32778. if (mat) {
  32779. if (mat.storeEffectOnSubMeshes) {
  32780. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32781. var subMesh = _a[_i];
  32782. var effectiveMaterial = subMesh.getMaterial();
  32783. if (effectiveMaterial) {
  32784. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32785. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32786. return false;
  32787. }
  32788. }
  32789. else {
  32790. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32791. return false;
  32792. }
  32793. }
  32794. }
  32795. }
  32796. }
  32797. else {
  32798. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32799. return false;
  32800. }
  32801. }
  32802. }
  32803. // Shadows
  32804. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32805. var light = _c[_b];
  32806. var generator = light.getShadowGenerator();
  32807. if (generator) {
  32808. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32809. var subMesh = _e[_d];
  32810. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32811. return false;
  32812. }
  32813. }
  32814. }
  32815. }
  32816. // LOD
  32817. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32818. var lod = _g[_f];
  32819. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32820. return false;
  32821. }
  32822. }
  32823. return true;
  32824. };
  32825. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32826. /**
  32827. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  32828. */
  32829. get: function () {
  32830. return this._areNormalsFrozen;
  32831. },
  32832. enumerable: true,
  32833. configurable: true
  32834. });
  32835. /**
  32836. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  32837. * @returns the current mesh
  32838. */
  32839. Mesh.prototype.freezeNormals = function () {
  32840. this._areNormalsFrozen = true;
  32841. return this;
  32842. };
  32843. /**
  32844. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  32845. * @returns the current mesh
  32846. */
  32847. Mesh.prototype.unfreezeNormals = function () {
  32848. this._areNormalsFrozen = false;
  32849. return this;
  32850. };
  32851. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32852. /**
  32853. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32854. */
  32855. set: function (count) {
  32856. this._instanceDataStorage.overridenInstanceCount = count;
  32857. },
  32858. enumerable: true,
  32859. configurable: true
  32860. });
  32861. // Methods
  32862. /** @hidden */
  32863. Mesh.prototype._preActivate = function () {
  32864. var sceneRenderId = this.getScene().getRenderId();
  32865. if (this._preActivateId === sceneRenderId) {
  32866. return this;
  32867. }
  32868. this._preActivateId = sceneRenderId;
  32869. this._instanceDataStorage.visibleInstances = null;
  32870. return this;
  32871. };
  32872. /** @hidden */
  32873. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32874. if (this._instanceDataStorage.visibleInstances) {
  32875. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32876. }
  32877. return this;
  32878. };
  32879. /** @hidden */
  32880. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32881. if (!this._instanceDataStorage.visibleInstances) {
  32882. this._instanceDataStorage.visibleInstances = {};
  32883. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32884. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32885. }
  32886. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32887. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32888. }
  32889. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32890. return this;
  32891. };
  32892. /**
  32893. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32894. * This means the mesh underlying bounding box and sphere are recomputed.
  32895. * @returns the current mesh
  32896. */
  32897. Mesh.prototype.refreshBoundingInfo = function () {
  32898. return this._refreshBoundingInfo(false);
  32899. };
  32900. /** @hidden */
  32901. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32902. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32903. return this;
  32904. }
  32905. var data = this._getPositionData(applySkeleton);
  32906. if (data) {
  32907. var bias = this.geometry ? this.geometry.boundingBias : null;
  32908. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32909. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32910. }
  32911. if (this.subMeshes) {
  32912. for (var index = 0; index < this.subMeshes.length; index++) {
  32913. this.subMeshes[index].refreshBoundingInfo();
  32914. }
  32915. }
  32916. this._updateBoundingInfo();
  32917. return this;
  32918. };
  32919. Mesh.prototype._getPositionData = function (applySkeleton) {
  32920. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32921. if (data && applySkeleton && this.skeleton) {
  32922. data = BABYLON.Tools.Slice(data);
  32923. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32924. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32925. if (matricesWeightsData && matricesIndicesData) {
  32926. var needExtras = this.numBoneInfluencers > 4;
  32927. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32928. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32929. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32930. var tempVector = BABYLON.Tmp.Vector3[0];
  32931. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32932. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32933. var matWeightIdx = 0;
  32934. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32935. finalMatrix.reset();
  32936. var inf;
  32937. var weight;
  32938. for (inf = 0; inf < 4; inf++) {
  32939. weight = matricesWeightsData[matWeightIdx + inf];
  32940. if (weight > 0) {
  32941. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32942. finalMatrix.addToSelf(tempMatrix);
  32943. }
  32944. }
  32945. if (needExtras) {
  32946. for (inf = 0; inf < 4; inf++) {
  32947. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32948. if (weight > 0) {
  32949. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32950. finalMatrix.addToSelf(tempMatrix);
  32951. }
  32952. }
  32953. }
  32954. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32955. tempVector.toArray(data, index);
  32956. }
  32957. }
  32958. }
  32959. return data;
  32960. };
  32961. /** @hidden */
  32962. Mesh.prototype._createGlobalSubMesh = function (force) {
  32963. var totalVertices = this.getTotalVertices();
  32964. if (!totalVertices || !this.getIndices()) {
  32965. return null;
  32966. }
  32967. // Check if we need to recreate the submeshes
  32968. if (this.subMeshes && this.subMeshes.length > 0) {
  32969. var ib = this.getIndices();
  32970. if (!ib) {
  32971. return null;
  32972. }
  32973. var totalIndices = ib.length;
  32974. var needToRecreate = false;
  32975. if (force) {
  32976. needToRecreate = true;
  32977. }
  32978. else {
  32979. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32980. var submesh = _a[_i];
  32981. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32982. needToRecreate = true;
  32983. break;
  32984. }
  32985. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32986. needToRecreate = true;
  32987. break;
  32988. }
  32989. }
  32990. }
  32991. if (!needToRecreate) {
  32992. return this.subMeshes[0];
  32993. }
  32994. }
  32995. this.releaseSubMeshes();
  32996. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32997. };
  32998. /**
  32999. * This function will subdivide the mesh into multiple submeshes
  33000. * @param count defines the expected number of submeshes
  33001. */
  33002. Mesh.prototype.subdivide = function (count) {
  33003. if (count < 1) {
  33004. return;
  33005. }
  33006. var totalIndices = this.getTotalIndices();
  33007. var subdivisionSize = (totalIndices / count) | 0;
  33008. var offset = 0;
  33009. // Ensure that subdivisionSize is a multiple of 3
  33010. while (subdivisionSize % 3 !== 0) {
  33011. subdivisionSize++;
  33012. }
  33013. this.releaseSubMeshes();
  33014. for (var index = 0; index < count; index++) {
  33015. if (offset >= totalIndices) {
  33016. break;
  33017. }
  33018. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33019. offset += subdivisionSize;
  33020. }
  33021. this.synchronizeInstances();
  33022. };
  33023. /**
  33024. * Copy a FloatArray into a specific associated vertex buffer
  33025. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33026. * - BABYLON.VertexBuffer.PositionKind
  33027. * - BABYLON.VertexBuffer.UVKind
  33028. * - BABYLON.VertexBuffer.UV2Kind
  33029. * - BABYLON.VertexBuffer.UV3Kind
  33030. * - BABYLON.VertexBuffer.UV4Kind
  33031. * - BABYLON.VertexBuffer.UV5Kind
  33032. * - BABYLON.VertexBuffer.UV6Kind
  33033. * - BABYLON.VertexBuffer.ColorKind
  33034. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33035. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33036. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33037. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33038. * @param data defines the data source
  33039. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33040. * @param stride defines the data stride size (can be null)
  33041. * @returns the current mesh
  33042. */
  33043. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33044. if (updatable === void 0) { updatable = false; }
  33045. if (!this._geometry) {
  33046. var vertexData = new BABYLON.VertexData();
  33047. vertexData.set(data, kind);
  33048. var scene = this.getScene();
  33049. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33050. }
  33051. else {
  33052. this._geometry.setVerticesData(kind, data, updatable, stride);
  33053. }
  33054. return this;
  33055. };
  33056. /**
  33057. * Flags an associated vertex buffer as updatable
  33058. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33059. * - BABYLON.VertexBuffer.PositionKind
  33060. * - BABYLON.VertexBuffer.UVKind
  33061. * - BABYLON.VertexBuffer.UV2Kind
  33062. * - BABYLON.VertexBuffer.UV3Kind
  33063. * - BABYLON.VertexBuffer.UV4Kind
  33064. * - BABYLON.VertexBuffer.UV5Kind
  33065. * - BABYLON.VertexBuffer.UV6Kind
  33066. * - BABYLON.VertexBuffer.ColorKind
  33067. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33068. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33069. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33070. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33071. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33072. */
  33073. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33074. if (updatable === void 0) { updatable = true; }
  33075. var vb = this.getVertexBuffer(kind);
  33076. if (!vb || vb.isUpdatable() === updatable) {
  33077. return;
  33078. }
  33079. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33080. };
  33081. /**
  33082. * Sets the mesh global Vertex Buffer
  33083. * @param buffer defines the buffer to use
  33084. * @returns the current mesh
  33085. */
  33086. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33087. if (!this._geometry) {
  33088. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33089. }
  33090. this._geometry.setVerticesBuffer(buffer);
  33091. return this;
  33092. };
  33093. /**
  33094. * Update a specific associated vertex buffer
  33095. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33096. * - BABYLON.VertexBuffer.PositionKind
  33097. * - BABYLON.VertexBuffer.UVKind
  33098. * - BABYLON.VertexBuffer.UV2Kind
  33099. * - BABYLON.VertexBuffer.UV3Kind
  33100. * - BABYLON.VertexBuffer.UV4Kind
  33101. * - BABYLON.VertexBuffer.UV5Kind
  33102. * - BABYLON.VertexBuffer.UV6Kind
  33103. * - BABYLON.VertexBuffer.ColorKind
  33104. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33105. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33106. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33107. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33108. * @param data defines the data source
  33109. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33110. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  33111. * @returns the current mesh
  33112. */
  33113. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33114. if (!this._geometry) {
  33115. return this;
  33116. }
  33117. if (!makeItUnique) {
  33118. this._geometry.updateVerticesData(kind, data, updateExtends);
  33119. }
  33120. else {
  33121. this.makeGeometryUnique();
  33122. this.updateVerticesData(kind, data, updateExtends, false);
  33123. }
  33124. return this;
  33125. };
  33126. /**
  33127. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33128. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33129. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33130. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33131. * @returns the current mesh
  33132. */
  33133. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33134. if (computeNormals === void 0) { computeNormals = true; }
  33135. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33136. if (!positions) {
  33137. return this;
  33138. }
  33139. positionFunction(positions);
  33140. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33141. if (computeNormals) {
  33142. var indices = this.getIndices();
  33143. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33144. if (!normals) {
  33145. return this;
  33146. }
  33147. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33148. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33149. }
  33150. return this;
  33151. };
  33152. /**
  33153. * Creates a un-shared specific occurence of the geometry for the mesh.
  33154. * @returns the current mesh
  33155. */
  33156. Mesh.prototype.makeGeometryUnique = function () {
  33157. if (!this._geometry) {
  33158. return this;
  33159. }
  33160. var oldGeometry = this._geometry;
  33161. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33162. oldGeometry.releaseForMesh(this, true);
  33163. geometry.applyToMesh(this);
  33164. return this;
  33165. };
  33166. /**
  33167. * Set the index buffer of this mesh
  33168. * @param indices defines the source data
  33169. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33170. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33171. * @returns the current mesh
  33172. */
  33173. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33174. if (totalVertices === void 0) { totalVertices = null; }
  33175. if (updatable === void 0) { updatable = false; }
  33176. if (!this._geometry) {
  33177. var vertexData = new BABYLON.VertexData();
  33178. vertexData.indices = indices;
  33179. var scene = this.getScene();
  33180. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33181. }
  33182. else {
  33183. this._geometry.setIndices(indices, totalVertices, updatable);
  33184. }
  33185. return this;
  33186. };
  33187. /**
  33188. * Update the current index buffer
  33189. * @param indices defines the source data
  33190. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33191. * @returns the current mesh
  33192. */
  33193. Mesh.prototype.updateIndices = function (indices, offset) {
  33194. if (!this._geometry) {
  33195. return this;
  33196. }
  33197. this._geometry.updateIndices(indices, offset);
  33198. return this;
  33199. };
  33200. /**
  33201. * Invert the geometry to move from a right handed system to a left handed one.
  33202. * @returns the current mesh
  33203. */
  33204. Mesh.prototype.toLeftHanded = function () {
  33205. if (!this._geometry) {
  33206. return this;
  33207. }
  33208. this._geometry.toLeftHanded();
  33209. return this;
  33210. };
  33211. /** @hidden */
  33212. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33213. if (!this._geometry) {
  33214. return this;
  33215. }
  33216. var engine = this.getScene().getEngine();
  33217. // Wireframe
  33218. var indexToBind;
  33219. if (this._unIndexed) {
  33220. indexToBind = null;
  33221. }
  33222. else {
  33223. switch (fillMode) {
  33224. case BABYLON.Material.PointFillMode:
  33225. indexToBind = null;
  33226. break;
  33227. case BABYLON.Material.WireFrameFillMode:
  33228. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33229. break;
  33230. default:
  33231. case BABYLON.Material.TriangleFillMode:
  33232. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33233. break;
  33234. }
  33235. }
  33236. // VBOs
  33237. this._geometry._bind(effect, indexToBind);
  33238. return this;
  33239. };
  33240. /** @hidden */
  33241. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33242. if (alternate === void 0) { alternate = false; }
  33243. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33244. return this;
  33245. }
  33246. if (this._onBeforeDrawObservable) {
  33247. this._onBeforeDrawObservable.notifyObservers(this);
  33248. }
  33249. var scene = this.getScene();
  33250. var engine = scene.getEngine();
  33251. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33252. // or triangles as points
  33253. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33254. }
  33255. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33256. // Triangles as wireframe
  33257. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33258. }
  33259. else {
  33260. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33261. }
  33262. if (scene._isAlternateRenderingEnabled && !alternate) {
  33263. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33264. if (!effect || !scene.activeCamera) {
  33265. return this;
  33266. }
  33267. scene._switchToAlternateCameraConfiguration(true);
  33268. this._effectiveMaterial.bindView(effect);
  33269. this._effectiveMaterial.bindViewProjection(effect);
  33270. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33271. this._draw(subMesh, fillMode, instancesCount, true);
  33272. engine.setViewport(scene.activeCamera.viewport);
  33273. scene._switchToAlternateCameraConfiguration(false);
  33274. this._effectiveMaterial.bindView(effect);
  33275. this._effectiveMaterial.bindViewProjection(effect);
  33276. }
  33277. return this;
  33278. };
  33279. /**
  33280. * Registers for this mesh a javascript function called just before the rendering process
  33281. * @param func defines the function to call before rendering this mesh
  33282. * @returns the current mesh
  33283. */
  33284. Mesh.prototype.registerBeforeRender = function (func) {
  33285. this.onBeforeRenderObservable.add(func);
  33286. return this;
  33287. };
  33288. /**
  33289. * Disposes a previously registered javascript function called before the rendering
  33290. * @param func defines the function to remove
  33291. * @returns the current mesh
  33292. */
  33293. Mesh.prototype.unregisterBeforeRender = function (func) {
  33294. this.onBeforeRenderObservable.removeCallback(func);
  33295. return this;
  33296. };
  33297. /**
  33298. * Registers for this mesh a javascript function called just after the rendering is complete
  33299. * @param func defines the function to call after rendering this mesh
  33300. * @returns the current mesh
  33301. */
  33302. Mesh.prototype.registerAfterRender = function (func) {
  33303. this.onAfterRenderObservable.add(func);
  33304. return this;
  33305. };
  33306. /**
  33307. * Disposes a previously registered javascript function called after the rendering.
  33308. * @param func defines the function to remove
  33309. * @returns the current mesh
  33310. */
  33311. Mesh.prototype.unregisterAfterRender = function (func) {
  33312. this.onAfterRenderObservable.removeCallback(func);
  33313. return this;
  33314. };
  33315. /** @hidden */
  33316. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33317. var scene = this.getScene();
  33318. var batchCache = this._instanceDataStorage.batchCache;
  33319. batchCache.mustReturn = false;
  33320. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33321. batchCache.visibleInstances[subMeshId] = null;
  33322. if (this._instanceDataStorage.visibleInstances) {
  33323. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33324. var currentRenderId = scene.getRenderId();
  33325. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33326. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33327. var selfRenderId = this._renderId;
  33328. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33329. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33330. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33331. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33332. }
  33333. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33334. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33335. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33336. batchCache.mustReturn = true;
  33337. return batchCache;
  33338. }
  33339. if (currentRenderId !== selfRenderId) {
  33340. batchCache.renderSelf[subMeshId] = false;
  33341. }
  33342. }
  33343. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33344. }
  33345. return batchCache;
  33346. };
  33347. /** @hidden */
  33348. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33349. var visibleInstances = batch.visibleInstances[subMesh._id];
  33350. if (!visibleInstances) {
  33351. return this;
  33352. }
  33353. var matricesCount = visibleInstances.length + 1;
  33354. var bufferSize = matricesCount * 16 * 4;
  33355. var instanceStorage = this._instanceDataStorage;
  33356. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33357. var instancesBuffer = instanceStorage.instancesBuffer;
  33358. while (instanceStorage.instancesBufferSize < bufferSize) {
  33359. instanceStorage.instancesBufferSize *= 2;
  33360. }
  33361. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33362. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33363. }
  33364. var offset = 0;
  33365. var instancesCount = 0;
  33366. var world = this.getWorldMatrix();
  33367. if (batch.renderSelf[subMesh._id]) {
  33368. world.copyToArray(instanceStorage.instancesData, offset);
  33369. offset += 16;
  33370. instancesCount++;
  33371. }
  33372. if (visibleInstances) {
  33373. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33374. var instance = visibleInstances[instanceIndex];
  33375. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33376. offset += 16;
  33377. instancesCount++;
  33378. }
  33379. }
  33380. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33381. if (instancesBuffer) {
  33382. instancesBuffer.dispose();
  33383. }
  33384. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33385. instanceStorage.instancesBuffer = instancesBuffer;
  33386. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33387. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33388. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33389. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33390. }
  33391. else {
  33392. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33393. }
  33394. this._bind(subMesh, effect, fillMode);
  33395. this._draw(subMesh, fillMode, instancesCount);
  33396. engine.unbindInstanceAttributes();
  33397. return this;
  33398. };
  33399. /** @hidden */
  33400. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33401. var scene = this.getScene();
  33402. var engine = scene.getEngine();
  33403. if (hardwareInstancedRendering) {
  33404. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33405. }
  33406. else {
  33407. if (batch.renderSelf[subMesh._id]) {
  33408. // Draw
  33409. if (onBeforeDraw) {
  33410. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33411. }
  33412. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33413. }
  33414. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33415. if (visibleInstancesForSubMesh) {
  33416. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33417. var instance = visibleInstancesForSubMesh[instanceIndex];
  33418. // World
  33419. var world = instance.getWorldMatrix();
  33420. if (onBeforeDraw) {
  33421. onBeforeDraw(true, world, effectiveMaterial);
  33422. }
  33423. // Draw
  33424. this._draw(subMesh, fillMode);
  33425. }
  33426. }
  33427. }
  33428. return this;
  33429. };
  33430. /**
  33431. * 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
  33432. * @param subMesh defines the subMesh to render
  33433. * @param enableAlphaMode defines if alpha mode can be changed
  33434. * @returns the current mesh
  33435. */
  33436. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33437. if (this._checkOcclusionQuery()) {
  33438. return this;
  33439. }
  33440. var scene = this.getScene();
  33441. // Managing instances
  33442. var batch = this._getInstancesRenderList(subMesh._id);
  33443. if (batch.mustReturn) {
  33444. return this;
  33445. }
  33446. // Checking geometry state
  33447. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33448. return this;
  33449. }
  33450. if (this._onBeforeRenderObservable) {
  33451. this._onBeforeRenderObservable.notifyObservers(this);
  33452. }
  33453. var engine = scene.getEngine();
  33454. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33455. // Material
  33456. var material = subMesh.getMaterial();
  33457. if (!material) {
  33458. return this;
  33459. }
  33460. this._effectiveMaterial = material;
  33461. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33462. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33463. return this;
  33464. }
  33465. }
  33466. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33467. return this;
  33468. }
  33469. // Alpha mode
  33470. if (enableAlphaMode) {
  33471. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33472. }
  33473. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33474. var step = _a[_i];
  33475. step.action(this, subMesh, batch);
  33476. }
  33477. var effect;
  33478. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33479. effect = subMesh.effect;
  33480. }
  33481. else {
  33482. effect = this._effectiveMaterial.getEffect();
  33483. }
  33484. if (!effect) {
  33485. return this;
  33486. }
  33487. var sideOrientation = this.overrideMaterialSideOrientation;
  33488. if (sideOrientation == null) {
  33489. sideOrientation = this._effectiveMaterial.sideOrientation;
  33490. if (this._getWorldMatrixDeterminant() < 0) {
  33491. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33492. }
  33493. }
  33494. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33495. if (this._effectiveMaterial.forceDepthWrite) {
  33496. engine.setDepthWrite(true);
  33497. }
  33498. // Bind
  33499. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33500. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33501. this._bind(subMesh, effect, fillMode);
  33502. }
  33503. var world = this.getWorldMatrix();
  33504. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33505. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33506. }
  33507. else {
  33508. this._effectiveMaterial.bind(world, this);
  33509. }
  33510. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33511. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33512. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33513. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33514. }
  33515. // Draw
  33516. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33517. // Unbind
  33518. this._effectiveMaterial.unbind();
  33519. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33520. var step = _c[_b];
  33521. step.action(this, subMesh, batch);
  33522. }
  33523. if (this._onAfterRenderObservable) {
  33524. this._onAfterRenderObservable.notifyObservers(this);
  33525. }
  33526. return this;
  33527. };
  33528. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33529. if (isInstance && effectiveMaterial) {
  33530. effectiveMaterial.bindOnlyWorldMatrix(world);
  33531. }
  33532. };
  33533. /**
  33534. * Renormalize the mesh and patch it up if there are no weights
  33535. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33536. * However in the case of zero weights then we set just a single influence to 1.
  33537. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33538. */
  33539. Mesh.prototype.cleanMatrixWeights = function () {
  33540. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33541. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33542. this.normalizeSkinWeightsAndExtra();
  33543. }
  33544. else {
  33545. this.normalizeSkinFourWeights();
  33546. }
  33547. }
  33548. };
  33549. // faster 4 weight version.
  33550. Mesh.prototype.normalizeSkinFourWeights = function () {
  33551. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33552. var numWeights = matricesWeights.length;
  33553. for (var a = 0; a < numWeights; a += 4) {
  33554. // accumulate weights
  33555. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33556. // check for invalid weight and just set it to 1.
  33557. if (t === 0) {
  33558. matricesWeights[a] = 1;
  33559. }
  33560. else {
  33561. // renormalize so everything adds to 1 use reciprical
  33562. var recip = 1 / t;
  33563. matricesWeights[a] *= recip;
  33564. matricesWeights[a + 1] *= recip;
  33565. matricesWeights[a + 2] *= recip;
  33566. matricesWeights[a + 3] *= recip;
  33567. }
  33568. }
  33569. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33570. };
  33571. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33572. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33573. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33574. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33575. var numWeights = matricesWeights.length;
  33576. for (var a = 0; a < numWeights; a += 4) {
  33577. // accumulate weights
  33578. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33579. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33580. // check for invalid weight and just set it to 1.
  33581. if (t === 0) {
  33582. matricesWeights[a] = 1;
  33583. }
  33584. else {
  33585. // renormalize so everything adds to 1 use reciprical
  33586. var recip = 1 / t;
  33587. matricesWeights[a] *= recip;
  33588. matricesWeights[a + 1] *= recip;
  33589. matricesWeights[a + 2] *= recip;
  33590. matricesWeights[a + 3] *= recip;
  33591. // same goes for extras
  33592. matricesWeightsExtra[a] *= recip;
  33593. matricesWeightsExtra[a + 1] *= recip;
  33594. matricesWeightsExtra[a + 2] *= recip;
  33595. matricesWeightsExtra[a + 3] *= recip;
  33596. }
  33597. }
  33598. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33599. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33600. };
  33601. /**
  33602. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33603. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33604. * the user know there was an issue with importing the mesh
  33605. * @returns a validation object with skinned, valid and report string
  33606. */
  33607. Mesh.prototype.validateSkinning = function () {
  33608. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33609. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33610. if (matricesWeights === null || this.skeleton == null) {
  33611. return { skinned: false, valid: true, report: "not skinned" };
  33612. }
  33613. var numWeights = matricesWeights.length;
  33614. var numberNotSorted = 0;
  33615. var missingWeights = 0;
  33616. var maxUsedWeights = 0;
  33617. var numberNotNormalized = 0;
  33618. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33619. var usedWeightCounts = new Array();
  33620. for (var a = 0; a <= numInfluences; a++) {
  33621. usedWeightCounts[a] = 0;
  33622. }
  33623. var toleranceEpsilon = 0.001;
  33624. for (var a = 0; a < numWeights; a += 4) {
  33625. var lastWeight = matricesWeights[a];
  33626. var t = lastWeight;
  33627. var usedWeights = t === 0 ? 0 : 1;
  33628. for (var b = 1; b < numInfluences; b++) {
  33629. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33630. if (d > lastWeight) {
  33631. numberNotSorted++;
  33632. }
  33633. if (d !== 0) {
  33634. usedWeights++;
  33635. }
  33636. t += d;
  33637. lastWeight = d;
  33638. }
  33639. // count the buffer weights usage
  33640. usedWeightCounts[usedWeights]++;
  33641. // max influences
  33642. if (usedWeights > maxUsedWeights) {
  33643. maxUsedWeights = usedWeights;
  33644. }
  33645. // check for invalid weight and just set it to 1.
  33646. if (t === 0) {
  33647. missingWeights++;
  33648. }
  33649. else {
  33650. // renormalize so everything adds to 1 use reciprical
  33651. var recip = 1 / t;
  33652. var tolerance = 0;
  33653. for (b = 0; b < numInfluences; b++) {
  33654. if (b < 4) {
  33655. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33656. }
  33657. else {
  33658. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33659. }
  33660. }
  33661. // arbitary epsilon value for dicdating not normalized
  33662. if (tolerance > toleranceEpsilon) {
  33663. numberNotNormalized++;
  33664. }
  33665. }
  33666. }
  33667. // validate bone indices are in range of the skeleton
  33668. var numBones = this.skeleton.bones.length;
  33669. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33670. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33671. var numBadBoneIndices = 0;
  33672. for (var a = 0; a < numWeights; a++) {
  33673. for (var b = 0; b < numInfluences; b++) {
  33674. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33675. if (index >= numBones || index < 0) {
  33676. numBadBoneIndices++;
  33677. }
  33678. }
  33679. }
  33680. // log mesh stats
  33681. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33682. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33683. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33684. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33685. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33686. };
  33687. /** @hidden */
  33688. Mesh.prototype._checkDelayState = function () {
  33689. var scene = this.getScene();
  33690. if (this._geometry) {
  33691. this._geometry.load(scene);
  33692. }
  33693. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33695. this._queueLoad(scene);
  33696. }
  33697. return this;
  33698. };
  33699. Mesh.prototype._queueLoad = function (scene) {
  33700. var _this = this;
  33701. scene._addPendingData(this);
  33702. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33703. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33704. if (data instanceof ArrayBuffer) {
  33705. _this._delayLoadingFunction(data, _this);
  33706. }
  33707. else {
  33708. _this._delayLoadingFunction(JSON.parse(data), _this);
  33709. }
  33710. _this.instances.forEach(function (instance) {
  33711. instance._syncSubMeshes();
  33712. });
  33713. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33714. scene._removePendingData(_this);
  33715. }, function () { }, scene.database, getBinaryData);
  33716. return this;
  33717. };
  33718. /**
  33719. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33720. * A mesh is in the frustum if its bounding box intersects the frustum
  33721. * @param frustumPlanes defines the frustum to test
  33722. * @returns true if the mesh is in the frustum planes
  33723. */
  33724. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33725. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33726. return false;
  33727. }
  33728. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33729. return false;
  33730. }
  33731. this._checkDelayState();
  33732. return true;
  33733. };
  33734. /**
  33735. * Sets the mesh material by the material or multiMaterial `id` property
  33736. * @param id is a string identifying the material or the multiMaterial
  33737. * @returns the current mesh
  33738. */
  33739. Mesh.prototype.setMaterialByID = function (id) {
  33740. var materials = this.getScene().materials;
  33741. var index;
  33742. for (index = materials.length - 1; index > -1; index--) {
  33743. if (materials[index].id === id) {
  33744. this.material = materials[index];
  33745. return this;
  33746. }
  33747. }
  33748. // Multi
  33749. var multiMaterials = this.getScene().multiMaterials;
  33750. for (index = multiMaterials.length - 1; index > -1; index--) {
  33751. if (multiMaterials[index].id === id) {
  33752. this.material = multiMaterials[index];
  33753. return this;
  33754. }
  33755. }
  33756. return this;
  33757. };
  33758. /**
  33759. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33760. * @returns an array of IAnimatable
  33761. */
  33762. Mesh.prototype.getAnimatables = function () {
  33763. var results = new Array();
  33764. if (this.material) {
  33765. results.push(this.material);
  33766. }
  33767. if (this.skeleton) {
  33768. results.push(this.skeleton);
  33769. }
  33770. return results;
  33771. };
  33772. /**
  33773. * Modifies the mesh geometry according to the passed transformation matrix.
  33774. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33775. * The mesh normals are modified using the same transformation.
  33776. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33777. * @param transform defines the transform matrix to use
  33778. * @see http://doc.babylonjs.com/resources/baking_transformations
  33779. * @returns the current mesh
  33780. */
  33781. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33782. // Position
  33783. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33784. return this;
  33785. }
  33786. var submeshes = this.subMeshes.splice(0);
  33787. this._resetPointsArrayCache();
  33788. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33789. var temp = new Array();
  33790. var index;
  33791. for (index = 0; index < data.length; index += 3) {
  33792. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33793. }
  33794. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33795. // Normals
  33796. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33797. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33798. temp = [];
  33799. for (index = 0; index < data.length; index += 3) {
  33800. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33801. }
  33802. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33803. }
  33804. // flip faces?
  33805. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33806. this.flipFaces();
  33807. }
  33808. // Restore submeshes
  33809. this.releaseSubMeshes();
  33810. this.subMeshes = submeshes;
  33811. return this;
  33812. };
  33813. /**
  33814. * Modifies the mesh geometry according to its own current World Matrix.
  33815. * The mesh World Matrix is then reset.
  33816. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33817. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33818. * @see http://doc.babylonjs.com/resources/baking_transformations
  33819. * @returns the current mesh
  33820. */
  33821. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33822. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33823. this.scaling.copyFromFloats(1, 1, 1);
  33824. this.position.copyFromFloats(0, 0, 0);
  33825. this.rotation.copyFromFloats(0, 0, 0);
  33826. //only if quaternion is already set
  33827. if (this.rotationQuaternion) {
  33828. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33829. }
  33830. this._worldMatrix = BABYLON.Matrix.Identity();
  33831. return this;
  33832. };
  33833. Object.defineProperty(Mesh.prototype, "_positions", {
  33834. // Cache
  33835. /** @hidden */
  33836. get: function () {
  33837. if (this._geometry) {
  33838. return this._geometry._positions;
  33839. }
  33840. return null;
  33841. },
  33842. enumerable: true,
  33843. configurable: true
  33844. });
  33845. /** @hidden */
  33846. Mesh.prototype._resetPointsArrayCache = function () {
  33847. if (this._geometry) {
  33848. this._geometry._resetPointsArrayCache();
  33849. }
  33850. return this;
  33851. };
  33852. /** @hidden */
  33853. Mesh.prototype._generatePointsArray = function () {
  33854. if (this._geometry) {
  33855. return this._geometry._generatePointsArray();
  33856. }
  33857. return false;
  33858. };
  33859. /**
  33860. * Returns a new Mesh object generated from the current mesh properties.
  33861. * This method must not get confused with createInstance()
  33862. * @param name is a string, the name given to the new mesh
  33863. * @param newParent can be any Node object (default `null`)
  33864. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33865. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33866. * @returns a new mesh
  33867. */
  33868. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33869. if (name === void 0) { name = ""; }
  33870. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33871. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33872. };
  33873. /**
  33874. * Releases resources associated with this mesh.
  33875. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33876. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33877. */
  33878. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33879. var _this = this;
  33880. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33881. this.morphTargetManager = null;
  33882. if (this._geometry) {
  33883. this._geometry.releaseForMesh(this, true);
  33884. }
  33885. if (this._onBeforeDrawObservable) {
  33886. this._onBeforeDrawObservable.clear();
  33887. }
  33888. if (this._onBeforeRenderObservable) {
  33889. this._onBeforeRenderObservable.clear();
  33890. }
  33891. if (this._onAfterRenderObservable) {
  33892. this._onAfterRenderObservable.clear();
  33893. }
  33894. // Sources
  33895. var meshes = this.getScene().meshes;
  33896. meshes.forEach(function (abstractMesh) {
  33897. var mesh = abstractMesh;
  33898. if (mesh._source && mesh._source === _this) {
  33899. mesh._source = null;
  33900. }
  33901. });
  33902. this._source = null;
  33903. // Instances
  33904. if (this._instanceDataStorage.instancesBuffer) {
  33905. this._instanceDataStorage.instancesBuffer.dispose();
  33906. this._instanceDataStorage.instancesBuffer = null;
  33907. }
  33908. while (this.instances.length) {
  33909. this.instances[0].dispose();
  33910. }
  33911. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33912. };
  33913. /**
  33914. * Modifies the mesh geometry according to a displacement map.
  33915. * 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.
  33916. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33917. * @param url is a string, the URL from the image file is to be downloaded.
  33918. * @param minHeight is the lower limit of the displacement.
  33919. * @param maxHeight is the upper limit of the displacement.
  33920. * @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.
  33921. * @param uvOffset is an optional vector2 used to offset UV.
  33922. * @param uvScale is an optional vector2 used to scale UV.
  33923. * @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.
  33924. * @returns the Mesh.
  33925. */
  33926. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33927. var _this = this;
  33928. if (forceUpdate === void 0) { forceUpdate = false; }
  33929. var scene = this.getScene();
  33930. var onload = function (img) {
  33931. // Getting height map data
  33932. var canvas = document.createElement("canvas");
  33933. var context = canvas.getContext("2d");
  33934. var heightMapWidth = img.width;
  33935. var heightMapHeight = img.height;
  33936. canvas.width = heightMapWidth;
  33937. canvas.height = heightMapHeight;
  33938. context.drawImage(img, 0, 0);
  33939. // Create VertexData from map data
  33940. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33941. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33942. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33943. //execute success callback, if set
  33944. if (onSuccess) {
  33945. onSuccess(_this);
  33946. }
  33947. };
  33948. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33949. return this;
  33950. };
  33951. /**
  33952. * Modifies the mesh geometry according to a displacementMap buffer.
  33953. * 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.
  33954. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33955. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33956. * @param heightMapWidth is the width of the buffer image.
  33957. * @param heightMapHeight is the height of the buffer image.
  33958. * @param minHeight is the lower limit of the displacement.
  33959. * @param maxHeight is the upper limit of the displacement.
  33960. * @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.
  33961. * @param uvOffset is an optional vector2 used to offset UV.
  33962. * @param uvScale is an optional vector2 used to scale UV.
  33963. * @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.
  33964. * @returns the Mesh.
  33965. */
  33966. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33967. if (forceUpdate === void 0) { forceUpdate = false; }
  33968. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33969. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33970. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33971. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33972. return this;
  33973. }
  33974. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33975. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33976. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33977. var position = BABYLON.Vector3.Zero();
  33978. var normal = BABYLON.Vector3.Zero();
  33979. var uv = BABYLON.Vector2.Zero();
  33980. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33981. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33982. for (var index = 0; index < positions.length; index += 3) {
  33983. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33984. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33985. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33986. // Compute height
  33987. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33988. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33989. var pos = (u + v * heightMapWidth) * 4;
  33990. var r = buffer[pos] / 255.0;
  33991. var g = buffer[pos + 1] / 255.0;
  33992. var b = buffer[pos + 2] / 255.0;
  33993. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33994. normal.normalize();
  33995. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33996. position = position.add(normal);
  33997. position.toArray(positions, index);
  33998. }
  33999. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34000. if (forceUpdate) {
  34001. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34002. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34003. }
  34004. else {
  34005. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34006. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34007. }
  34008. return this;
  34009. };
  34010. /**
  34011. * Modify the mesh to get a flat shading rendering.
  34012. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34013. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34014. * @returns current mesh
  34015. */
  34016. Mesh.prototype.convertToFlatShadedMesh = function () {
  34017. var kinds = this.getVerticesDataKinds();
  34018. var vbs = {};
  34019. var data = {};
  34020. var newdata = {};
  34021. var updatableNormals = false;
  34022. var kindIndex;
  34023. var kind;
  34024. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34025. kind = kinds[kindIndex];
  34026. var vertexBuffer = this.getVertexBuffer(kind);
  34027. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34028. updatableNormals = vertexBuffer.isUpdatable();
  34029. kinds.splice(kindIndex, 1);
  34030. kindIndex--;
  34031. continue;
  34032. }
  34033. vbs[kind] = vertexBuffer;
  34034. data[kind] = vbs[kind].getData();
  34035. newdata[kind] = [];
  34036. }
  34037. // Save previous submeshes
  34038. var previousSubmeshes = this.subMeshes.slice(0);
  34039. var indices = this.getIndices();
  34040. var totalIndices = this.getTotalIndices();
  34041. // Generating unique vertices per face
  34042. var index;
  34043. for (index = 0; index < totalIndices; index++) {
  34044. var vertexIndex = indices[index];
  34045. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34046. kind = kinds[kindIndex];
  34047. var stride = vbs[kind].getStrideSize();
  34048. for (var offset = 0; offset < stride; offset++) {
  34049. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34050. }
  34051. }
  34052. }
  34053. // Updating faces & normal
  34054. var normals = [];
  34055. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34056. for (index = 0; index < totalIndices; index += 3) {
  34057. indices[index] = index;
  34058. indices[index + 1] = index + 1;
  34059. indices[index + 2] = index + 2;
  34060. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34061. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34062. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34063. var p1p2 = p1.subtract(p2);
  34064. var p3p2 = p3.subtract(p2);
  34065. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34066. // Store same normals for every vertex
  34067. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34068. normals.push(normal.x);
  34069. normals.push(normal.y);
  34070. normals.push(normal.z);
  34071. }
  34072. }
  34073. this.setIndices(indices);
  34074. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34075. // Updating vertex buffers
  34076. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34077. kind = kinds[kindIndex];
  34078. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34079. }
  34080. // Updating submeshes
  34081. this.releaseSubMeshes();
  34082. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34083. var previousOne = previousSubmeshes[submeshIndex];
  34084. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34085. }
  34086. this.synchronizeInstances();
  34087. return this;
  34088. };
  34089. /**
  34090. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34091. * In other words, more vertices, no more indices and a single bigger VBO.
  34092. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34093. * @returns current mesh
  34094. */
  34095. Mesh.prototype.convertToUnIndexedMesh = function () {
  34096. var kinds = this.getVerticesDataKinds();
  34097. var vbs = {};
  34098. var data = {};
  34099. var newdata = {};
  34100. var kindIndex;
  34101. var kind;
  34102. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34103. kind = kinds[kindIndex];
  34104. var vertexBuffer = this.getVertexBuffer(kind);
  34105. vbs[kind] = vertexBuffer;
  34106. data[kind] = vbs[kind].getData();
  34107. newdata[kind] = [];
  34108. }
  34109. // Save previous submeshes
  34110. var previousSubmeshes = this.subMeshes.slice(0);
  34111. var indices = this.getIndices();
  34112. var totalIndices = this.getTotalIndices();
  34113. // Generating unique vertices per face
  34114. var index;
  34115. for (index = 0; index < totalIndices; index++) {
  34116. var vertexIndex = indices[index];
  34117. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34118. kind = kinds[kindIndex];
  34119. var stride = vbs[kind].getStrideSize();
  34120. for (var offset = 0; offset < stride; offset++) {
  34121. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34122. }
  34123. }
  34124. }
  34125. // Updating indices
  34126. for (index = 0; index < totalIndices; index += 3) {
  34127. indices[index] = index;
  34128. indices[index + 1] = index + 1;
  34129. indices[index + 2] = index + 2;
  34130. }
  34131. this.setIndices(indices);
  34132. // Updating vertex buffers
  34133. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34134. kind = kinds[kindIndex];
  34135. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34136. }
  34137. // Updating submeshes
  34138. this.releaseSubMeshes();
  34139. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34140. var previousOne = previousSubmeshes[submeshIndex];
  34141. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34142. }
  34143. this._unIndexed = true;
  34144. this.synchronizeInstances();
  34145. return this;
  34146. };
  34147. /**
  34148. * Inverses facet orientations.
  34149. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34150. * @param flipNormals will also inverts the normals
  34151. * @returns current mesh
  34152. */
  34153. Mesh.prototype.flipFaces = function (flipNormals) {
  34154. if (flipNormals === void 0) { flipNormals = false; }
  34155. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34156. var i;
  34157. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34158. for (i = 0; i < vertex_data.normals.length; i++) {
  34159. vertex_data.normals[i] *= -1;
  34160. }
  34161. }
  34162. if (vertex_data.indices) {
  34163. var temp;
  34164. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34165. // reassign indices
  34166. temp = vertex_data.indices[i + 1];
  34167. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34168. vertex_data.indices[i + 2] = temp;
  34169. }
  34170. }
  34171. vertex_data.applyToMesh(this);
  34172. return this;
  34173. };
  34174. // Instances
  34175. /**
  34176. * Creates a new InstancedMesh object from the mesh model.
  34177. * Warning : this method is not supported for Line mesh and LineSystem
  34178. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34179. * @param name defines the name of the new instance
  34180. * @returns a new InstancedMesh
  34181. */
  34182. Mesh.prototype.createInstance = function (name) {
  34183. return new BABYLON.InstancedMesh(name, this);
  34184. };
  34185. /**
  34186. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34187. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34188. * @returns the current mesh
  34189. */
  34190. Mesh.prototype.synchronizeInstances = function () {
  34191. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34192. var instance = this.instances[instanceIndex];
  34193. instance._syncSubMeshes();
  34194. }
  34195. return this;
  34196. };
  34197. /**
  34198. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34199. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34200. * This should be used together with the simplification to avoid disappearing triangles.
  34201. * @param successCallback an optional success callback to be called after the optimization finished.
  34202. * @returns the current mesh
  34203. */
  34204. Mesh.prototype.optimizeIndices = function (successCallback) {
  34205. var _this = this;
  34206. var indices = this.getIndices();
  34207. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34208. if (!positions || !indices) {
  34209. return this;
  34210. }
  34211. var vectorPositions = new Array();
  34212. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34213. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34214. }
  34215. var dupes = new Array();
  34216. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34217. var realPos = vectorPositions.length - 1 - iteration;
  34218. var testedPosition = vectorPositions[realPos];
  34219. for (var j = 0; j < realPos; ++j) {
  34220. var againstPosition = vectorPositions[j];
  34221. if (testedPosition.equals(againstPosition)) {
  34222. dupes[realPos] = j;
  34223. break;
  34224. }
  34225. }
  34226. }, function () {
  34227. for (var i = 0; i < indices.length; ++i) {
  34228. indices[i] = dupes[indices[i]] || indices[i];
  34229. }
  34230. //indices are now reordered
  34231. var originalSubMeshes = _this.subMeshes.slice(0);
  34232. _this.setIndices(indices);
  34233. _this.subMeshes = originalSubMeshes;
  34234. if (successCallback) {
  34235. successCallback(_this);
  34236. }
  34237. });
  34238. return this;
  34239. };
  34240. /**
  34241. * Serialize current mesh
  34242. * @param serializationObject defines the object which will receive the serialization data
  34243. */
  34244. Mesh.prototype.serialize = function (serializationObject) {
  34245. serializationObject.name = this.name;
  34246. serializationObject.id = this.id;
  34247. serializationObject.type = this.getClassName();
  34248. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34249. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34250. }
  34251. serializationObject.position = this.position.asArray();
  34252. if (this.rotationQuaternion) {
  34253. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34254. }
  34255. else if (this.rotation) {
  34256. serializationObject.rotation = this.rotation.asArray();
  34257. }
  34258. serializationObject.scaling = this.scaling.asArray();
  34259. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34260. serializationObject.isEnabled = this.isEnabled(false);
  34261. serializationObject.isVisible = this.isVisible;
  34262. serializationObject.infiniteDistance = this.infiniteDistance;
  34263. serializationObject.pickable = this.isPickable;
  34264. serializationObject.receiveShadows = this.receiveShadows;
  34265. serializationObject.billboardMode = this.billboardMode;
  34266. serializationObject.visibility = this.visibility;
  34267. serializationObject.checkCollisions = this.checkCollisions;
  34268. serializationObject.isBlocker = this.isBlocker;
  34269. // Parent
  34270. if (this.parent) {
  34271. serializationObject.parentId = this.parent.id;
  34272. }
  34273. // Geometry
  34274. serializationObject.isUnIndexed = this.isUnIndexed;
  34275. var geometry = this._geometry;
  34276. if (geometry) {
  34277. var geometryId = geometry.id;
  34278. serializationObject.geometryId = geometryId;
  34279. // SubMeshes
  34280. serializationObject.subMeshes = [];
  34281. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34282. var subMesh = this.subMeshes[subIndex];
  34283. serializationObject.subMeshes.push({
  34284. materialIndex: subMesh.materialIndex,
  34285. verticesStart: subMesh.verticesStart,
  34286. verticesCount: subMesh.verticesCount,
  34287. indexStart: subMesh.indexStart,
  34288. indexCount: subMesh.indexCount
  34289. });
  34290. }
  34291. }
  34292. // Material
  34293. if (this.material) {
  34294. serializationObject.materialId = this.material.id;
  34295. }
  34296. else {
  34297. this.material = null;
  34298. }
  34299. // Morph targets
  34300. if (this.morphTargetManager) {
  34301. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34302. }
  34303. // Skeleton
  34304. if (this.skeleton) {
  34305. serializationObject.skeletonId = this.skeleton.id;
  34306. }
  34307. // Physics
  34308. //TODO implement correct serialization for physics impostors.
  34309. var impostor = this.getPhysicsImpostor();
  34310. if (impostor) {
  34311. serializationObject.physicsMass = impostor.getParam("mass");
  34312. serializationObject.physicsFriction = impostor.getParam("friction");
  34313. serializationObject.physicsRestitution = impostor.getParam("mass");
  34314. serializationObject.physicsImpostor = impostor.type;
  34315. }
  34316. // Metadata
  34317. if (this.metadata) {
  34318. serializationObject.metadata = this.metadata;
  34319. }
  34320. // Instances
  34321. serializationObject.instances = [];
  34322. for (var index = 0; index < this.instances.length; index++) {
  34323. var instance = this.instances[index];
  34324. if (instance.doNotSerialize) {
  34325. continue;
  34326. }
  34327. var serializationInstance = {
  34328. name: instance.name,
  34329. id: instance.id,
  34330. position: instance.position.asArray(),
  34331. scaling: instance.scaling.asArray()
  34332. };
  34333. if (instance.parent) {
  34334. serializationInstance.parentId = instance.parent.id;
  34335. }
  34336. if (instance.rotationQuaternion) {
  34337. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34338. }
  34339. else if (instance.rotation) {
  34340. serializationInstance.rotation = instance.rotation.asArray();
  34341. }
  34342. serializationObject.instances.push(serializationInstance);
  34343. // Animations
  34344. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34345. serializationInstance.ranges = instance.serializeAnimationRanges();
  34346. }
  34347. //
  34348. // Animations
  34349. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34350. serializationObject.ranges = this.serializeAnimationRanges();
  34351. // Layer mask
  34352. serializationObject.layerMask = this.layerMask;
  34353. // Alpha
  34354. serializationObject.alphaIndex = this.alphaIndex;
  34355. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34356. // Overlay
  34357. serializationObject.overlayAlpha = this.overlayAlpha;
  34358. serializationObject.overlayColor = this.overlayColor.asArray();
  34359. serializationObject.renderOverlay = this.renderOverlay;
  34360. // Fog
  34361. serializationObject.applyFog = this.applyFog;
  34362. // Action Manager
  34363. if (this.actionManager) {
  34364. serializationObject.actions = this.actionManager.serialize(this.name);
  34365. }
  34366. };
  34367. /** @hidden */
  34368. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34369. if (!this.geometry) {
  34370. return;
  34371. }
  34372. this._markSubMeshesAsAttributesDirty();
  34373. var morphTargetManager = this._morphTargetManager;
  34374. if (morphTargetManager && morphTargetManager.vertexCount) {
  34375. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34376. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34377. this.morphTargetManager = null;
  34378. return;
  34379. }
  34380. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34381. var morphTarget = morphTargetManager.getActiveTarget(index);
  34382. var positions = morphTarget.getPositions();
  34383. if (!positions) {
  34384. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34385. return;
  34386. }
  34387. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34388. var normals = morphTarget.getNormals();
  34389. if (normals) {
  34390. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34391. }
  34392. var tangents = morphTarget.getTangents();
  34393. if (tangents) {
  34394. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34395. }
  34396. }
  34397. }
  34398. else {
  34399. var index = 0;
  34400. // Positions
  34401. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34402. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34403. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34404. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34405. }
  34406. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34407. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34408. }
  34409. index++;
  34410. }
  34411. }
  34412. };
  34413. // Statics
  34414. /**
  34415. * Returns a new Mesh object parsed from the source provided.
  34416. * @param parsedMesh is the source
  34417. * @param scene defines the hosting scene
  34418. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34419. * @returns a new Mesh
  34420. */
  34421. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34422. var mesh;
  34423. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34424. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34425. }
  34426. else {
  34427. mesh = new Mesh(parsedMesh.name, scene);
  34428. }
  34429. mesh.id = parsedMesh.id;
  34430. if (BABYLON.Tags) {
  34431. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34432. }
  34433. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34434. if (parsedMesh.metadata !== undefined) {
  34435. mesh.metadata = parsedMesh.metadata;
  34436. }
  34437. if (parsedMesh.rotationQuaternion) {
  34438. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34439. }
  34440. else if (parsedMesh.rotation) {
  34441. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34442. }
  34443. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34444. if (parsedMesh.localMatrix) {
  34445. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34446. }
  34447. else if (parsedMesh.pivotMatrix) {
  34448. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34449. }
  34450. mesh.setEnabled(parsedMesh.isEnabled);
  34451. mesh.isVisible = parsedMesh.isVisible;
  34452. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34453. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34454. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34455. if (parsedMesh.applyFog !== undefined) {
  34456. mesh.applyFog = parsedMesh.applyFog;
  34457. }
  34458. if (parsedMesh.pickable !== undefined) {
  34459. mesh.isPickable = parsedMesh.pickable;
  34460. }
  34461. if (parsedMesh.alphaIndex !== undefined) {
  34462. mesh.alphaIndex = parsedMesh.alphaIndex;
  34463. }
  34464. mesh.receiveShadows = parsedMesh.receiveShadows;
  34465. mesh.billboardMode = parsedMesh.billboardMode;
  34466. if (parsedMesh.visibility !== undefined) {
  34467. mesh.visibility = parsedMesh.visibility;
  34468. }
  34469. mesh.checkCollisions = parsedMesh.checkCollisions;
  34470. if (parsedMesh.isBlocker !== undefined) {
  34471. mesh.isBlocker = parsedMesh.isBlocker;
  34472. }
  34473. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34474. // freezeWorldMatrix
  34475. if (parsedMesh.freezeWorldMatrix) {
  34476. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34477. }
  34478. // Parent
  34479. if (parsedMesh.parentId) {
  34480. mesh._waitingParentId = parsedMesh.parentId;
  34481. }
  34482. // Actions
  34483. if (parsedMesh.actions !== undefined) {
  34484. mesh._waitingActions = parsedMesh.actions;
  34485. }
  34486. // Overlay
  34487. if (parsedMesh.overlayAlpha !== undefined) {
  34488. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34489. }
  34490. if (parsedMesh.overlayColor !== undefined) {
  34491. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34492. }
  34493. if (parsedMesh.renderOverlay !== undefined) {
  34494. mesh.renderOverlay = parsedMesh.renderOverlay;
  34495. }
  34496. // Geometry
  34497. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34498. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34499. if (parsedMesh.delayLoadingFile) {
  34500. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34501. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34502. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34503. if (parsedMesh._binaryInfo) {
  34504. mesh._binaryInfo = parsedMesh._binaryInfo;
  34505. }
  34506. mesh._delayInfo = [];
  34507. if (parsedMesh.hasUVs) {
  34508. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34509. }
  34510. if (parsedMesh.hasUVs2) {
  34511. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34512. }
  34513. if (parsedMesh.hasUVs3) {
  34514. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34515. }
  34516. if (parsedMesh.hasUVs4) {
  34517. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34518. }
  34519. if (parsedMesh.hasUVs5) {
  34520. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34521. }
  34522. if (parsedMesh.hasUVs6) {
  34523. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34524. }
  34525. if (parsedMesh.hasColors) {
  34526. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34527. }
  34528. if (parsedMesh.hasMatricesIndices) {
  34529. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34530. }
  34531. if (parsedMesh.hasMatricesWeights) {
  34532. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34533. }
  34534. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34535. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34536. mesh._checkDelayState();
  34537. }
  34538. }
  34539. else {
  34540. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34541. }
  34542. // Material
  34543. if (parsedMesh.materialId) {
  34544. mesh.setMaterialByID(parsedMesh.materialId);
  34545. }
  34546. else {
  34547. mesh.material = null;
  34548. }
  34549. // Morph targets
  34550. if (parsedMesh.morphTargetManagerId > -1) {
  34551. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34552. }
  34553. // Skeleton
  34554. if (parsedMesh.skeletonId > -1) {
  34555. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34556. if (parsedMesh.numBoneInfluencers) {
  34557. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34558. }
  34559. }
  34560. // Animations
  34561. if (parsedMesh.animations) {
  34562. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34563. var parsedAnimation = parsedMesh.animations[animationIndex];
  34564. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34565. }
  34566. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34567. }
  34568. if (parsedMesh.autoAnimate) {
  34569. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34570. }
  34571. // Layer Mask
  34572. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34573. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34574. }
  34575. else {
  34576. mesh.layerMask = 0x0FFFFFFF;
  34577. }
  34578. // Physics
  34579. if (parsedMesh.physicsImpostor) {
  34580. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34581. mass: parsedMesh.physicsMass,
  34582. friction: parsedMesh.physicsFriction,
  34583. restitution: parsedMesh.physicsRestitution
  34584. }, scene);
  34585. }
  34586. // Instances
  34587. if (parsedMesh.instances) {
  34588. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34589. var parsedInstance = parsedMesh.instances[index];
  34590. var instance = mesh.createInstance(parsedInstance.name);
  34591. if (parsedInstance.id) {
  34592. instance.id = parsedInstance.id;
  34593. }
  34594. if (BABYLON.Tags) {
  34595. if (parsedInstance.tags) {
  34596. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34597. }
  34598. else {
  34599. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34600. }
  34601. }
  34602. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34603. if (parsedInstance.parentId) {
  34604. instance._waitingParentId = parsedInstance.parentId;
  34605. }
  34606. if (parsedInstance.rotationQuaternion) {
  34607. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34608. }
  34609. else if (parsedInstance.rotation) {
  34610. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34611. }
  34612. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34613. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34614. instance.checkCollisions = parsedInstance.checkCollisions;
  34615. }
  34616. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34617. instance.isPickable = parsedInstance.pickable;
  34618. }
  34619. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34620. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34621. }
  34622. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34623. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34624. }
  34625. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34626. instance.alphaIndex = parsedInstance.alphaIndex;
  34627. }
  34628. // Physics
  34629. if (parsedInstance.physicsImpostor) {
  34630. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34631. mass: parsedInstance.physicsMass,
  34632. friction: parsedInstance.physicsFriction,
  34633. restitution: parsedInstance.physicsRestitution
  34634. }, scene);
  34635. }
  34636. // Animation
  34637. if (parsedInstance.animations) {
  34638. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34639. parsedAnimation = parsedInstance.animations[animationIndex];
  34640. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34641. }
  34642. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34643. if (parsedInstance.autoAnimate) {
  34644. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34645. }
  34646. }
  34647. }
  34648. }
  34649. return mesh;
  34650. };
  34651. /**
  34652. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34653. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34654. * @param name defines the name of the mesh to create
  34655. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34656. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34657. * @param closePath creates a seam between the first and the last points of each path of the path array
  34658. * @param offset is taken in account only if the `pathArray` is containing a single path
  34659. * @param scene defines the hosting scene
  34660. * @param updatable defines if the mesh must be flagged as updatable
  34661. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34662. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  34663. * @returns a new Mesh
  34664. */
  34665. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34666. if (closeArray === void 0) { closeArray = false; }
  34667. if (updatable === void 0) { updatable = false; }
  34668. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34669. pathArray: pathArray,
  34670. closeArray: closeArray,
  34671. closePath: closePath,
  34672. offset: offset,
  34673. updatable: updatable,
  34674. sideOrientation: sideOrientation,
  34675. instance: instance
  34676. }, scene);
  34677. };
  34678. /**
  34679. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34680. * @param name defines the name of the mesh to create
  34681. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34682. * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  34683. * @param scene defines the hosting scene
  34684. * @param updatable defines if the mesh must be flagged as updatable
  34685. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34686. * @returns a new Mesh
  34687. */
  34688. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34689. if (scene === void 0) { scene = null; }
  34690. var options = {
  34691. radius: radius,
  34692. tessellation: tessellation,
  34693. sideOrientation: sideOrientation,
  34694. updatable: updatable
  34695. };
  34696. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34697. };
  34698. /**
  34699. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34700. * @param name defines the name of the mesh to create
  34701. * @param size sets the size (float) of each box side (default 1)
  34702. * @param scene defines the hosting scene
  34703. * @param updatable defines if the mesh must be flagged as updatable
  34704. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34705. * @returns a new Mesh
  34706. */
  34707. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34708. if (scene === void 0) { scene = null; }
  34709. var options = {
  34710. size: size,
  34711. sideOrientation: sideOrientation,
  34712. updatable: updatable
  34713. };
  34714. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34715. };
  34716. /**
  34717. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34718. * @param name defines the name of the mesh to create
  34719. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34720. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34721. * @param scene defines the hosting scene
  34722. * @param updatable defines if the mesh must be flagged as updatable
  34723. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34724. * @returns a new Mesh
  34725. */
  34726. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34727. var options = {
  34728. segments: segments,
  34729. diameterX: diameter,
  34730. diameterY: diameter,
  34731. diameterZ: diameter,
  34732. sideOrientation: sideOrientation,
  34733. updatable: updatable
  34734. };
  34735. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34736. };
  34737. /**
  34738. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34739. * @param name defines the name of the mesh to create
  34740. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34741. * @param diameterTop set the top cap diameter (floats, default 1)
  34742. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34743. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34744. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34745. * @param scene defines the hosting scene
  34746. * @param updatable defines if the mesh must be flagged as updatable
  34747. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34748. * @returns a new Mesh
  34749. */
  34750. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34751. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34752. if (scene !== undefined) {
  34753. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34754. updatable = scene;
  34755. }
  34756. scene = subdivisions;
  34757. subdivisions = 1;
  34758. }
  34759. var options = {
  34760. height: height,
  34761. diameterTop: diameterTop,
  34762. diameterBottom: diameterBottom,
  34763. tessellation: tessellation,
  34764. subdivisions: subdivisions,
  34765. sideOrientation: sideOrientation,
  34766. updatable: updatable
  34767. };
  34768. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34769. };
  34770. // Torus (Code from SharpDX.org)
  34771. /**
  34772. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34773. * @param name defines the name of the mesh to create
  34774. * @param diameter sets the diameter size (float) of the torus (default 1)
  34775. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34776. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34777. * @param scene defines the hosting scene
  34778. * @param updatable defines if the mesh must be flagged as updatable
  34779. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34780. * @returns a new Mesh
  34781. */
  34782. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34783. var options = {
  34784. diameter: diameter,
  34785. thickness: thickness,
  34786. tessellation: tessellation,
  34787. sideOrientation: sideOrientation,
  34788. updatable: updatable
  34789. };
  34790. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34791. };
  34792. /**
  34793. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34794. * @param name defines the name of the mesh to create
  34795. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34796. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34797. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34798. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34799. * @param p the number of windings on X axis (positive integers, default 2)
  34800. * @param q the number of windings on Y axis (positive integers, default 3)
  34801. * @param scene defines the hosting scene
  34802. * @param updatable defines if the mesh must be flagged as updatable
  34803. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34804. * @returns a new Mesh
  34805. */
  34806. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34807. var options = {
  34808. radius: radius,
  34809. tube: tube,
  34810. radialSegments: radialSegments,
  34811. tubularSegments: tubularSegments,
  34812. p: p,
  34813. q: q,
  34814. sideOrientation: sideOrientation,
  34815. updatable: updatable
  34816. };
  34817. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34818. };
  34819. /**
  34820. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34821. * @param name defines the name of the mesh to create
  34822. * @param points is an array successive Vector3
  34823. * @param scene defines the hosting scene
  34824. * @param updatable defines if the mesh must be flagged as updatable
  34825. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  34826. * @returns a new Mesh
  34827. */
  34828. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34829. if (scene === void 0) { scene = null; }
  34830. if (updatable === void 0) { updatable = false; }
  34831. if (instance === void 0) { instance = null; }
  34832. var options = {
  34833. points: points,
  34834. updatable: updatable,
  34835. instance: instance
  34836. };
  34837. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34838. };
  34839. /**
  34840. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34841. * @param name defines the name of the mesh to create
  34842. * @param points is an array successive Vector3
  34843. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34844. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34845. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34846. * @param scene defines the hosting scene
  34847. * @param updatable defines if the mesh must be flagged as updatable
  34848. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  34849. * @returns a new Mesh
  34850. */
  34851. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34852. if (scene === void 0) { scene = null; }
  34853. var options = {
  34854. points: points,
  34855. dashSize: dashSize,
  34856. gapSize: gapSize,
  34857. dashNb: dashNb,
  34858. updatable: updatable,
  34859. instance: instance
  34860. };
  34861. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34862. };
  34863. /**
  34864. * Creates a polygon mesh.
  34865. * Please consider using the same method from the MeshBuilder class instead.
  34866. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34867. * 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.
  34868. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34870. * Remember you can only change the shape positions, not their number when updating a polygon.
  34871. */
  34872. /**
  34873. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34874. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34875. * @param name defines the name of the mesh to create
  34876. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  34877. * @param scene defines the hosting scene
  34878. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34879. * @param updatable defines if the mesh must be flagged as updatable
  34880. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34881. * @returns a new Mesh
  34882. */
  34883. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34884. var options = {
  34885. shape: shape,
  34886. holes: holes,
  34887. updatable: updatable,
  34888. sideOrientation: sideOrientation
  34889. };
  34890. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34891. };
  34892. /**
  34893. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34894. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34895. * @param name defines the name of the mesh to create
  34896. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  34897. * @param depth defines the height of extrusion
  34898. * @param scene defines the hosting scene
  34899. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34900. * @param updatable defines if the mesh must be flagged as updatable
  34901. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34902. * @returns a new Mesh
  34903. */
  34904. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34905. var options = {
  34906. shape: shape,
  34907. holes: holes,
  34908. depth: depth,
  34909. updatable: updatable,
  34910. sideOrientation: sideOrientation
  34911. };
  34912. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34913. };
  34914. /**
  34915. * Creates an extruded shape mesh.
  34916. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  34917. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34918. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34919. * @param name defines the name of the mesh to create
  34920. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  34921. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34922. * @param scale is the value to scale the shape
  34923. * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
  34924. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  34925. * @param scene defines the hosting scene
  34926. * @param updatable defines if the mesh must be flagged as updatable
  34927. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34928. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  34929. * @returns a new Mesh
  34930. */
  34931. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34932. if (scene === void 0) { scene = null; }
  34933. var options = {
  34934. shape: shape,
  34935. path: path,
  34936. scale: scale,
  34937. rotation: rotation,
  34938. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34939. sideOrientation: sideOrientation,
  34940. instance: instance,
  34941. updatable: updatable
  34942. };
  34943. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34944. };
  34945. /**
  34946. * Creates an custom extruded shape mesh.
  34947. * The custom extrusion is a parametric shape.
  34948. * It has no predefined shape. Its final shape will depend on the input parameters.
  34949. * Please consider using the same method from the MeshBuilder class instead
  34950. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34951. * @param name defines the name of the mesh to create
  34952. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  34953. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34954. * @param scaleFunction is a custom Javascript function called on each path point
  34955. * @param rotationFunction is a custom Javascript function called on each path point
  34956. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34957. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34958. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  34959. * @param scene defines the hosting scene
  34960. * @param updatable defines if the mesh must be flagged as updatable
  34961. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34962. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  34963. * @returns a new Mesh
  34964. */
  34965. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34966. var options = {
  34967. shape: shape,
  34968. path: path,
  34969. scaleFunction: scaleFunction,
  34970. rotationFunction: rotationFunction,
  34971. ribbonCloseArray: ribbonCloseArray,
  34972. ribbonClosePath: ribbonClosePath,
  34973. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34974. sideOrientation: sideOrientation,
  34975. instance: instance,
  34976. updatable: updatable
  34977. };
  34978. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34979. };
  34980. /**
  34981. * Creates lathe mesh.
  34982. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34983. * Please consider using the same method from the MeshBuilder class instead
  34984. * @param name defines the name of the mesh to create
  34985. * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  34986. * @param radius is the radius value of the lathe
  34987. * @param tessellation is the side number of the lathe.
  34988. * @param scene defines the hosting scene
  34989. * @param updatable defines if the mesh must be flagged as updatable
  34990. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34991. * @returns a new Mesh
  34992. */
  34993. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34994. var options = {
  34995. shape: shape,
  34996. radius: radius,
  34997. tessellation: tessellation,
  34998. sideOrientation: sideOrientation,
  34999. updatable: updatable
  35000. };
  35001. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35002. };
  35003. /**
  35004. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35005. * @param name defines the name of the mesh to create
  35006. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35007. * @param scene defines the hosting scene
  35008. * @param updatable defines if the mesh must be flagged as updatable
  35009. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35010. * @returns a new Mesh
  35011. */
  35012. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35013. var options = {
  35014. size: size,
  35015. width: size,
  35016. height: size,
  35017. sideOrientation: sideOrientation,
  35018. updatable: updatable
  35019. };
  35020. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35021. };
  35022. /**
  35023. * Creates a ground mesh.
  35024. * Please consider using the same method from the MeshBuilder class instead
  35025. * @param name defines the name of the mesh to create
  35026. * @param width set the width of the ground
  35027. * @param height set the height of the ground
  35028. * @param subdivisions sets the number of subdivisions per side
  35029. * @param scene defines the hosting scene
  35030. * @param updatable defines if the mesh must be flagged as updatable
  35031. * @returns a new Mesh
  35032. */
  35033. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35034. var options = {
  35035. width: width,
  35036. height: height,
  35037. subdivisions: subdivisions,
  35038. updatable: updatable
  35039. };
  35040. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35041. };
  35042. /**
  35043. * Creates a tiled ground mesh.
  35044. * Please consider using the same method from the MeshBuilder class instead
  35045. * @param name defines the name of the mesh to create
  35046. * @param xmin set the ground minimum X coordinate
  35047. * @param zmin set the ground minimum Y coordinate
  35048. * @param xmax set the ground maximum X coordinate
  35049. * @param zmax set the ground maximum Z coordinate
  35050. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  35051. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  35052. * @param scene defines the hosting scene
  35053. * @param updatable defines if the mesh must be flagged as updatable
  35054. * @returns a new Mesh
  35055. */
  35056. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35057. var options = {
  35058. xmin: xmin,
  35059. zmin: zmin,
  35060. xmax: xmax,
  35061. zmax: zmax,
  35062. subdivisions: subdivisions,
  35063. precision: precision,
  35064. updatable: updatable
  35065. };
  35066. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35067. };
  35068. /**
  35069. * Creates a ground mesh from a height map.
  35070. * Please consider using the same method from the MeshBuilder class instead
  35071. * @see http://doc.babylonjs.com/babylon101/height_map
  35072. * @param name defines the name of the mesh to create
  35073. * @param url sets the URL of the height map image resource
  35074. * @param width set the ground width size
  35075. * @param height set the ground height size
  35076. * @param subdivisions sets the number of subdivision per side
  35077. * @param minHeight is the minimum altitude on the ground
  35078. * @param maxHeight is the maximum altitude on the ground
  35079. * @param scene defines the hosting scene
  35080. * @param updatable defines if the mesh must be flagged as updatable
  35081. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35082. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35083. * @returns a new Mesh
  35084. */
  35085. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35086. var options = {
  35087. width: width,
  35088. height: height,
  35089. subdivisions: subdivisions,
  35090. minHeight: minHeight,
  35091. maxHeight: maxHeight,
  35092. updatable: updatable,
  35093. onReady: onReady,
  35094. alphaFilter: alphaFilter
  35095. };
  35096. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35097. };
  35098. /**
  35099. * Creates a tube mesh.
  35100. * The tube is a parametric shape.
  35101. * It has no predefined shape. Its final shape will depend on the input parameters.
  35102. * Please consider using the same method from the MeshBuilder class instead
  35103. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35104. * @param name defines the name of the mesh to create
  35105. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35106. * @param radius sets the tube radius size
  35107. * @param tessellation is the number of sides on the tubular surface
  35108. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
  35109. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  35110. * @param scene defines the hosting scene
  35111. * @param updatable defines if the mesh must be flagged as updatable
  35112. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35113. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  35114. * @returns a new Mesh
  35115. */
  35116. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35117. var options = {
  35118. path: path,
  35119. radius: radius,
  35120. tessellation: tessellation,
  35121. radiusFunction: radiusFunction,
  35122. arc: 1,
  35123. cap: cap,
  35124. updatable: updatable,
  35125. sideOrientation: sideOrientation,
  35126. instance: instance
  35127. };
  35128. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35129. };
  35130. /**
  35131. * Creates a polyhedron mesh.
  35132. * Please consider using the same method from the MeshBuilder class instead.
  35133. * * 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
  35134. * * The parameter `size` (positive float, default 1) sets the polygon size
  35135. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35136. * * 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`
  35137. * * 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
  35138. * * 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)`)
  35139. * * 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
  35140. * * 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
  35141. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35142. * * 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
  35143. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35144. * @param name defines the name of the mesh to create
  35145. * @param options defines the options used to create the mesh
  35146. * @param scene defines the hosting scene
  35147. * @returns a new Mesh
  35148. */
  35149. Mesh.CreatePolyhedron = function (name, options, scene) {
  35150. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35151. };
  35152. /**
  35153. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35154. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35155. * * 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`)
  35156. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35157. * * 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
  35158. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35159. * * 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
  35160. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35161. * @param name defines the name of the mesh
  35162. * @param options defines the options used to create the mesh
  35163. * @param scene defines the hosting scene
  35164. * @returns a new Mesh
  35165. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35166. */
  35167. Mesh.CreateIcoSphere = function (name, options, scene) {
  35168. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35169. };
  35170. /**
  35171. * Creates a decal mesh.
  35172. * Please consider using the same method from the MeshBuilder class instead.
  35173. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35174. * @param name defines the name of the mesh
  35175. * @param sourceMesh defines the mesh receiving the decal
  35176. * @param position sets the position of the decal in world coordinates
  35177. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35178. * @param size sets the decal scaling
  35179. * @param angle sets the angle to rotate the decal
  35180. * @returns a new Mesh
  35181. */
  35182. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35183. var options = {
  35184. position: position,
  35185. normal: normal,
  35186. size: size,
  35187. angle: angle
  35188. };
  35189. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35190. };
  35191. // Skeletons
  35192. /**
  35193. * Prepare internal position array for software CPU skinning
  35194. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35195. */
  35196. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35197. if (!this._sourcePositions) {
  35198. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35199. if (!source) {
  35200. return this._sourcePositions;
  35201. }
  35202. this._sourcePositions = new Float32Array(source);
  35203. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35204. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35205. }
  35206. }
  35207. return this._sourcePositions;
  35208. };
  35209. /**
  35210. * Prepare internal normal array for software CPU skinning
  35211. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35212. */
  35213. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35214. if (!this._sourceNormals) {
  35215. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35216. if (!source) {
  35217. return this._sourceNormals;
  35218. }
  35219. this._sourceNormals = new Float32Array(source);
  35220. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35221. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35222. }
  35223. }
  35224. return this._sourceNormals;
  35225. };
  35226. /**
  35227. * Updates the vertex buffer by applying transformation from the bones
  35228. * @param skeleton defines the skeleton to apply to current mesh
  35229. * @returns the current mesh
  35230. */
  35231. Mesh.prototype.applySkeleton = function (skeleton) {
  35232. if (!this.geometry) {
  35233. return this;
  35234. }
  35235. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35236. return this;
  35237. }
  35238. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35239. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35240. return this;
  35241. }
  35242. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35243. return this;
  35244. }
  35245. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35246. return this;
  35247. }
  35248. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35249. return this;
  35250. }
  35251. if (!this._sourcePositions) {
  35252. var submeshes = this.subMeshes.slice();
  35253. this.setPositionsForCPUSkinning();
  35254. this.subMeshes = submeshes;
  35255. }
  35256. if (!this._sourceNormals) {
  35257. this.setNormalsForCPUSkinning();
  35258. }
  35259. // positionsData checks for not being Float32Array will only pass at most once
  35260. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35261. if (!positionsData) {
  35262. return this;
  35263. }
  35264. if (!(positionsData instanceof Float32Array)) {
  35265. positionsData = new Float32Array(positionsData);
  35266. }
  35267. // normalsData checks for not being Float32Array will only pass at most once
  35268. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35269. if (!normalsData) {
  35270. return this;
  35271. }
  35272. if (!(normalsData instanceof Float32Array)) {
  35273. normalsData = new Float32Array(normalsData);
  35274. }
  35275. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35276. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35277. if (!matricesWeightsData || !matricesIndicesData) {
  35278. return this;
  35279. }
  35280. var needExtras = this.numBoneInfluencers > 4;
  35281. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35282. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35283. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35284. var tempVector3 = BABYLON.Vector3.Zero();
  35285. var finalMatrix = new BABYLON.Matrix();
  35286. var tempMatrix = new BABYLON.Matrix();
  35287. var matWeightIdx = 0;
  35288. var inf;
  35289. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35290. var weight;
  35291. for (inf = 0; inf < 4; inf++) {
  35292. weight = matricesWeightsData[matWeightIdx + inf];
  35293. if (weight > 0) {
  35294. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35295. finalMatrix.addToSelf(tempMatrix);
  35296. }
  35297. }
  35298. if (needExtras) {
  35299. for (inf = 0; inf < 4; inf++) {
  35300. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35301. if (weight > 0) {
  35302. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35303. finalMatrix.addToSelf(tempMatrix);
  35304. }
  35305. }
  35306. }
  35307. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35308. tempVector3.toArray(positionsData, index);
  35309. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35310. tempVector3.toArray(normalsData, index);
  35311. finalMatrix.reset();
  35312. }
  35313. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35314. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35315. return this;
  35316. };
  35317. // Tools
  35318. /**
  35319. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  35320. * @param meshes defines the list of meshes to scan
  35321. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35322. */
  35323. Mesh.MinMax = function (meshes) {
  35324. var minVector = null;
  35325. var maxVector = null;
  35326. meshes.forEach(function (mesh, index, array) {
  35327. var boundingInfo = mesh.getBoundingInfo();
  35328. var boundingBox = boundingInfo.boundingBox;
  35329. if (!minVector || !maxVector) {
  35330. minVector = boundingBox.minimumWorld;
  35331. maxVector = boundingBox.maximumWorld;
  35332. }
  35333. else {
  35334. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35335. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35336. }
  35337. });
  35338. if (!minVector || !maxVector) {
  35339. return {
  35340. min: BABYLON.Vector3.Zero(),
  35341. max: BABYLON.Vector3.Zero()
  35342. };
  35343. }
  35344. return {
  35345. min: minVector,
  35346. max: maxVector
  35347. };
  35348. };
  35349. /**
  35350. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35351. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35352. * @returns a vector3
  35353. */
  35354. Mesh.Center = function (meshesOrMinMaxVector) {
  35355. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35356. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35357. };
  35358. /**
  35359. * Merge the array of meshes into a single mesh for performance reasons.
  35360. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35361. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35362. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35363. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35364. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35365. * @returns a new mesh
  35366. */
  35367. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35368. if (disposeSource === void 0) { disposeSource = true; }
  35369. var index;
  35370. if (!allow32BitsIndices) {
  35371. var totalVertices = 0;
  35372. // Counting vertices
  35373. for (index = 0; index < meshes.length; index++) {
  35374. if (meshes[index]) {
  35375. totalVertices += meshes[index].getTotalVertices();
  35376. if (totalVertices > 65536) {
  35377. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35378. return null;
  35379. }
  35380. }
  35381. }
  35382. }
  35383. // Merge
  35384. var vertexData = null;
  35385. var otherVertexData;
  35386. var indiceArray = new Array();
  35387. var source = null;
  35388. for (index = 0; index < meshes.length; index++) {
  35389. if (meshes[index]) {
  35390. var wm = meshes[index].computeWorldMatrix(true);
  35391. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35392. otherVertexData.transform(wm);
  35393. if (vertexData) {
  35394. vertexData.merge(otherVertexData, allow32BitsIndices);
  35395. }
  35396. else {
  35397. vertexData = otherVertexData;
  35398. source = meshes[index];
  35399. }
  35400. if (subdivideWithSubMeshes) {
  35401. indiceArray.push(meshes[index].getTotalIndices());
  35402. }
  35403. }
  35404. }
  35405. source = source;
  35406. if (!meshSubclass) {
  35407. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35408. }
  35409. vertexData.applyToMesh(meshSubclass);
  35410. // Setting properties
  35411. meshSubclass.material = source.material;
  35412. meshSubclass.checkCollisions = source.checkCollisions;
  35413. // Cleaning
  35414. if (disposeSource) {
  35415. for (index = 0; index < meshes.length; index++) {
  35416. if (meshes[index]) {
  35417. meshes[index].dispose();
  35418. }
  35419. }
  35420. }
  35421. // Subdivide
  35422. if (subdivideWithSubMeshes) {
  35423. //-- removal of global submesh
  35424. meshSubclass.releaseSubMeshes();
  35425. index = 0;
  35426. var offset = 0;
  35427. //-- apply subdivision according to index table
  35428. while (index < indiceArray.length) {
  35429. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35430. offset += indiceArray[index];
  35431. index++;
  35432. }
  35433. }
  35434. return meshSubclass;
  35435. };
  35436. // Consts
  35437. /**
  35438. * Mesh side orientation : usually the external or front surface
  35439. */
  35440. Mesh.FRONTSIDE = 0;
  35441. /**
  35442. * Mesh side orientation : usually the internal or back surface
  35443. */
  35444. Mesh.BACKSIDE = 1;
  35445. /**
  35446. * Mesh side orientation : both internal and external or front and back surfaces
  35447. */
  35448. Mesh.DOUBLESIDE = 2;
  35449. /**
  35450. * Mesh side orientation : by default, `FRONTSIDE`
  35451. */
  35452. Mesh.DEFAULTSIDE = 0;
  35453. /**
  35454. * Mesh cap setting : no cap
  35455. */
  35456. Mesh.NO_CAP = 0;
  35457. /**
  35458. * Mesh cap setting : one cap at the beginning of the mesh
  35459. */
  35460. Mesh.CAP_START = 1;
  35461. /**
  35462. * Mesh cap setting : one cap at the end of the mesh
  35463. */
  35464. Mesh.CAP_END = 2;
  35465. /**
  35466. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35467. */
  35468. Mesh.CAP_ALL = 3;
  35469. return Mesh;
  35470. }(BABYLON.AbstractMesh));
  35471. BABYLON.Mesh = Mesh;
  35472. })(BABYLON || (BABYLON = {}));
  35473. //# sourceMappingURL=babylon.mesh.js.map
  35474. var BABYLON;
  35475. (function (BABYLON) {
  35476. /**
  35477. * Base class for submeshes
  35478. */
  35479. var BaseSubMesh = /** @class */ (function () {
  35480. function BaseSubMesh() {
  35481. }
  35482. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35483. /**
  35484. * Gets associated effect
  35485. */
  35486. get: function () {
  35487. return this._materialEffect;
  35488. },
  35489. enumerable: true,
  35490. configurable: true
  35491. });
  35492. /**
  35493. * Sets associated effect (effect used to render this submesh)
  35494. * @param effect defines the effect to associate with
  35495. * @param defines defines the set of defines used to compile this effect
  35496. */
  35497. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35498. if (defines === void 0) { defines = null; }
  35499. if (this._materialEffect === effect) {
  35500. if (!effect) {
  35501. this._materialDefines = null;
  35502. }
  35503. return;
  35504. }
  35505. this._materialDefines = defines;
  35506. this._materialEffect = effect;
  35507. };
  35508. return BaseSubMesh;
  35509. }());
  35510. BABYLON.BaseSubMesh = BaseSubMesh;
  35511. /**
  35512. * Defines a subdivision inside a mesh
  35513. */
  35514. var SubMesh = /** @class */ (function (_super) {
  35515. __extends(SubMesh, _super);
  35516. /**
  35517. * Creates a new submesh
  35518. * @param materialIndex defines the material index to use
  35519. * @param verticesStart defines vertex index start
  35520. * @param verticesCount defines vertices count
  35521. * @param indexStart defines index start
  35522. * @param indexCount defines indices count
  35523. * @param mesh defines the parent mesh
  35524. * @param renderingMesh defines an optional rendering mesh
  35525. * @param createBoundingBox defines if bounding box should be created for this submesh
  35526. */
  35527. function SubMesh(
  35528. /** the material index to use */
  35529. materialIndex,
  35530. /** vertex index start */
  35531. verticesStart,
  35532. /** vertices count */
  35533. verticesCount,
  35534. /** index start */
  35535. indexStart,
  35536. /** indices count */
  35537. indexCount, mesh, renderingMesh, createBoundingBox) {
  35538. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35539. var _this = _super.call(this) || this;
  35540. _this.materialIndex = materialIndex;
  35541. _this.verticesStart = verticesStart;
  35542. _this.verticesCount = verticesCount;
  35543. _this.indexStart = indexStart;
  35544. _this.indexCount = indexCount;
  35545. /** @hidden */
  35546. _this._renderId = 0;
  35547. _this._mesh = mesh;
  35548. _this._renderingMesh = renderingMesh || mesh;
  35549. mesh.subMeshes.push(_this);
  35550. _this._trianglePlanes = [];
  35551. _this._id = mesh.subMeshes.length - 1;
  35552. if (createBoundingBox) {
  35553. _this.refreshBoundingInfo();
  35554. mesh.computeWorldMatrix(true);
  35555. }
  35556. return _this;
  35557. }
  35558. /**
  35559. * Add a new submesh to a mesh
  35560. * @param materialIndex defines the material index to use
  35561. * @param verticesStart defines vertex index start
  35562. * @param verticesCount defines vertices count
  35563. * @param indexStart defines index start
  35564. * @param indexCount defines indices count
  35565. * @param mesh defines the parent mesh
  35566. * @param renderingMesh defines an optional rendering mesh
  35567. * @param createBoundingBox defines if bounding box should be created for this submesh
  35568. * @returns the new submesh
  35569. */
  35570. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35571. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35572. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35573. };
  35574. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35575. /**
  35576. * Returns true if this submesh covers the entire parent mesh
  35577. * @ignorenaming
  35578. */
  35579. get: function () {
  35580. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35581. },
  35582. enumerable: true,
  35583. configurable: true
  35584. });
  35585. /**
  35586. * Returns the submesh BoudingInfo object
  35587. * @returns current bounding info (or mesh's one if the submesh is global)
  35588. */
  35589. SubMesh.prototype.getBoundingInfo = function () {
  35590. if (this.IsGlobal) {
  35591. return this._mesh.getBoundingInfo();
  35592. }
  35593. return this._boundingInfo;
  35594. };
  35595. /**
  35596. * Sets the submesh BoundingInfo
  35597. * @param boundingInfo defines the new bounding info to use
  35598. * @returns the SubMesh
  35599. */
  35600. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35601. this._boundingInfo = boundingInfo;
  35602. return this;
  35603. };
  35604. /**
  35605. * Returns the mesh of the current submesh
  35606. * @return the parent mesh
  35607. */
  35608. SubMesh.prototype.getMesh = function () {
  35609. return this._mesh;
  35610. };
  35611. /**
  35612. * Returns the rendering mesh of the submesh
  35613. * @returns the rendering mesh (could be different from parent mesh)
  35614. */
  35615. SubMesh.prototype.getRenderingMesh = function () {
  35616. return this._renderingMesh;
  35617. };
  35618. /**
  35619. * Returns the submesh material
  35620. * @returns null or the current material
  35621. */
  35622. SubMesh.prototype.getMaterial = function () {
  35623. var rootMaterial = this._renderingMesh.material;
  35624. if (rootMaterial === null || rootMaterial === undefined) {
  35625. return this._mesh.getScene().defaultMaterial;
  35626. }
  35627. else if (rootMaterial.getSubMaterial) {
  35628. var multiMaterial = rootMaterial;
  35629. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35630. if (this._currentMaterial !== effectiveMaterial) {
  35631. this._currentMaterial = effectiveMaterial;
  35632. this._materialDefines = null;
  35633. }
  35634. return effectiveMaterial;
  35635. }
  35636. return rootMaterial;
  35637. };
  35638. // Methods
  35639. /**
  35640. * Sets a new updated BoundingInfo object to the submesh
  35641. * @returns the SubMesh
  35642. */
  35643. SubMesh.prototype.refreshBoundingInfo = function () {
  35644. this._lastColliderWorldVertices = null;
  35645. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35646. return this;
  35647. }
  35648. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35649. if (!data) {
  35650. this._boundingInfo = this._mesh.getBoundingInfo();
  35651. return this;
  35652. }
  35653. var indices = this._renderingMesh.getIndices();
  35654. var extend;
  35655. //is this the only submesh?
  35656. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35657. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35658. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35659. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35660. }
  35661. else {
  35662. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35663. }
  35664. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35665. return this;
  35666. };
  35667. /** @hidden */
  35668. SubMesh.prototype._checkCollision = function (collider) {
  35669. var boundingInfo = this.getBoundingInfo();
  35670. return boundingInfo._checkCollision(collider);
  35671. };
  35672. /**
  35673. * Updates the submesh BoundingInfo
  35674. * @param world defines the world matrix to use to update the bounding info
  35675. * @returns the submesh
  35676. */
  35677. SubMesh.prototype.updateBoundingInfo = function (world) {
  35678. var boundingInfo = this.getBoundingInfo();
  35679. if (!boundingInfo) {
  35680. this.refreshBoundingInfo();
  35681. boundingInfo = this.getBoundingInfo();
  35682. }
  35683. boundingInfo.update(world);
  35684. return this;
  35685. };
  35686. /**
  35687. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35688. * @param frustumPlanes defines the frustum planes
  35689. * @returns true if the submesh is intersecting with the frustum
  35690. */
  35691. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35692. var boundingInfo = this.getBoundingInfo();
  35693. if (!boundingInfo) {
  35694. return false;
  35695. }
  35696. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35697. };
  35698. /**
  35699. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35700. * @param frustumPlanes defines the frustum planes
  35701. * @returns true if the submesh is inside the frustum
  35702. */
  35703. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35704. var boundingInfo = this.getBoundingInfo();
  35705. if (!boundingInfo) {
  35706. return false;
  35707. }
  35708. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35709. };
  35710. /**
  35711. * Renders the submesh
  35712. * @param enableAlphaMode defines if alpha needs to be used
  35713. * @returns the submesh
  35714. */
  35715. SubMesh.prototype.render = function (enableAlphaMode) {
  35716. this._renderingMesh.render(this, enableAlphaMode);
  35717. return this;
  35718. };
  35719. /**
  35720. * @hidden
  35721. */
  35722. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35723. if (!this._linesIndexBuffer) {
  35724. var linesIndices = [];
  35725. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35726. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35727. }
  35728. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35729. this._linesIndexCount = linesIndices.length;
  35730. }
  35731. return this._linesIndexBuffer;
  35732. };
  35733. /**
  35734. * Checks if the submesh intersects with a ray
  35735. * @param ray defines the ray to test
  35736. * @returns true is the passed ray intersects the submesh bounding box
  35737. */
  35738. SubMesh.prototype.canIntersects = function (ray) {
  35739. var boundingInfo = this.getBoundingInfo();
  35740. if (!boundingInfo) {
  35741. return false;
  35742. }
  35743. return ray.intersectsBox(boundingInfo.boundingBox);
  35744. };
  35745. /**
  35746. * Intersects current submesh with a ray
  35747. * @param ray defines the ray to test
  35748. * @param positions defines mesh's positions array
  35749. * @param indices defines mesh's indices array
  35750. * @param fastCheck defines if only bounding info should be used
  35751. * @returns intersection info or null if no intersection
  35752. */
  35753. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35754. var material = this.getMaterial();
  35755. if (!material) {
  35756. return null;
  35757. }
  35758. switch (material.fillMode) {
  35759. case BABYLON.Material.PointListDrawMode:
  35760. case BABYLON.Material.LineListDrawMode:
  35761. case BABYLON.Material.LineLoopDrawMode:
  35762. case BABYLON.Material.LineStripDrawMode:
  35763. case BABYLON.Material.TriangleFanDrawMode:
  35764. case BABYLON.Material.TriangleStripDrawMode:
  35765. return null;
  35766. }
  35767. // LineMesh first as it's also a Mesh...
  35768. if (BABYLON.LinesMesh) {
  35769. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35770. if (mesh instanceof BABYLON.LinesMesh) {
  35771. var linesMesh = mesh;
  35772. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  35773. }
  35774. }
  35775. return this._intersectTriangles(ray, positions, indices, fastCheck);
  35776. };
  35777. /** @hidden */
  35778. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  35779. var intersectInfo = null;
  35780. // Line test
  35781. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35782. var p0 = positions[indices[index]];
  35783. var p1 = positions[indices[index + 1]];
  35784. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  35785. if (length < 0) {
  35786. continue;
  35787. }
  35788. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35789. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35790. if (fastCheck) {
  35791. break;
  35792. }
  35793. }
  35794. }
  35795. return intersectInfo;
  35796. };
  35797. /** @hidden */
  35798. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  35799. var intersectInfo = null;
  35800. // Triangles test
  35801. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35802. var p0 = positions[indices[index]];
  35803. var p1 = positions[indices[index + 1]];
  35804. var p2 = positions[indices[index + 2]];
  35805. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35806. if (currentIntersectInfo) {
  35807. if (currentIntersectInfo.distance < 0) {
  35808. continue;
  35809. }
  35810. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35811. intersectInfo = currentIntersectInfo;
  35812. intersectInfo.faceId = index / 3;
  35813. if (fastCheck) {
  35814. break;
  35815. }
  35816. }
  35817. }
  35818. }
  35819. return intersectInfo;
  35820. };
  35821. /** @hidden */
  35822. SubMesh.prototype._rebuild = function () {
  35823. if (this._linesIndexBuffer) {
  35824. this._linesIndexBuffer = null;
  35825. }
  35826. };
  35827. // Clone
  35828. /**
  35829. * Creates a new submesh from the passed mesh
  35830. * @param newMesh defines the new hosting mesh
  35831. * @param newRenderingMesh defines an optional rendering mesh
  35832. * @returns the new submesh
  35833. */
  35834. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35835. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35836. if (!this.IsGlobal) {
  35837. var boundingInfo = this.getBoundingInfo();
  35838. if (!boundingInfo) {
  35839. return result;
  35840. }
  35841. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35842. }
  35843. return result;
  35844. };
  35845. // Dispose
  35846. /**
  35847. * Release associated resources
  35848. */
  35849. SubMesh.prototype.dispose = function () {
  35850. if (this._linesIndexBuffer) {
  35851. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35852. this._linesIndexBuffer = null;
  35853. }
  35854. // Remove from mesh
  35855. var index = this._mesh.subMeshes.indexOf(this);
  35856. this._mesh.subMeshes.splice(index, 1);
  35857. };
  35858. // Statics
  35859. /**
  35860. * Creates a new submesh from indices data
  35861. * @param materialIndex the index of the main mesh material
  35862. * @param startIndex the index where to start the copy in the mesh indices array
  35863. * @param indexCount the number of indices to copy then from the startIndex
  35864. * @param mesh the main mesh to create the submesh from
  35865. * @param renderingMesh the optional rendering mesh
  35866. * @returns a new submesh
  35867. */
  35868. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35869. var minVertexIndex = Number.MAX_VALUE;
  35870. var maxVertexIndex = -Number.MAX_VALUE;
  35871. renderingMesh = (renderingMesh || mesh);
  35872. var indices = renderingMesh.getIndices();
  35873. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35874. var vertexIndex = indices[index];
  35875. if (vertexIndex < minVertexIndex) {
  35876. minVertexIndex = vertexIndex;
  35877. }
  35878. if (vertexIndex > maxVertexIndex) {
  35879. maxVertexIndex = vertexIndex;
  35880. }
  35881. }
  35882. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35883. };
  35884. return SubMesh;
  35885. }(BaseSubMesh));
  35886. BABYLON.SubMesh = SubMesh;
  35887. })(BABYLON || (BABYLON = {}));
  35888. //# sourceMappingURL=babylon.subMesh.js.map
  35889. var __assign = (this && this.__assign) || function () {
  35890. __assign = Object.assign || function(t) {
  35891. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35892. s = arguments[i];
  35893. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35894. t[p] = s[p];
  35895. }
  35896. return t;
  35897. };
  35898. return __assign.apply(this, arguments);
  35899. };
  35900. var BABYLON;
  35901. (function (BABYLON) {
  35902. /**
  35903. * Manages the defines for the Material
  35904. */
  35905. var MaterialDefines = /** @class */ (function () {
  35906. function MaterialDefines() {
  35907. this._isDirty = true;
  35908. /** @hidden */
  35909. this._areLightsDirty = true;
  35910. /** @hidden */
  35911. this._areAttributesDirty = true;
  35912. /** @hidden */
  35913. this._areTexturesDirty = true;
  35914. /** @hidden */
  35915. this._areFresnelDirty = true;
  35916. /** @hidden */
  35917. this._areMiscDirty = true;
  35918. /** @hidden */
  35919. this._areImageProcessingDirty = true;
  35920. /** @hidden */
  35921. this._normals = false;
  35922. /** @hidden */
  35923. this._uvs = false;
  35924. /** @hidden */
  35925. this._needNormals = false;
  35926. /** @hidden */
  35927. this._needUVs = false;
  35928. }
  35929. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35930. /**
  35931. * Specifies if the material needs to be re-calculated
  35932. */
  35933. get: function () {
  35934. return this._isDirty;
  35935. },
  35936. enumerable: true,
  35937. configurable: true
  35938. });
  35939. /**
  35940. * Marks the material to indicate that it has been re-calculated
  35941. */
  35942. MaterialDefines.prototype.markAsProcessed = function () {
  35943. this._isDirty = false;
  35944. this._areAttributesDirty = false;
  35945. this._areTexturesDirty = false;
  35946. this._areFresnelDirty = false;
  35947. this._areLightsDirty = false;
  35948. this._areMiscDirty = false;
  35949. this._areImageProcessingDirty = false;
  35950. };
  35951. /**
  35952. * Marks the material to indicate that it needs to be re-calculated
  35953. */
  35954. MaterialDefines.prototype.markAsUnprocessed = function () {
  35955. this._isDirty = true;
  35956. };
  35957. /**
  35958. * Marks the material to indicate all of its defines need to be re-calculated
  35959. */
  35960. MaterialDefines.prototype.markAllAsDirty = function () {
  35961. this._areTexturesDirty = true;
  35962. this._areAttributesDirty = true;
  35963. this._areLightsDirty = true;
  35964. this._areFresnelDirty = true;
  35965. this._areMiscDirty = true;
  35966. this._areImageProcessingDirty = true;
  35967. this._isDirty = true;
  35968. };
  35969. /**
  35970. * Marks the material to indicate that image processing needs to be re-calculated
  35971. */
  35972. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35973. this._areImageProcessingDirty = true;
  35974. this._isDirty = true;
  35975. };
  35976. /**
  35977. * Marks the material to indicate the lights need to be re-calculated
  35978. */
  35979. MaterialDefines.prototype.markAsLightDirty = function () {
  35980. this._areLightsDirty = true;
  35981. this._isDirty = true;
  35982. };
  35983. /**
  35984. * Marks the attribute state as changed
  35985. */
  35986. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35987. this._areAttributesDirty = true;
  35988. this._isDirty = true;
  35989. };
  35990. /**
  35991. * Marks the texture state as changed
  35992. */
  35993. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35994. this._areTexturesDirty = true;
  35995. this._isDirty = true;
  35996. };
  35997. /**
  35998. * Marks the fresnel state as changed
  35999. */
  36000. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36001. this._areFresnelDirty = true;
  36002. this._isDirty = true;
  36003. };
  36004. /**
  36005. * Marks the misc state as changed
  36006. */
  36007. MaterialDefines.prototype.markAsMiscDirty = function () {
  36008. this._areMiscDirty = true;
  36009. this._isDirty = true;
  36010. };
  36011. /**
  36012. * Rebuilds the material defines
  36013. */
  36014. MaterialDefines.prototype.rebuild = function () {
  36015. if (this._keys) {
  36016. delete this._keys;
  36017. }
  36018. this._keys = [];
  36019. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36020. var key = _a[_i];
  36021. if (key[0] === "_") {
  36022. continue;
  36023. }
  36024. this._keys.push(key);
  36025. }
  36026. };
  36027. /**
  36028. * Specifies if two material defines are equal
  36029. * @param other - A material define instance to compare to
  36030. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36031. */
  36032. MaterialDefines.prototype.isEqual = function (other) {
  36033. if (this._keys.length !== other._keys.length) {
  36034. return false;
  36035. }
  36036. for (var index = 0; index < this._keys.length; index++) {
  36037. var prop = this._keys[index];
  36038. if (this[prop] !== other[prop]) {
  36039. return false;
  36040. }
  36041. }
  36042. return true;
  36043. };
  36044. /**
  36045. * Clones this instance's defines to another instance
  36046. * @param other - material defines to clone values to
  36047. */
  36048. MaterialDefines.prototype.cloneTo = function (other) {
  36049. if (this._keys.length !== other._keys.length) {
  36050. other._keys = this._keys.slice(0);
  36051. }
  36052. for (var index = 0; index < this._keys.length; index++) {
  36053. var prop = this._keys[index];
  36054. other[prop] = this[prop];
  36055. }
  36056. };
  36057. /**
  36058. * Resets the material define values
  36059. */
  36060. MaterialDefines.prototype.reset = function () {
  36061. for (var index = 0; index < this._keys.length; index++) {
  36062. var prop = this._keys[index];
  36063. var type = typeof this[prop];
  36064. switch (type) {
  36065. case "number":
  36066. this[prop] = 0;
  36067. break;
  36068. case "string":
  36069. this[prop] = "";
  36070. break;
  36071. default:
  36072. this[prop] = false;
  36073. break;
  36074. }
  36075. }
  36076. };
  36077. /**
  36078. * Converts the material define values to a string
  36079. * @returns - String of material define information
  36080. */
  36081. MaterialDefines.prototype.toString = function () {
  36082. var result = "";
  36083. for (var index = 0; index < this._keys.length; index++) {
  36084. var prop = this._keys[index];
  36085. var value = this[prop];
  36086. var type = typeof value;
  36087. switch (type) {
  36088. case "number":
  36089. case "string":
  36090. result += "#define " + prop + " " + value + "\n";
  36091. break;
  36092. default:
  36093. if (value) {
  36094. result += "#define " + prop + "\n";
  36095. }
  36096. break;
  36097. }
  36098. }
  36099. return result;
  36100. };
  36101. return MaterialDefines;
  36102. }());
  36103. BABYLON.MaterialDefines = MaterialDefines;
  36104. /**
  36105. * Base class for the main features of a material in Babylon.js
  36106. */
  36107. var Material = /** @class */ (function () {
  36108. /**
  36109. * Creates a material instance
  36110. * @param name defines the name of the material
  36111. * @param scene defines the scene to reference
  36112. * @param doNotAdd specifies if the material should be added to the scene
  36113. */
  36114. function Material(name, scene, doNotAdd) {
  36115. /**
  36116. * Specifies if the ready state should be checked on each call
  36117. */
  36118. this.checkReadyOnEveryCall = false;
  36119. /**
  36120. * Specifies if the ready state should be checked once
  36121. */
  36122. this.checkReadyOnlyOnce = false;
  36123. /**
  36124. * The state of the material
  36125. */
  36126. this.state = "";
  36127. /**
  36128. * The alpha value of the material
  36129. */
  36130. this._alpha = 1.0;
  36131. /**
  36132. * Specifies if back face culling is enabled
  36133. */
  36134. this._backFaceCulling = true;
  36135. /**
  36136. * Specifies if the material should be serialized
  36137. */
  36138. this.doNotSerialize = false;
  36139. /**
  36140. * Specifies if the effect should be stored on sub meshes
  36141. */
  36142. this.storeEffectOnSubMeshes = false;
  36143. /**
  36144. * An event triggered when the material is disposed
  36145. */
  36146. this.onDisposeObservable = new BABYLON.Observable();
  36147. /**
  36148. * Stores the value of the alpha mode
  36149. */
  36150. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36151. /**
  36152. * Stores the state of the need depth pre-pass value
  36153. */
  36154. this._needDepthPrePass = false;
  36155. /**
  36156. * Specifies if depth writing should be disabled
  36157. */
  36158. this.disableDepthWrite = false;
  36159. /**
  36160. * Specifies if depth writing should be forced
  36161. */
  36162. this.forceDepthWrite = false;
  36163. /**
  36164. * Specifies if there should be a separate pass for culling
  36165. */
  36166. this.separateCullingPass = false;
  36167. /**
  36168. * Stores the state specifing if fog should be enabled
  36169. */
  36170. this._fogEnabled = true;
  36171. /**
  36172. * Stores the size of points
  36173. */
  36174. this.pointSize = 1.0;
  36175. /**
  36176. * Stores the z offset value
  36177. */
  36178. this.zOffset = 0;
  36179. /**
  36180. * @hidden
  36181. * Specifies if the material was previously ready
  36182. */
  36183. this._wasPreviouslyReady = false;
  36184. /**
  36185. * Stores the fill mode state
  36186. */
  36187. this._fillMode = Material.TriangleFillMode;
  36188. this.name = name;
  36189. this.id = name || BABYLON.Tools.RandomId();
  36190. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36191. this.uniqueId = this._scene.getUniqueId();
  36192. if (this._scene.useRightHandedSystem) {
  36193. this.sideOrientation = Material.ClockWiseSideOrientation;
  36194. }
  36195. else {
  36196. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36197. }
  36198. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36199. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36200. if (!doNotAdd) {
  36201. this._scene.materials.push(this);
  36202. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  36203. }
  36204. }
  36205. Object.defineProperty(Material, "TriangleFillMode", {
  36206. /**
  36207. * Returns the triangle fill mode
  36208. */
  36209. get: function () {
  36210. return Material._TriangleFillMode;
  36211. },
  36212. enumerable: true,
  36213. configurable: true
  36214. });
  36215. Object.defineProperty(Material, "WireFrameFillMode", {
  36216. /**
  36217. * Returns the wireframe mode
  36218. */
  36219. get: function () {
  36220. return Material._WireFrameFillMode;
  36221. },
  36222. enumerable: true,
  36223. configurable: true
  36224. });
  36225. Object.defineProperty(Material, "PointFillMode", {
  36226. /**
  36227. * Returns the point fill mode
  36228. */
  36229. get: function () {
  36230. return Material._PointFillMode;
  36231. },
  36232. enumerable: true,
  36233. configurable: true
  36234. });
  36235. Object.defineProperty(Material, "PointListDrawMode", {
  36236. /**
  36237. * Returns the point list draw mode
  36238. */
  36239. get: function () {
  36240. return Material._PointListDrawMode;
  36241. },
  36242. enumerable: true,
  36243. configurable: true
  36244. });
  36245. Object.defineProperty(Material, "LineListDrawMode", {
  36246. /**
  36247. * Returns the line list draw mode
  36248. */
  36249. get: function () {
  36250. return Material._LineListDrawMode;
  36251. },
  36252. enumerable: true,
  36253. configurable: true
  36254. });
  36255. Object.defineProperty(Material, "LineLoopDrawMode", {
  36256. /**
  36257. * Returns the line loop draw mode
  36258. */
  36259. get: function () {
  36260. return Material._LineLoopDrawMode;
  36261. },
  36262. enumerable: true,
  36263. configurable: true
  36264. });
  36265. Object.defineProperty(Material, "LineStripDrawMode", {
  36266. /**
  36267. * Returns the line strip draw mode
  36268. */
  36269. get: function () {
  36270. return Material._LineStripDrawMode;
  36271. },
  36272. enumerable: true,
  36273. configurable: true
  36274. });
  36275. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36276. /**
  36277. * Returns the triangle strip draw mode
  36278. */
  36279. get: function () {
  36280. return Material._TriangleStripDrawMode;
  36281. },
  36282. enumerable: true,
  36283. configurable: true
  36284. });
  36285. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36286. /**
  36287. * Returns the triangle fan draw mode
  36288. */
  36289. get: function () {
  36290. return Material._TriangleFanDrawMode;
  36291. },
  36292. enumerable: true,
  36293. configurable: true
  36294. });
  36295. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36296. /**
  36297. * Returns the clock-wise side orientation
  36298. */
  36299. get: function () {
  36300. return Material._ClockWiseSideOrientation;
  36301. },
  36302. enumerable: true,
  36303. configurable: true
  36304. });
  36305. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36306. /**
  36307. * Returns the counter clock-wise side orientation
  36308. */
  36309. get: function () {
  36310. return Material._CounterClockWiseSideOrientation;
  36311. },
  36312. enumerable: true,
  36313. configurable: true
  36314. });
  36315. Object.defineProperty(Material.prototype, "alpha", {
  36316. /**
  36317. * Gets the alpha value of the material
  36318. */
  36319. get: function () {
  36320. return this._alpha;
  36321. },
  36322. /**
  36323. * Sets the alpha value of the material
  36324. */
  36325. set: function (value) {
  36326. if (this._alpha === value) {
  36327. return;
  36328. }
  36329. this._alpha = value;
  36330. this.markAsDirty(Material.MiscDirtyFlag);
  36331. },
  36332. enumerable: true,
  36333. configurable: true
  36334. });
  36335. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36336. /**
  36337. * Gets the back-face culling state
  36338. */
  36339. get: function () {
  36340. return this._backFaceCulling;
  36341. },
  36342. /**
  36343. * Sets the back-face culling state
  36344. */
  36345. set: function (value) {
  36346. if (this._backFaceCulling === value) {
  36347. return;
  36348. }
  36349. this._backFaceCulling = value;
  36350. this.markAsDirty(Material.TextureDirtyFlag);
  36351. },
  36352. enumerable: true,
  36353. configurable: true
  36354. });
  36355. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36356. /**
  36357. * Gets a boolean indicating that current material needs to register RTT
  36358. */
  36359. get: function () {
  36360. return false;
  36361. },
  36362. enumerable: true,
  36363. configurable: true
  36364. });
  36365. Object.defineProperty(Material.prototype, "onDispose", {
  36366. /**
  36367. * Called during a dispose event
  36368. */
  36369. set: function (callback) {
  36370. if (this._onDisposeObserver) {
  36371. this.onDisposeObservable.remove(this._onDisposeObserver);
  36372. }
  36373. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36374. },
  36375. enumerable: true,
  36376. configurable: true
  36377. });
  36378. Object.defineProperty(Material.prototype, "onBindObservable", {
  36379. /**
  36380. * An event triggered when the material is bound
  36381. */
  36382. get: function () {
  36383. if (!this._onBindObservable) {
  36384. this._onBindObservable = new BABYLON.Observable();
  36385. }
  36386. return this._onBindObservable;
  36387. },
  36388. enumerable: true,
  36389. configurable: true
  36390. });
  36391. Object.defineProperty(Material.prototype, "onBind", {
  36392. /**
  36393. * Called during a bind event
  36394. */
  36395. set: function (callback) {
  36396. if (this._onBindObserver) {
  36397. this.onBindObservable.remove(this._onBindObserver);
  36398. }
  36399. this._onBindObserver = this.onBindObservable.add(callback);
  36400. },
  36401. enumerable: true,
  36402. configurable: true
  36403. });
  36404. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36405. /**
  36406. * An event triggered when the material is unbound
  36407. */
  36408. get: function () {
  36409. if (!this._onUnBindObservable) {
  36410. this._onUnBindObservable = new BABYLON.Observable();
  36411. }
  36412. return this._onUnBindObservable;
  36413. },
  36414. enumerable: true,
  36415. configurable: true
  36416. });
  36417. Object.defineProperty(Material.prototype, "alphaMode", {
  36418. /**
  36419. * Gets the value of the alpha mode
  36420. */
  36421. get: function () {
  36422. return this._alphaMode;
  36423. },
  36424. /**
  36425. * Sets the value of the alpha mode.
  36426. *
  36427. * | Value | Type | Description |
  36428. * | --- | --- | --- |
  36429. * | 0 | ALPHA_DISABLE | |
  36430. * | 1 | ALPHA_ADD | |
  36431. * | 2 | ALPHA_COMBINE | |
  36432. * | 3 | ALPHA_SUBTRACT | |
  36433. * | 4 | ALPHA_MULTIPLY | |
  36434. * | 5 | ALPHA_MAXIMIZED | |
  36435. * | 6 | ALPHA_ONEONE | |
  36436. * | 7 | ALPHA_PREMULTIPLIED | |
  36437. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36438. * | 9 | ALPHA_INTERPOLATE | |
  36439. * | 10 | ALPHA_SCREENMODE | |
  36440. *
  36441. */
  36442. set: function (value) {
  36443. if (this._alphaMode === value) {
  36444. return;
  36445. }
  36446. this._alphaMode = value;
  36447. this.markAsDirty(Material.TextureDirtyFlag);
  36448. },
  36449. enumerable: true,
  36450. configurable: true
  36451. });
  36452. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36453. /**
  36454. * Gets the depth pre-pass value
  36455. */
  36456. get: function () {
  36457. return this._needDepthPrePass;
  36458. },
  36459. /**
  36460. * Sets the need depth pre-pass value
  36461. */
  36462. set: function (value) {
  36463. if (this._needDepthPrePass === value) {
  36464. return;
  36465. }
  36466. this._needDepthPrePass = value;
  36467. if (this._needDepthPrePass) {
  36468. this.checkReadyOnEveryCall = true;
  36469. }
  36470. },
  36471. enumerable: true,
  36472. configurable: true
  36473. });
  36474. Object.defineProperty(Material.prototype, "fogEnabled", {
  36475. /**
  36476. * Gets the value of the fog enabled state
  36477. */
  36478. get: function () {
  36479. return this._fogEnabled;
  36480. },
  36481. /**
  36482. * Sets the state for enabling fog
  36483. */
  36484. set: function (value) {
  36485. if (this._fogEnabled === value) {
  36486. return;
  36487. }
  36488. this._fogEnabled = value;
  36489. this.markAsDirty(Material.MiscDirtyFlag);
  36490. },
  36491. enumerable: true,
  36492. configurable: true
  36493. });
  36494. Object.defineProperty(Material.prototype, "wireframe", {
  36495. /**
  36496. * Gets a value specifying if wireframe mode is enabled
  36497. */
  36498. get: function () {
  36499. switch (this._fillMode) {
  36500. case Material.WireFrameFillMode:
  36501. case Material.LineListDrawMode:
  36502. case Material.LineLoopDrawMode:
  36503. case Material.LineStripDrawMode:
  36504. return true;
  36505. }
  36506. return this._scene.forceWireframe;
  36507. },
  36508. /**
  36509. * Sets the state of wireframe mode
  36510. */
  36511. set: function (value) {
  36512. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36513. },
  36514. enumerable: true,
  36515. configurable: true
  36516. });
  36517. Object.defineProperty(Material.prototype, "pointsCloud", {
  36518. /**
  36519. * Gets the value specifying if point clouds are enabled
  36520. */
  36521. get: function () {
  36522. switch (this._fillMode) {
  36523. case Material.PointFillMode:
  36524. case Material.PointListDrawMode:
  36525. return true;
  36526. }
  36527. return this._scene.forcePointsCloud;
  36528. },
  36529. /**
  36530. * Sets the state of point cloud mode
  36531. */
  36532. set: function (value) {
  36533. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36534. },
  36535. enumerable: true,
  36536. configurable: true
  36537. });
  36538. Object.defineProperty(Material.prototype, "fillMode", {
  36539. /**
  36540. * Gets the material fill mode
  36541. */
  36542. get: function () {
  36543. return this._fillMode;
  36544. },
  36545. /**
  36546. * Sets the material fill mode
  36547. */
  36548. set: function (value) {
  36549. if (this._fillMode === value) {
  36550. return;
  36551. }
  36552. this._fillMode = value;
  36553. this.markAsDirty(Material.MiscDirtyFlag);
  36554. },
  36555. enumerable: true,
  36556. configurable: true
  36557. });
  36558. /**
  36559. * Returns a string representation of the current material
  36560. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36561. * @returns a string with material information
  36562. */
  36563. Material.prototype.toString = function (fullDetails) {
  36564. var ret = "Name: " + this.name;
  36565. if (fullDetails) {
  36566. }
  36567. return ret;
  36568. };
  36569. /**
  36570. * Gets the class name of the material
  36571. * @returns a string with the class name of the material
  36572. */
  36573. Material.prototype.getClassName = function () {
  36574. return "Material";
  36575. };
  36576. Object.defineProperty(Material.prototype, "isFrozen", {
  36577. /**
  36578. * Specifies if updates for the material been locked
  36579. */
  36580. get: function () {
  36581. return this.checkReadyOnlyOnce;
  36582. },
  36583. enumerable: true,
  36584. configurable: true
  36585. });
  36586. /**
  36587. * Locks updates for the material
  36588. */
  36589. Material.prototype.freeze = function () {
  36590. this.checkReadyOnlyOnce = true;
  36591. };
  36592. /**
  36593. * Unlocks updates for the material
  36594. */
  36595. Material.prototype.unfreeze = function () {
  36596. this.checkReadyOnlyOnce = false;
  36597. };
  36598. /**
  36599. * Specifies if the material is ready to be used
  36600. * @param mesh defines the mesh to check
  36601. * @param useInstances specifies if instances should be used
  36602. * @returns a boolean indicating if the material is ready to be used
  36603. */
  36604. Material.prototype.isReady = function (mesh, useInstances) {
  36605. return true;
  36606. };
  36607. /**
  36608. * Specifies that the submesh is ready to be used
  36609. * @param mesh defines the mesh to check
  36610. * @param subMesh defines which submesh to check
  36611. * @param useInstances specifies that instances should be used
  36612. * @returns a boolean indicating that the submesh is ready or not
  36613. */
  36614. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36615. return false;
  36616. };
  36617. /**
  36618. * Returns the material effect
  36619. * @returns the effect associated with the material
  36620. */
  36621. Material.prototype.getEffect = function () {
  36622. return this._effect;
  36623. };
  36624. /**
  36625. * Returns the current scene
  36626. * @returns a Scene
  36627. */
  36628. Material.prototype.getScene = function () {
  36629. return this._scene;
  36630. };
  36631. /**
  36632. * Specifies if the material will require alpha blending
  36633. * @returns a boolean specifying if alpha blending is needed
  36634. */
  36635. Material.prototype.needAlphaBlending = function () {
  36636. return (this.alpha < 1.0);
  36637. };
  36638. /**
  36639. * Specifies if the mesh will require alpha blending
  36640. * @param mesh defines the mesh to check
  36641. * @returns a boolean specifying if alpha blending is needed for the mesh
  36642. */
  36643. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36644. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36645. };
  36646. /**
  36647. * Specifies if this material should be rendered in alpha test mode
  36648. * @returns a boolean specifying if an alpha test is needed.
  36649. */
  36650. Material.prototype.needAlphaTesting = function () {
  36651. return false;
  36652. };
  36653. /**
  36654. * Gets the texture used for the alpha test
  36655. * @returns the texture to use for alpha testing
  36656. */
  36657. Material.prototype.getAlphaTestTexture = function () {
  36658. return null;
  36659. };
  36660. /**
  36661. * Marks the material to indicate that it needs to be re-calculated
  36662. */
  36663. Material.prototype.markDirty = function () {
  36664. this._wasPreviouslyReady = false;
  36665. };
  36666. /** @hidden */
  36667. Material.prototype._preBind = function (effect, overrideOrientation) {
  36668. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36669. var engine = this._scene.getEngine();
  36670. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36671. var reverse = orientation === Material.ClockWiseSideOrientation;
  36672. engine.enableEffect(effect ? effect : this._effect);
  36673. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36674. return reverse;
  36675. };
  36676. /**
  36677. * Binds the material to the mesh
  36678. * @param world defines the world transformation matrix
  36679. * @param mesh defines the mesh to bind the material to
  36680. */
  36681. Material.prototype.bind = function (world, mesh) {
  36682. };
  36683. /**
  36684. * Binds the submesh to the material
  36685. * @param world defines the world transformation matrix
  36686. * @param mesh defines the mesh containing the submesh
  36687. * @param subMesh defines the submesh to bind the material to
  36688. */
  36689. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36690. };
  36691. /**
  36692. * Binds the world matrix to the material
  36693. * @param world defines the world transformation matrix
  36694. */
  36695. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36696. };
  36697. /**
  36698. * Binds the scene's uniform buffer to the effect.
  36699. * @param effect defines the effect to bind to the scene uniform buffer
  36700. * @param sceneUbo defines the uniform buffer storing scene data
  36701. */
  36702. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36703. sceneUbo.bindToEffect(effect, "Scene");
  36704. };
  36705. /**
  36706. * Binds the view matrix to the effect
  36707. * @param effect defines the effect to bind the view matrix to
  36708. */
  36709. Material.prototype.bindView = function (effect) {
  36710. if (!this._useUBO) {
  36711. effect.setMatrix("view", this.getScene().getViewMatrix());
  36712. }
  36713. else {
  36714. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36715. }
  36716. };
  36717. /**
  36718. * Binds the view projection matrix to the effect
  36719. * @param effect defines the effect to bind the view projection matrix to
  36720. */
  36721. Material.prototype.bindViewProjection = function (effect) {
  36722. if (!this._useUBO) {
  36723. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36724. }
  36725. else {
  36726. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36727. }
  36728. };
  36729. /**
  36730. * Specifies if material alpha testing should be turned on for the mesh
  36731. * @param mesh defines the mesh to check
  36732. */
  36733. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36734. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36735. };
  36736. /**
  36737. * Processes to execute after binding the material to a mesh
  36738. * @param mesh defines the rendered mesh
  36739. */
  36740. Material.prototype._afterBind = function (mesh) {
  36741. this._scene._cachedMaterial = this;
  36742. if (mesh) {
  36743. this._scene._cachedVisibility = mesh.visibility;
  36744. }
  36745. else {
  36746. this._scene._cachedVisibility = 1;
  36747. }
  36748. if (this._onBindObservable && mesh) {
  36749. this._onBindObservable.notifyObservers(mesh);
  36750. }
  36751. if (this.disableDepthWrite) {
  36752. var engine = this._scene.getEngine();
  36753. this._cachedDepthWriteState = engine.getDepthWrite();
  36754. engine.setDepthWrite(false);
  36755. }
  36756. };
  36757. /**
  36758. * Unbinds the material from the mesh
  36759. */
  36760. Material.prototype.unbind = function () {
  36761. if (this._onUnBindObservable) {
  36762. this._onUnBindObservable.notifyObservers(this);
  36763. }
  36764. if (this.disableDepthWrite) {
  36765. var engine = this._scene.getEngine();
  36766. engine.setDepthWrite(this._cachedDepthWriteState);
  36767. }
  36768. };
  36769. /**
  36770. * Gets the active textures from the material
  36771. * @returns an array of textures
  36772. */
  36773. Material.prototype.getActiveTextures = function () {
  36774. return [];
  36775. };
  36776. /**
  36777. * Specifies if the material uses a texture
  36778. * @param texture defines the texture to check against the material
  36779. * @returns a boolean specifying if the material uses the texture
  36780. */
  36781. Material.prototype.hasTexture = function (texture) {
  36782. return false;
  36783. };
  36784. /**
  36785. * Makes a duplicate of the material, and gives it a new name
  36786. * @param name defines the new name for the duplicated material
  36787. * @returns the cloned material
  36788. */
  36789. Material.prototype.clone = function (name) {
  36790. return null;
  36791. };
  36792. /**
  36793. * Gets the meshes bound to the material
  36794. * @returns an array of meshes bound to the material
  36795. */
  36796. Material.prototype.getBindedMeshes = function () {
  36797. var result = new Array();
  36798. for (var index = 0; index < this._scene.meshes.length; index++) {
  36799. var mesh = this._scene.meshes[index];
  36800. if (mesh.material === this) {
  36801. result.push(mesh);
  36802. }
  36803. }
  36804. return result;
  36805. };
  36806. /**
  36807. * Force shader compilation
  36808. * @param mesh defines the mesh associated with this material
  36809. * @param onCompiled defines a function to execute once the material is compiled
  36810. * @param options defines the options to configure the compilation
  36811. */
  36812. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36813. var _this = this;
  36814. var localOptions = __assign({ clipPlane: false }, options);
  36815. var subMesh = new BABYLON.BaseSubMesh();
  36816. var scene = this.getScene();
  36817. var checkReady = function () {
  36818. if (!_this._scene || !_this._scene.getEngine()) {
  36819. return;
  36820. }
  36821. if (subMesh._materialDefines) {
  36822. subMesh._materialDefines._renderId = -1;
  36823. }
  36824. var clipPlaneState = scene.clipPlane;
  36825. if (localOptions.clipPlane) {
  36826. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36827. }
  36828. if (_this.storeEffectOnSubMeshes) {
  36829. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36830. if (onCompiled) {
  36831. onCompiled(_this);
  36832. }
  36833. }
  36834. else {
  36835. setTimeout(checkReady, 16);
  36836. }
  36837. }
  36838. else {
  36839. if (_this.isReady(mesh)) {
  36840. if (onCompiled) {
  36841. onCompiled(_this);
  36842. }
  36843. }
  36844. else {
  36845. setTimeout(checkReady, 16);
  36846. }
  36847. }
  36848. if (localOptions.clipPlane) {
  36849. scene.clipPlane = clipPlaneState;
  36850. }
  36851. };
  36852. checkReady();
  36853. };
  36854. /**
  36855. * Force shader compilation
  36856. * @param mesh defines the mesh that will use this material
  36857. * @param options defines additional options for compiling the shaders
  36858. * @returns a promise that resolves when the compilation completes
  36859. */
  36860. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36861. var _this = this;
  36862. return new Promise(function (resolve) {
  36863. _this.forceCompilation(mesh, function () {
  36864. resolve();
  36865. }, options);
  36866. });
  36867. };
  36868. /**
  36869. * Marks a define in the material to indicate that it needs to be re-computed
  36870. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36871. */
  36872. Material.prototype.markAsDirty = function (flag) {
  36873. if (flag & Material.TextureDirtyFlag) {
  36874. this._markAllSubMeshesAsTexturesDirty();
  36875. }
  36876. if (flag & Material.LightDirtyFlag) {
  36877. this._markAllSubMeshesAsLightsDirty();
  36878. }
  36879. if (flag & Material.FresnelDirtyFlag) {
  36880. this._markAllSubMeshesAsFresnelDirty();
  36881. }
  36882. if (flag & Material.AttributesDirtyFlag) {
  36883. this._markAllSubMeshesAsAttributesDirty();
  36884. }
  36885. if (flag & Material.MiscDirtyFlag) {
  36886. this._markAllSubMeshesAsMiscDirty();
  36887. }
  36888. this.getScene().resetCachedMaterial();
  36889. };
  36890. /**
  36891. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36892. * @param func defines a function which checks material defines against the submeshes
  36893. */
  36894. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36895. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36896. var mesh = _a[_i];
  36897. if (!mesh.subMeshes) {
  36898. continue;
  36899. }
  36900. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36901. var subMesh = _c[_b];
  36902. if (subMesh.getMaterial() !== this) {
  36903. continue;
  36904. }
  36905. if (!subMesh._materialDefines) {
  36906. continue;
  36907. }
  36908. func(subMesh._materialDefines);
  36909. }
  36910. }
  36911. };
  36912. /**
  36913. * Indicates that image processing needs to be re-calculated for all submeshes
  36914. */
  36915. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36916. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36917. };
  36918. /**
  36919. * Indicates that textures need to be re-calculated for all submeshes
  36920. */
  36921. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36922. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36923. };
  36924. /**
  36925. * Indicates that fresnel needs to be re-calculated for all submeshes
  36926. */
  36927. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36928. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36929. };
  36930. /**
  36931. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36932. */
  36933. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36934. this._markAllSubMeshesAsDirty(function (defines) {
  36935. defines.markAsFresnelDirty();
  36936. defines.markAsMiscDirty();
  36937. });
  36938. };
  36939. /**
  36940. * Indicates that lights need to be re-calculated for all submeshes
  36941. */
  36942. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36943. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36944. };
  36945. /**
  36946. * Indicates that attributes need to be re-calculated for all submeshes
  36947. */
  36948. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36949. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36950. };
  36951. /**
  36952. * Indicates that misc needs to be re-calculated for all submeshes
  36953. */
  36954. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36955. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36956. };
  36957. /**
  36958. * Indicates that textures and misc need to be re-calculated for all submeshes
  36959. */
  36960. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36961. this._markAllSubMeshesAsDirty(function (defines) {
  36962. defines.markAsTexturesDirty();
  36963. defines.markAsMiscDirty();
  36964. });
  36965. };
  36966. /**
  36967. * Disposes the material
  36968. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36969. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36970. */
  36971. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36972. // Animations
  36973. this.getScene().stopAnimation(this);
  36974. this.getScene().freeProcessedMaterials();
  36975. // Remove from scene
  36976. var index = this._scene.materials.indexOf(this);
  36977. if (index >= 0) {
  36978. this._scene.materials.splice(index, 1);
  36979. }
  36980. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36981. // Remove from meshes
  36982. for (index = 0; index < this._scene.meshes.length; index++) {
  36983. var mesh = this._scene.meshes[index];
  36984. if (mesh.material === this) {
  36985. mesh.material = null;
  36986. if (mesh.geometry) {
  36987. var geometry = (mesh.geometry);
  36988. if (this.storeEffectOnSubMeshes) {
  36989. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36990. var subMesh = _a[_i];
  36991. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36992. if (forceDisposeEffect && subMesh._materialEffect) {
  36993. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36994. }
  36995. }
  36996. }
  36997. else {
  36998. geometry._releaseVertexArrayObject(this._effect);
  36999. }
  37000. }
  37001. }
  37002. }
  37003. this._uniformBuffer.dispose();
  37004. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37005. if (forceDisposeEffect && this._effect) {
  37006. if (!this.storeEffectOnSubMeshes) {
  37007. this._scene.getEngine()._releaseEffect(this._effect);
  37008. }
  37009. this._effect = null;
  37010. }
  37011. // Callback
  37012. this.onDisposeObservable.notifyObservers(this);
  37013. this.onDisposeObservable.clear();
  37014. if (this._onBindObservable) {
  37015. this._onBindObservable.clear();
  37016. }
  37017. if (this._onUnBindObservable) {
  37018. this._onUnBindObservable.clear();
  37019. }
  37020. };
  37021. /**
  37022. * Serializes this material
  37023. * @returns the serialized material object
  37024. */
  37025. Material.prototype.serialize = function () {
  37026. return BABYLON.SerializationHelper.Serialize(this);
  37027. };
  37028. /**
  37029. * Creates a MultiMaterial from parsed MultiMaterial data.
  37030. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37031. * @param scene defines the hosting scene
  37032. * @returns a new MultiMaterial
  37033. */
  37034. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37035. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37036. multiMaterial.id = parsedMultiMaterial.id;
  37037. if (BABYLON.Tags) {
  37038. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37039. }
  37040. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37041. var subMatId = parsedMultiMaterial.materials[matIndex];
  37042. if (subMatId) {
  37043. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37044. }
  37045. else {
  37046. multiMaterial.subMaterials.push(null);
  37047. }
  37048. }
  37049. return multiMaterial;
  37050. };
  37051. /**
  37052. * Creates a material from parsed material data
  37053. * @param parsedMaterial defines parsed material data
  37054. * @param scene defines the hosting scene
  37055. * @param rootUrl defines the root URL to use to load textures
  37056. * @returns a new material
  37057. */
  37058. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37059. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37060. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37061. }
  37062. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37063. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37064. if (!BABYLON.LegacyPBRMaterial) {
  37065. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37066. return;
  37067. }
  37068. }
  37069. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37070. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37071. };
  37072. // Triangle views
  37073. Material._TriangleFillMode = 0;
  37074. Material._WireFrameFillMode = 1;
  37075. Material._PointFillMode = 2;
  37076. // Draw modes
  37077. Material._PointListDrawMode = 3;
  37078. Material._LineListDrawMode = 4;
  37079. Material._LineLoopDrawMode = 5;
  37080. Material._LineStripDrawMode = 6;
  37081. Material._TriangleStripDrawMode = 7;
  37082. Material._TriangleFanDrawMode = 8;
  37083. /**
  37084. * Stores the clock-wise side orientation
  37085. */
  37086. Material._ClockWiseSideOrientation = 0;
  37087. /**
  37088. * Stores the counter clock-wise side orientation
  37089. */
  37090. Material._CounterClockWiseSideOrientation = 1;
  37091. /**
  37092. * The dirty texture flag value
  37093. */
  37094. Material.TextureDirtyFlag = 1;
  37095. /**
  37096. * The dirty light flag value
  37097. */
  37098. Material.LightDirtyFlag = 2;
  37099. /**
  37100. * The dirty fresnel flag value
  37101. */
  37102. Material.FresnelDirtyFlag = 4;
  37103. /**
  37104. * The dirty attribute flag value
  37105. */
  37106. Material.AttributesDirtyFlag = 8;
  37107. /**
  37108. * The dirty misc flag value
  37109. */
  37110. Material.MiscDirtyFlag = 16;
  37111. /**
  37112. * The all dirty flag value
  37113. */
  37114. Material.AllDirtyFlag = 31;
  37115. __decorate([
  37116. BABYLON.serialize()
  37117. ], Material.prototype, "id", void 0);
  37118. __decorate([
  37119. BABYLON.serialize()
  37120. ], Material.prototype, "uniqueId", void 0);
  37121. __decorate([
  37122. BABYLON.serialize()
  37123. ], Material.prototype, "name", void 0);
  37124. __decorate([
  37125. BABYLON.serialize()
  37126. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37127. __decorate([
  37128. BABYLON.serialize()
  37129. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37130. __decorate([
  37131. BABYLON.serialize()
  37132. ], Material.prototype, "state", void 0);
  37133. __decorate([
  37134. BABYLON.serialize("alpha")
  37135. ], Material.prototype, "_alpha", void 0);
  37136. __decorate([
  37137. BABYLON.serialize("backFaceCulling")
  37138. ], Material.prototype, "_backFaceCulling", void 0);
  37139. __decorate([
  37140. BABYLON.serialize()
  37141. ], Material.prototype, "sideOrientation", void 0);
  37142. __decorate([
  37143. BABYLON.serialize("alphaMode")
  37144. ], Material.prototype, "_alphaMode", void 0);
  37145. __decorate([
  37146. BABYLON.serialize()
  37147. ], Material.prototype, "_needDepthPrePass", void 0);
  37148. __decorate([
  37149. BABYLON.serialize()
  37150. ], Material.prototype, "disableDepthWrite", void 0);
  37151. __decorate([
  37152. BABYLON.serialize()
  37153. ], Material.prototype, "forceDepthWrite", void 0);
  37154. __decorate([
  37155. BABYLON.serialize()
  37156. ], Material.prototype, "separateCullingPass", void 0);
  37157. __decorate([
  37158. BABYLON.serialize("fogEnabled")
  37159. ], Material.prototype, "_fogEnabled", void 0);
  37160. __decorate([
  37161. BABYLON.serialize()
  37162. ], Material.prototype, "pointSize", void 0);
  37163. __decorate([
  37164. BABYLON.serialize()
  37165. ], Material.prototype, "zOffset", void 0);
  37166. __decorate([
  37167. BABYLON.serialize()
  37168. ], Material.prototype, "wireframe", null);
  37169. __decorate([
  37170. BABYLON.serialize()
  37171. ], Material.prototype, "pointsCloud", null);
  37172. __decorate([
  37173. BABYLON.serialize()
  37174. ], Material.prototype, "fillMode", null);
  37175. return Material;
  37176. }());
  37177. BABYLON.Material = Material;
  37178. })(BABYLON || (BABYLON = {}));
  37179. //# sourceMappingURL=babylon.material.js.map
  37180. var BABYLON;
  37181. (function (BABYLON) {
  37182. /**
  37183. * Uniform buffer objects.
  37184. *
  37185. * Handles blocks of uniform on the GPU.
  37186. *
  37187. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37188. *
  37189. * For more information, please refer to :
  37190. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37191. */
  37192. var UniformBuffer = /** @class */ (function () {
  37193. /**
  37194. * Instantiates a new Uniform buffer objects.
  37195. *
  37196. * Handles blocks of uniform on the GPU.
  37197. *
  37198. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37199. *
  37200. * For more information, please refer to :
  37201. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37202. * @param engine Define the engine the buffer is associated with
  37203. * @param data Define the data contained in the buffer
  37204. * @param dynamic Define if the buffer is updatable
  37205. */
  37206. function UniformBuffer(engine, data, dynamic) {
  37207. this._engine = engine;
  37208. this._noUBO = !engine.supportsUniformBuffers;
  37209. this._dynamic = dynamic;
  37210. this._data = data || [];
  37211. this._uniformLocations = {};
  37212. this._uniformSizes = {};
  37213. this._uniformLocationPointer = 0;
  37214. this._needSync = false;
  37215. if (this._noUBO) {
  37216. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37217. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37218. this.updateFloat = this._updateFloatForEffect;
  37219. this.updateFloat2 = this._updateFloat2ForEffect;
  37220. this.updateFloat3 = this._updateFloat3ForEffect;
  37221. this.updateFloat4 = this._updateFloat4ForEffect;
  37222. this.updateMatrix = this._updateMatrixForEffect;
  37223. this.updateVector3 = this._updateVector3ForEffect;
  37224. this.updateVector4 = this._updateVector4ForEffect;
  37225. this.updateColor3 = this._updateColor3ForEffect;
  37226. this.updateColor4 = this._updateColor4ForEffect;
  37227. }
  37228. else {
  37229. this._engine._uniformBuffers.push(this);
  37230. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37231. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37232. this.updateFloat = this._updateFloatForUniform;
  37233. this.updateFloat2 = this._updateFloat2ForUniform;
  37234. this.updateFloat3 = this._updateFloat3ForUniform;
  37235. this.updateFloat4 = this._updateFloat4ForUniform;
  37236. this.updateMatrix = this._updateMatrixForUniform;
  37237. this.updateVector3 = this._updateVector3ForUniform;
  37238. this.updateVector4 = this._updateVector4ForUniform;
  37239. this.updateColor3 = this._updateColor3ForUniform;
  37240. this.updateColor4 = this._updateColor4ForUniform;
  37241. }
  37242. }
  37243. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37244. /**
  37245. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37246. * or just falling back on setUniformXXX calls.
  37247. */
  37248. get: function () {
  37249. return !this._noUBO;
  37250. },
  37251. enumerable: true,
  37252. configurable: true
  37253. });
  37254. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37255. /**
  37256. * Indicates if the WebGL underlying uniform buffer is in sync
  37257. * with the javascript cache data.
  37258. */
  37259. get: function () {
  37260. return !this._needSync;
  37261. },
  37262. enumerable: true,
  37263. configurable: true
  37264. });
  37265. /**
  37266. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37267. * Also, a dynamic UniformBuffer will disable cache verification and always
  37268. * update the underlying WebGL uniform buffer to the GPU.
  37269. * @returns if Dynamic, otherwise false
  37270. */
  37271. UniformBuffer.prototype.isDynamic = function () {
  37272. return this._dynamic !== undefined;
  37273. };
  37274. /**
  37275. * The data cache on JS side.
  37276. * @returns the underlying data as a float array
  37277. */
  37278. UniformBuffer.prototype.getData = function () {
  37279. return this._bufferData;
  37280. };
  37281. /**
  37282. * The underlying WebGL Uniform buffer.
  37283. * @returns the webgl buffer
  37284. */
  37285. UniformBuffer.prototype.getBuffer = function () {
  37286. return this._buffer;
  37287. };
  37288. /**
  37289. * std140 layout specifies how to align data within an UBO structure.
  37290. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37291. * for specs.
  37292. */
  37293. UniformBuffer.prototype._fillAlignment = function (size) {
  37294. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37295. // and 4x4 matrices
  37296. // TODO : change if other types are used
  37297. var alignment;
  37298. if (size <= 2) {
  37299. alignment = size;
  37300. }
  37301. else {
  37302. alignment = 4;
  37303. }
  37304. if ((this._uniformLocationPointer % alignment) !== 0) {
  37305. var oldPointer = this._uniformLocationPointer;
  37306. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37307. var diff = this._uniformLocationPointer - oldPointer;
  37308. for (var i = 0; i < diff; i++) {
  37309. this._data.push(0);
  37310. }
  37311. }
  37312. };
  37313. /**
  37314. * Adds an uniform in the buffer.
  37315. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37316. * for the layout to be correct !
  37317. * @param name Name of the uniform, as used in the uniform block in the shader.
  37318. * @param size Data size, or data directly.
  37319. */
  37320. UniformBuffer.prototype.addUniform = function (name, size) {
  37321. if (this._noUBO) {
  37322. return;
  37323. }
  37324. if (this._uniformLocations[name] !== undefined) {
  37325. // Already existing uniform
  37326. return;
  37327. }
  37328. // This function must be called in the order of the shader layout !
  37329. // size can be the size of the uniform, or data directly
  37330. var data;
  37331. if (size instanceof Array) {
  37332. data = size;
  37333. size = data.length;
  37334. }
  37335. else {
  37336. size = size;
  37337. data = [];
  37338. // Fill with zeros
  37339. for (var i = 0; i < size; i++) {
  37340. data.push(0);
  37341. }
  37342. }
  37343. this._fillAlignment(size);
  37344. this._uniformSizes[name] = size;
  37345. this._uniformLocations[name] = this._uniformLocationPointer;
  37346. this._uniformLocationPointer += size;
  37347. for (var i = 0; i < size; i++) {
  37348. this._data.push(data[i]);
  37349. }
  37350. this._needSync = true;
  37351. };
  37352. /**
  37353. * Adds a Matrix 4x4 to the uniform buffer.
  37354. * @param name Name of the uniform, as used in the uniform block in the shader.
  37355. * @param mat A 4x4 matrix.
  37356. */
  37357. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37358. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37359. };
  37360. /**
  37361. * Adds a vec2 to the uniform buffer.
  37362. * @param name Name of the uniform, as used in the uniform block in the shader.
  37363. * @param x Define the x component value of the vec2
  37364. * @param y Define the y component value of the vec2
  37365. */
  37366. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37367. var temp = [x, y];
  37368. this.addUniform(name, temp);
  37369. };
  37370. /**
  37371. * Adds a vec3 to the uniform buffer.
  37372. * @param name Name of the uniform, as used in the uniform block in the shader.
  37373. * @param x Define the x component value of the vec3
  37374. * @param y Define the y component value of the vec3
  37375. * @param z Define the z component value of the vec3
  37376. */
  37377. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37378. var temp = [x, y, z];
  37379. this.addUniform(name, temp);
  37380. };
  37381. /**
  37382. * Adds a vec3 to the uniform buffer.
  37383. * @param name Name of the uniform, as used in the uniform block in the shader.
  37384. * @param color Define the vec3 from a Color
  37385. */
  37386. UniformBuffer.prototype.addColor3 = function (name, color) {
  37387. var temp = new Array();
  37388. color.toArray(temp);
  37389. this.addUniform(name, temp);
  37390. };
  37391. /**
  37392. * Adds a vec4 to the uniform buffer.
  37393. * @param name Name of the uniform, as used in the uniform block in the shader.
  37394. * @param color Define the rgb components from a Color
  37395. * @param alpha Define the a component of the vec4
  37396. */
  37397. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37398. var temp = new Array();
  37399. color.toArray(temp);
  37400. temp.push(alpha);
  37401. this.addUniform(name, temp);
  37402. };
  37403. /**
  37404. * Adds a vec3 to the uniform buffer.
  37405. * @param name Name of the uniform, as used in the uniform block in the shader.
  37406. * @param vector Define the vec3 components from a Vector
  37407. */
  37408. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37409. var temp = new Array();
  37410. vector.toArray(temp);
  37411. this.addUniform(name, temp);
  37412. };
  37413. /**
  37414. * Adds a Matrix 3x3 to the uniform buffer.
  37415. * @param name Name of the uniform, as used in the uniform block in the shader.
  37416. */
  37417. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37418. this.addUniform(name, 12);
  37419. };
  37420. /**
  37421. * Adds a Matrix 2x2 to the uniform buffer.
  37422. * @param name Name of the uniform, as used in the uniform block in the shader.
  37423. */
  37424. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37425. this.addUniform(name, 8);
  37426. };
  37427. /**
  37428. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37429. */
  37430. UniformBuffer.prototype.create = function () {
  37431. if (this._noUBO) {
  37432. return;
  37433. }
  37434. if (this._buffer) {
  37435. return; // nothing to do
  37436. }
  37437. // See spec, alignment must be filled as a vec4
  37438. this._fillAlignment(4);
  37439. this._bufferData = new Float32Array(this._data);
  37440. this._rebuild();
  37441. this._needSync = true;
  37442. };
  37443. /** @hidden */
  37444. UniformBuffer.prototype._rebuild = function () {
  37445. if (this._noUBO) {
  37446. return;
  37447. }
  37448. if (this._dynamic) {
  37449. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37450. }
  37451. else {
  37452. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37453. }
  37454. };
  37455. /**
  37456. * Updates the WebGL Uniform Buffer on the GPU.
  37457. * If the `dynamic` flag is set to true, no cache comparison is done.
  37458. * Otherwise, the buffer will be updated only if the cache differs.
  37459. */
  37460. UniformBuffer.prototype.update = function () {
  37461. if (!this._buffer) {
  37462. this.create();
  37463. return;
  37464. }
  37465. if (!this._dynamic && !this._needSync) {
  37466. return;
  37467. }
  37468. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37469. this._needSync = false;
  37470. };
  37471. /**
  37472. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37473. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37474. * @param data Define the flattened data
  37475. * @param size Define the size of the data.
  37476. */
  37477. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37478. var location = this._uniformLocations[uniformName];
  37479. if (location === undefined) {
  37480. if (this._buffer) {
  37481. // Cannot add an uniform if the buffer is already created
  37482. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37483. return;
  37484. }
  37485. this.addUniform(uniformName, size);
  37486. location = this._uniformLocations[uniformName];
  37487. }
  37488. if (!this._buffer) {
  37489. this.create();
  37490. }
  37491. if (!this._dynamic) {
  37492. // Cache for static uniform buffers
  37493. var changed = false;
  37494. for (var i = 0; i < size; i++) {
  37495. if (this._bufferData[location + i] !== data[i]) {
  37496. changed = true;
  37497. this._bufferData[location + i] = data[i];
  37498. }
  37499. }
  37500. this._needSync = this._needSync || changed;
  37501. }
  37502. else {
  37503. // No cache for dynamic
  37504. for (var i = 0; i < size; i++) {
  37505. this._bufferData[location + i] = data[i];
  37506. }
  37507. }
  37508. };
  37509. // Update methods
  37510. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37511. // To match std140, matrix must be realigned
  37512. for (var i = 0; i < 3; i++) {
  37513. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37514. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37515. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37516. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37517. }
  37518. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37519. };
  37520. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37521. this._currentEffect.setMatrix3x3(name, matrix);
  37522. };
  37523. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37524. this._currentEffect.setMatrix2x2(name, matrix);
  37525. };
  37526. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37527. // To match std140, matrix must be realigned
  37528. for (var i = 0; i < 2; i++) {
  37529. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37530. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37531. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37532. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37533. }
  37534. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37535. };
  37536. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37537. this._currentEffect.setFloat(name, x);
  37538. };
  37539. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37540. UniformBuffer._tempBuffer[0] = x;
  37541. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37542. };
  37543. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37544. if (suffix === void 0) { suffix = ""; }
  37545. this._currentEffect.setFloat2(name + suffix, x, y);
  37546. };
  37547. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37548. if (suffix === void 0) { suffix = ""; }
  37549. UniformBuffer._tempBuffer[0] = x;
  37550. UniformBuffer._tempBuffer[1] = y;
  37551. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37552. };
  37553. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37554. if (suffix === void 0) { suffix = ""; }
  37555. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37556. };
  37557. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37558. if (suffix === void 0) { suffix = ""; }
  37559. UniformBuffer._tempBuffer[0] = x;
  37560. UniformBuffer._tempBuffer[1] = y;
  37561. UniformBuffer._tempBuffer[2] = z;
  37562. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37563. };
  37564. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37565. if (suffix === void 0) { suffix = ""; }
  37566. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37567. };
  37568. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37569. if (suffix === void 0) { suffix = ""; }
  37570. UniformBuffer._tempBuffer[0] = x;
  37571. UniformBuffer._tempBuffer[1] = y;
  37572. UniformBuffer._tempBuffer[2] = z;
  37573. UniformBuffer._tempBuffer[3] = w;
  37574. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37575. };
  37576. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37577. this._currentEffect.setMatrix(name, mat);
  37578. };
  37579. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37580. this.updateUniform(name, mat.toArray(), 16);
  37581. };
  37582. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37583. this._currentEffect.setVector3(name, vector);
  37584. };
  37585. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37586. vector.toArray(UniformBuffer._tempBuffer);
  37587. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37588. };
  37589. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37590. this._currentEffect.setVector4(name, vector);
  37591. };
  37592. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37593. vector.toArray(UniformBuffer._tempBuffer);
  37594. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37595. };
  37596. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37597. if (suffix === void 0) { suffix = ""; }
  37598. this._currentEffect.setColor3(name + suffix, color);
  37599. };
  37600. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37601. if (suffix === void 0) { suffix = ""; }
  37602. color.toArray(UniformBuffer._tempBuffer);
  37603. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37604. };
  37605. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37606. if (suffix === void 0) { suffix = ""; }
  37607. this._currentEffect.setColor4(name + suffix, color, alpha);
  37608. };
  37609. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37610. if (suffix === void 0) { suffix = ""; }
  37611. color.toArray(UniformBuffer._tempBuffer);
  37612. UniformBuffer._tempBuffer[3] = alpha;
  37613. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37614. };
  37615. /**
  37616. * Sets a sampler uniform on the effect.
  37617. * @param name Define the name of the sampler.
  37618. * @param texture Define the texture to set in the sampler
  37619. */
  37620. UniformBuffer.prototype.setTexture = function (name, texture) {
  37621. this._currentEffect.setTexture(name, texture);
  37622. };
  37623. /**
  37624. * Directly updates the value of the uniform in the cache AND on the GPU.
  37625. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37626. * @param data Define the flattened data
  37627. */
  37628. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37629. this.updateUniform(uniformName, data, data.length);
  37630. this.update();
  37631. };
  37632. /**
  37633. * Binds this uniform buffer to an effect.
  37634. * @param effect Define the effect to bind the buffer to
  37635. * @param name Name of the uniform block in the shader.
  37636. */
  37637. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37638. this._currentEffect = effect;
  37639. if (this._noUBO || !this._buffer) {
  37640. return;
  37641. }
  37642. effect.bindUniformBuffer(this._buffer, name);
  37643. };
  37644. /**
  37645. * Disposes the uniform buffer.
  37646. */
  37647. UniformBuffer.prototype.dispose = function () {
  37648. if (this._noUBO) {
  37649. return;
  37650. }
  37651. var index = this._engine._uniformBuffers.indexOf(this);
  37652. if (index !== -1) {
  37653. this._engine._uniformBuffers.splice(index, 1);
  37654. }
  37655. if (!this._buffer) {
  37656. return;
  37657. }
  37658. if (this._engine._releaseBuffer(this._buffer)) {
  37659. this._buffer = null;
  37660. }
  37661. };
  37662. // Pool for avoiding memory leaks
  37663. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37664. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37665. return UniformBuffer;
  37666. }());
  37667. BABYLON.UniformBuffer = UniformBuffer;
  37668. })(BABYLON || (BABYLON = {}));
  37669. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37670. var BABYLON;
  37671. (function (BABYLON) {
  37672. /**
  37673. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37674. */
  37675. var VertexData = /** @class */ (function () {
  37676. function VertexData() {
  37677. }
  37678. /**
  37679. * Uses the passed data array to set the set the values for the specified kind of data
  37680. * @param data a linear array of floating numbers
  37681. * @param kind the type of data that is being set, eg positions, colors etc
  37682. */
  37683. VertexData.prototype.set = function (data, kind) {
  37684. switch (kind) {
  37685. case BABYLON.VertexBuffer.PositionKind:
  37686. this.positions = data;
  37687. break;
  37688. case BABYLON.VertexBuffer.NormalKind:
  37689. this.normals = data;
  37690. break;
  37691. case BABYLON.VertexBuffer.TangentKind:
  37692. this.tangents = data;
  37693. break;
  37694. case BABYLON.VertexBuffer.UVKind:
  37695. this.uvs = data;
  37696. break;
  37697. case BABYLON.VertexBuffer.UV2Kind:
  37698. this.uvs2 = data;
  37699. break;
  37700. case BABYLON.VertexBuffer.UV3Kind:
  37701. this.uvs3 = data;
  37702. break;
  37703. case BABYLON.VertexBuffer.UV4Kind:
  37704. this.uvs4 = data;
  37705. break;
  37706. case BABYLON.VertexBuffer.UV5Kind:
  37707. this.uvs5 = data;
  37708. break;
  37709. case BABYLON.VertexBuffer.UV6Kind:
  37710. this.uvs6 = data;
  37711. break;
  37712. case BABYLON.VertexBuffer.ColorKind:
  37713. this.colors = data;
  37714. break;
  37715. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37716. this.matricesIndices = data;
  37717. break;
  37718. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37719. this.matricesWeights = data;
  37720. break;
  37721. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37722. this.matricesIndicesExtra = data;
  37723. break;
  37724. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37725. this.matricesWeightsExtra = data;
  37726. break;
  37727. }
  37728. };
  37729. /**
  37730. * Associates the vertexData to the passed Mesh.
  37731. * Sets it as updatable or not (default `false`)
  37732. * @param mesh the mesh the vertexData is applied to
  37733. * @param updatable when used and having the value true allows new data to update the vertexData
  37734. * @returns the VertexData
  37735. */
  37736. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37737. this._applyTo(mesh, updatable);
  37738. return this;
  37739. };
  37740. /**
  37741. * Associates the vertexData to the passed Geometry.
  37742. * Sets it as updatable or not (default `false`)
  37743. * @param geometry the geometry the vertexData is applied to
  37744. * @param updatable when used and having the value true allows new data to update the vertexData
  37745. * @returns VertexData
  37746. */
  37747. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37748. this._applyTo(geometry, updatable);
  37749. return this;
  37750. };
  37751. /**
  37752. * Updates the associated mesh
  37753. * @param mesh the mesh to be updated
  37754. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37755. * @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
  37756. * @returns VertexData
  37757. */
  37758. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37759. this._update(mesh);
  37760. return this;
  37761. };
  37762. /**
  37763. * Updates the associated geometry
  37764. * @param geometry the geometry to be updated
  37765. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37766. * @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
  37767. * @returns VertexData.
  37768. */
  37769. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37770. this._update(geometry);
  37771. return this;
  37772. };
  37773. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37774. if (updatable === void 0) { updatable = false; }
  37775. if (this.positions) {
  37776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37777. }
  37778. if (this.normals) {
  37779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37780. }
  37781. if (this.tangents) {
  37782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37783. }
  37784. if (this.uvs) {
  37785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37786. }
  37787. if (this.uvs2) {
  37788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37789. }
  37790. if (this.uvs3) {
  37791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37792. }
  37793. if (this.uvs4) {
  37794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37795. }
  37796. if (this.uvs5) {
  37797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37798. }
  37799. if (this.uvs6) {
  37800. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37801. }
  37802. if (this.colors) {
  37803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37804. }
  37805. if (this.matricesIndices) {
  37806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37807. }
  37808. if (this.matricesWeights) {
  37809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37810. }
  37811. if (this.matricesIndicesExtra) {
  37812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37813. }
  37814. if (this.matricesWeightsExtra) {
  37815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37816. }
  37817. if (this.indices) {
  37818. meshOrGeometry.setIndices(this.indices, null, updatable);
  37819. }
  37820. else {
  37821. meshOrGeometry.setIndices([], null);
  37822. }
  37823. return this;
  37824. };
  37825. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37826. if (this.positions) {
  37827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37828. }
  37829. if (this.normals) {
  37830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37831. }
  37832. if (this.tangents) {
  37833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37834. }
  37835. if (this.uvs) {
  37836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37837. }
  37838. if (this.uvs2) {
  37839. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37840. }
  37841. if (this.uvs3) {
  37842. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37843. }
  37844. if (this.uvs4) {
  37845. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37846. }
  37847. if (this.uvs5) {
  37848. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37849. }
  37850. if (this.uvs6) {
  37851. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37852. }
  37853. if (this.colors) {
  37854. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37855. }
  37856. if (this.matricesIndices) {
  37857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37858. }
  37859. if (this.matricesWeights) {
  37860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37861. }
  37862. if (this.matricesIndicesExtra) {
  37863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37864. }
  37865. if (this.matricesWeightsExtra) {
  37866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37867. }
  37868. if (this.indices) {
  37869. meshOrGeometry.setIndices(this.indices, null);
  37870. }
  37871. return this;
  37872. };
  37873. /**
  37874. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37875. * @param matrix the transforming matrix
  37876. * @returns the VertexData
  37877. */
  37878. VertexData.prototype.transform = function (matrix) {
  37879. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37880. var transformed = BABYLON.Vector3.Zero();
  37881. var index;
  37882. if (this.positions) {
  37883. var position = BABYLON.Vector3.Zero();
  37884. for (index = 0; index < this.positions.length; index += 3) {
  37885. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37886. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37887. this.positions[index] = transformed.x;
  37888. this.positions[index + 1] = transformed.y;
  37889. this.positions[index + 2] = transformed.z;
  37890. }
  37891. }
  37892. if (this.normals) {
  37893. var normal = BABYLON.Vector3.Zero();
  37894. for (index = 0; index < this.normals.length; index += 3) {
  37895. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37896. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37897. this.normals[index] = transformed.x;
  37898. this.normals[index + 1] = transformed.y;
  37899. this.normals[index + 2] = transformed.z;
  37900. }
  37901. }
  37902. if (this.tangents) {
  37903. var tangent = BABYLON.Vector4.Zero();
  37904. var tangentTransformed = BABYLON.Vector4.Zero();
  37905. for (index = 0; index < this.tangents.length; index += 4) {
  37906. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37907. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37908. this.tangents[index] = tangentTransformed.x;
  37909. this.tangents[index + 1] = tangentTransformed.y;
  37910. this.tangents[index + 2] = tangentTransformed.z;
  37911. this.tangents[index + 3] = tangentTransformed.w;
  37912. }
  37913. }
  37914. if (flip && this.indices) {
  37915. for (index = 0; index < this.indices.length; index += 3) {
  37916. var tmp = this.indices[index + 1];
  37917. this.indices[index + 1] = this.indices[index + 2];
  37918. this.indices[index + 2] = tmp;
  37919. }
  37920. }
  37921. return this;
  37922. };
  37923. /**
  37924. * Merges the passed VertexData into the current one
  37925. * @param other the VertexData to be merged into the current one
  37926. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37927. * @returns the modified VertexData
  37928. */
  37929. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37930. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37931. this._validate();
  37932. other._validate();
  37933. if (!this.normals !== !other.normals ||
  37934. !this.tangents !== !other.tangents ||
  37935. !this.uvs !== !other.uvs ||
  37936. !this.uvs2 !== !other.uvs2 ||
  37937. !this.uvs3 !== !other.uvs3 ||
  37938. !this.uvs4 !== !other.uvs4 ||
  37939. !this.uvs5 !== !other.uvs5 ||
  37940. !this.uvs6 !== !other.uvs6 ||
  37941. !this.colors !== !other.colors ||
  37942. !this.matricesIndices !== !other.matricesIndices ||
  37943. !this.matricesWeights !== !other.matricesWeights ||
  37944. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37945. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37946. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37947. }
  37948. if (other.indices) {
  37949. if (!this.indices) {
  37950. this.indices = [];
  37951. }
  37952. var offset = this.positions ? this.positions.length / 3 : 0;
  37953. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37954. if (isSrcTypedArray) {
  37955. var len = this.indices.length + other.indices.length;
  37956. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37957. temp.set(this.indices);
  37958. var decal = this.indices.length;
  37959. for (var index = 0; index < other.indices.length; index++) {
  37960. temp[decal + index] = other.indices[index] + offset;
  37961. }
  37962. this.indices = temp;
  37963. }
  37964. else {
  37965. for (var index = 0; index < other.indices.length; index++) {
  37966. this.indices.push(other.indices[index] + offset);
  37967. }
  37968. }
  37969. }
  37970. this.positions = this._mergeElement(this.positions, other.positions);
  37971. this.normals = this._mergeElement(this.normals, other.normals);
  37972. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37973. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37974. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37975. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37976. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37977. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37978. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37979. this.colors = this._mergeElement(this.colors, other.colors);
  37980. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37981. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37982. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37983. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37984. return this;
  37985. };
  37986. VertexData.prototype._mergeElement = function (source, other) {
  37987. if (!source) {
  37988. return other;
  37989. }
  37990. if (!other) {
  37991. return source;
  37992. }
  37993. var len = other.length + source.length;
  37994. var isSrcTypedArray = source instanceof Float32Array;
  37995. var isOthTypedArray = other instanceof Float32Array;
  37996. // use non-loop method when the source is Float32Array
  37997. if (isSrcTypedArray) {
  37998. var ret32 = new Float32Array(len);
  37999. ret32.set(source);
  38000. ret32.set(other, source.length);
  38001. return ret32;
  38002. // source is number[], when other is also use concat
  38003. }
  38004. else if (!isOthTypedArray) {
  38005. return source.concat(other);
  38006. // source is a number[], but other is a Float32Array, loop required
  38007. }
  38008. else {
  38009. var ret = source.slice(0); // copy source to a separate array
  38010. for (var i = 0, len = other.length; i < len; i++) {
  38011. ret.push(other[i]);
  38012. }
  38013. return ret;
  38014. }
  38015. };
  38016. VertexData.prototype._validate = function () {
  38017. if (!this.positions) {
  38018. throw new Error("Positions are required");
  38019. }
  38020. var getElementCount = function (kind, values) {
  38021. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38022. if ((values.length % stride) !== 0) {
  38023. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38024. }
  38025. return values.length / stride;
  38026. };
  38027. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38028. var validateElementCount = function (kind, values) {
  38029. var elementCount = getElementCount(kind, values);
  38030. if (elementCount !== positionsElementCount) {
  38031. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38032. }
  38033. };
  38034. if (this.normals) {
  38035. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38036. }
  38037. if (this.tangents) {
  38038. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38039. }
  38040. if (this.uvs) {
  38041. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38042. }
  38043. if (this.uvs2) {
  38044. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38045. }
  38046. if (this.uvs3) {
  38047. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38048. }
  38049. if (this.uvs4) {
  38050. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38051. }
  38052. if (this.uvs5) {
  38053. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38054. }
  38055. if (this.uvs6) {
  38056. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38057. }
  38058. if (this.colors) {
  38059. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38060. }
  38061. if (this.matricesIndices) {
  38062. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38063. }
  38064. if (this.matricesWeights) {
  38065. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38066. }
  38067. if (this.matricesIndicesExtra) {
  38068. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38069. }
  38070. if (this.matricesWeightsExtra) {
  38071. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38072. }
  38073. };
  38074. /**
  38075. * Serializes the VertexData
  38076. * @returns a serialized object
  38077. */
  38078. VertexData.prototype.serialize = function () {
  38079. var serializationObject = this.serialize();
  38080. if (this.positions) {
  38081. serializationObject.positions = this.positions;
  38082. }
  38083. if (this.normals) {
  38084. serializationObject.normals = this.normals;
  38085. }
  38086. if (this.tangents) {
  38087. serializationObject.tangents = this.tangents;
  38088. }
  38089. if (this.uvs) {
  38090. serializationObject.uvs = this.uvs;
  38091. }
  38092. if (this.uvs2) {
  38093. serializationObject.uvs2 = this.uvs2;
  38094. }
  38095. if (this.uvs3) {
  38096. serializationObject.uvs3 = this.uvs3;
  38097. }
  38098. if (this.uvs4) {
  38099. serializationObject.uvs4 = this.uvs4;
  38100. }
  38101. if (this.uvs5) {
  38102. serializationObject.uvs5 = this.uvs5;
  38103. }
  38104. if (this.uvs6) {
  38105. serializationObject.uvs6 = this.uvs6;
  38106. }
  38107. if (this.colors) {
  38108. serializationObject.colors = this.colors;
  38109. }
  38110. if (this.matricesIndices) {
  38111. serializationObject.matricesIndices = this.matricesIndices;
  38112. serializationObject.matricesIndices._isExpanded = true;
  38113. }
  38114. if (this.matricesWeights) {
  38115. serializationObject.matricesWeights = this.matricesWeights;
  38116. }
  38117. if (this.matricesIndicesExtra) {
  38118. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38119. serializationObject.matricesIndicesExtra._isExpanded = true;
  38120. }
  38121. if (this.matricesWeightsExtra) {
  38122. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38123. }
  38124. serializationObject.indices = this.indices;
  38125. return serializationObject;
  38126. };
  38127. // Statics
  38128. /**
  38129. * Extracts the vertexData from a mesh
  38130. * @param mesh the mesh from which to extract the VertexData
  38131. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38132. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38133. * @returns the object VertexData associated to the passed mesh
  38134. */
  38135. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38136. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38137. };
  38138. /**
  38139. * Extracts the vertexData from the geometry
  38140. * @param geometry the geometry from which to extract the VertexData
  38141. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38142. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38143. * @returns the object VertexData associated to the passed mesh
  38144. */
  38145. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38146. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38147. };
  38148. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38149. var result = new VertexData();
  38150. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38151. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38152. }
  38153. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38154. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38155. }
  38156. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38157. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38158. }
  38159. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38160. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38161. }
  38162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38163. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38164. }
  38165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38166. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38167. }
  38168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38169. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38170. }
  38171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38172. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38173. }
  38174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38175. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38176. }
  38177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38178. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38179. }
  38180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38181. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38182. }
  38183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38184. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38185. }
  38186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38187. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38188. }
  38189. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38190. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38191. }
  38192. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38193. return result;
  38194. };
  38195. /**
  38196. * Creates the VertexData for a Ribbon
  38197. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38198. * * pathArray array of paths, each of which an array of successive Vector3
  38199. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38200. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38201. * * 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
  38202. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38203. * * 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)
  38204. * * 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)
  38205. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38206. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38207. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38208. * @returns the VertexData of the ribbon
  38209. */
  38210. VertexData.CreateRibbon = function (options) {
  38211. var pathArray = options.pathArray;
  38212. var closeArray = options.closeArray || false;
  38213. var closePath = options.closePath || false;
  38214. var invertUV = options.invertUV || false;
  38215. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38216. var offset = options.offset || defaultOffset;
  38217. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38218. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38219. var customUV = options.uvs;
  38220. var customColors = options.colors;
  38221. var positions = [];
  38222. var indices = [];
  38223. var normals = [];
  38224. var uvs = [];
  38225. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38226. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38227. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38228. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38229. var minlg; // minimal length among all paths from pathArray
  38230. var lg = []; // array of path lengths : nb of vertex per path
  38231. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38232. var p; // path iterator
  38233. var i; // point iterator
  38234. var j; // point iterator
  38235. // if single path in pathArray
  38236. if (pathArray.length < 2) {
  38237. var ar1 = [];
  38238. var ar2 = [];
  38239. for (i = 0; i < pathArray[0].length - offset; i++) {
  38240. ar1.push(pathArray[0][i]);
  38241. ar2.push(pathArray[0][i + offset]);
  38242. }
  38243. pathArray = [ar1, ar2];
  38244. }
  38245. // positions and horizontal distances (u)
  38246. var idc = 0;
  38247. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38248. var path;
  38249. var l;
  38250. minlg = pathArray[0].length;
  38251. var vectlg;
  38252. var dist;
  38253. for (p = 0; p < pathArray.length; p++) {
  38254. uTotalDistance[p] = 0;
  38255. us[p] = [0];
  38256. path = pathArray[p];
  38257. l = path.length;
  38258. minlg = (minlg < l) ? minlg : l;
  38259. j = 0;
  38260. while (j < l) {
  38261. positions.push(path[j].x, path[j].y, path[j].z);
  38262. if (j > 0) {
  38263. vectlg = path[j].subtract(path[j - 1]).length();
  38264. dist = vectlg + uTotalDistance[p];
  38265. us[p].push(dist);
  38266. uTotalDistance[p] = dist;
  38267. }
  38268. j++;
  38269. }
  38270. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38271. j--;
  38272. positions.push(path[0].x, path[0].y, path[0].z);
  38273. vectlg = path[j].subtract(path[0]).length();
  38274. dist = vectlg + uTotalDistance[p];
  38275. us[p].push(dist);
  38276. uTotalDistance[p] = dist;
  38277. }
  38278. lg[p] = l + closePathCorr;
  38279. idx[p] = idc;
  38280. idc += (l + closePathCorr);
  38281. }
  38282. // vertical distances (v)
  38283. var path1;
  38284. var path2;
  38285. var vertex1 = null;
  38286. var vertex2 = null;
  38287. for (i = 0; i < minlg + closePathCorr; i++) {
  38288. vTotalDistance[i] = 0;
  38289. vs[i] = [0];
  38290. for (p = 0; p < pathArray.length - 1; p++) {
  38291. path1 = pathArray[p];
  38292. path2 = pathArray[p + 1];
  38293. if (i === minlg) { // closePath
  38294. vertex1 = path1[0];
  38295. vertex2 = path2[0];
  38296. }
  38297. else {
  38298. vertex1 = path1[i];
  38299. vertex2 = path2[i];
  38300. }
  38301. vectlg = vertex2.subtract(vertex1).length();
  38302. dist = vectlg + vTotalDistance[i];
  38303. vs[i].push(dist);
  38304. vTotalDistance[i] = dist;
  38305. }
  38306. if (closeArray && vertex2 && vertex1) {
  38307. path1 = pathArray[p];
  38308. path2 = pathArray[0];
  38309. if (i === minlg) { // closePath
  38310. vertex2 = path2[0];
  38311. }
  38312. vectlg = vertex2.subtract(vertex1).length();
  38313. dist = vectlg + vTotalDistance[i];
  38314. vTotalDistance[i] = dist;
  38315. }
  38316. }
  38317. // uvs
  38318. var u;
  38319. var v;
  38320. if (customUV) {
  38321. for (p = 0; p < customUV.length; p++) {
  38322. uvs.push(customUV[p].x, customUV[p].y);
  38323. }
  38324. }
  38325. else {
  38326. for (p = 0; p < pathArray.length; p++) {
  38327. for (i = 0; i < minlg + closePathCorr; i++) {
  38328. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38329. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38330. if (invertUV) {
  38331. uvs.push(v, u);
  38332. }
  38333. else {
  38334. uvs.push(u, v);
  38335. }
  38336. }
  38337. }
  38338. }
  38339. // indices
  38340. p = 0; // path index
  38341. var pi = 0; // positions array index
  38342. var l1 = lg[p] - 1; // path1 length
  38343. var l2 = lg[p + 1] - 1; // path2 length
  38344. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38345. var shft = idx[1] - idx[0]; // shift
  38346. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38347. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38348. // 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
  38349. indices.push(pi, pi + shft, pi + 1);
  38350. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38351. pi += 1;
  38352. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38353. p++;
  38354. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38355. shft = idx[0] - idx[p];
  38356. l1 = lg[p] - 1;
  38357. l2 = lg[0] - 1;
  38358. }
  38359. else {
  38360. shft = idx[p + 1] - idx[p];
  38361. l1 = lg[p] - 1;
  38362. l2 = lg[p + 1] - 1;
  38363. }
  38364. pi = idx[p];
  38365. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38366. }
  38367. }
  38368. // normals
  38369. VertexData.ComputeNormals(positions, indices, normals);
  38370. if (closePath) { // update both the first and last vertex normals to their average value
  38371. var indexFirst = 0;
  38372. var indexLast = 0;
  38373. for (p = 0; p < pathArray.length; p++) {
  38374. indexFirst = idx[p] * 3;
  38375. if (p + 1 < pathArray.length) {
  38376. indexLast = (idx[p + 1] - 1) * 3;
  38377. }
  38378. else {
  38379. indexLast = normals.length - 3;
  38380. }
  38381. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38382. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38383. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38384. normals[indexLast] = normals[indexFirst];
  38385. normals[indexLast + 1] = normals[indexFirst + 1];
  38386. normals[indexLast + 2] = normals[indexFirst + 2];
  38387. }
  38388. }
  38389. // sides
  38390. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38391. // Colors
  38392. var colors = null;
  38393. if (customColors) {
  38394. colors = new Float32Array(customColors.length * 4);
  38395. for (var c = 0; c < customColors.length; c++) {
  38396. colors[c * 4] = customColors[c].r;
  38397. colors[c * 4 + 1] = customColors[c].g;
  38398. colors[c * 4 + 2] = customColors[c].b;
  38399. colors[c * 4 + 3] = customColors[c].a;
  38400. }
  38401. }
  38402. // Result
  38403. var vertexData = new VertexData();
  38404. var positions32 = new Float32Array(positions);
  38405. var normals32 = new Float32Array(normals);
  38406. var uvs32 = new Float32Array(uvs);
  38407. vertexData.indices = indices;
  38408. vertexData.positions = positions32;
  38409. vertexData.normals = normals32;
  38410. vertexData.uvs = uvs32;
  38411. if (colors) {
  38412. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38413. }
  38414. if (closePath) {
  38415. vertexData._idx = idx;
  38416. }
  38417. return vertexData;
  38418. };
  38419. /**
  38420. * Creates the VertexData for a box
  38421. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38422. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38423. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38424. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38425. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38426. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38427. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38428. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38429. * * 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)
  38430. * * 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)
  38431. * @returns the VertexData of the box
  38432. */
  38433. VertexData.CreateBox = function (options) {
  38434. var normalsSource = [
  38435. new BABYLON.Vector3(0, 0, 1),
  38436. new BABYLON.Vector3(0, 0, -1),
  38437. new BABYLON.Vector3(1, 0, 0),
  38438. new BABYLON.Vector3(-1, 0, 0),
  38439. new BABYLON.Vector3(0, 1, 0),
  38440. new BABYLON.Vector3(0, -1, 0)
  38441. ];
  38442. var indices = [];
  38443. var positions = [];
  38444. var normals = [];
  38445. var uvs = [];
  38446. var width = options.width || options.size || 1;
  38447. var height = options.height || options.size || 1;
  38448. var depth = options.depth || options.size || 1;
  38449. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38450. var faceUV = options.faceUV || new Array(6);
  38451. var faceColors = options.faceColors;
  38452. var colors = [];
  38453. // default face colors and UV if undefined
  38454. for (var f = 0; f < 6; f++) {
  38455. if (faceUV[f] === undefined) {
  38456. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38457. }
  38458. if (faceColors && faceColors[f] === undefined) {
  38459. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38460. }
  38461. }
  38462. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38463. // Create each face in turn.
  38464. for (var index = 0; index < normalsSource.length; index++) {
  38465. var normal = normalsSource[index];
  38466. // Get two vectors perpendicular to the face normal and to each other.
  38467. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38468. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38469. // Six indices (two triangles) per face.
  38470. var verticesLength = positions.length / 3;
  38471. indices.push(verticesLength);
  38472. indices.push(verticesLength + 1);
  38473. indices.push(verticesLength + 2);
  38474. indices.push(verticesLength);
  38475. indices.push(verticesLength + 2);
  38476. indices.push(verticesLength + 3);
  38477. // Four vertices per face.
  38478. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38479. positions.push(vertex.x, vertex.y, vertex.z);
  38480. normals.push(normal.x, normal.y, normal.z);
  38481. uvs.push(faceUV[index].z, faceUV[index].w);
  38482. if (faceColors) {
  38483. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38484. }
  38485. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38486. positions.push(vertex.x, vertex.y, vertex.z);
  38487. normals.push(normal.x, normal.y, normal.z);
  38488. uvs.push(faceUV[index].x, faceUV[index].w);
  38489. if (faceColors) {
  38490. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38491. }
  38492. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38493. positions.push(vertex.x, vertex.y, vertex.z);
  38494. normals.push(normal.x, normal.y, normal.z);
  38495. uvs.push(faceUV[index].x, faceUV[index].y);
  38496. if (faceColors) {
  38497. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38498. }
  38499. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38500. positions.push(vertex.x, vertex.y, vertex.z);
  38501. normals.push(normal.x, normal.y, normal.z);
  38502. uvs.push(faceUV[index].z, faceUV[index].y);
  38503. if (faceColors) {
  38504. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38505. }
  38506. }
  38507. // sides
  38508. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38509. // Result
  38510. var vertexData = new VertexData();
  38511. vertexData.indices = indices;
  38512. vertexData.positions = positions;
  38513. vertexData.normals = normals;
  38514. vertexData.uvs = uvs;
  38515. if (faceColors) {
  38516. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38517. vertexData.colors = totalColors;
  38518. }
  38519. return vertexData;
  38520. };
  38521. /**
  38522. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38523. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38524. * * segments sets the number of horizontal strips optional, default 32
  38525. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38526. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38527. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38528. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38529. * * 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
  38530. * * 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
  38531. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38532. * * 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)
  38533. * * 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)
  38534. * @returns the VertexData of the ellipsoid
  38535. */
  38536. VertexData.CreateSphere = function (options) {
  38537. var segments = options.segments || 32;
  38538. var diameterX = options.diameterX || options.diameter || 1;
  38539. var diameterY = options.diameterY || options.diameter || 1;
  38540. var diameterZ = options.diameterZ || options.diameter || 1;
  38541. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38542. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38543. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38544. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38545. var totalZRotationSteps = 2 + segments;
  38546. var totalYRotationSteps = 2 * totalZRotationSteps;
  38547. var indices = [];
  38548. var positions = [];
  38549. var normals = [];
  38550. var uvs = [];
  38551. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38552. var normalizedZ = zRotationStep / totalZRotationSteps;
  38553. var angleZ = normalizedZ * Math.PI * slice;
  38554. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38555. var normalizedY = yRotationStep / totalYRotationSteps;
  38556. var angleY = normalizedY * Math.PI * 2 * arc;
  38557. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38558. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38559. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38560. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38561. var vertex = complete.multiply(radius);
  38562. var normal = complete.divide(radius).normalize();
  38563. positions.push(vertex.x, vertex.y, vertex.z);
  38564. normals.push(normal.x, normal.y, normal.z);
  38565. uvs.push(normalizedY, normalizedZ);
  38566. }
  38567. if (zRotationStep > 0) {
  38568. var verticesCount = positions.length / 3;
  38569. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38570. indices.push((firstIndex));
  38571. indices.push((firstIndex + 1));
  38572. indices.push(firstIndex + totalYRotationSteps + 1);
  38573. indices.push((firstIndex + totalYRotationSteps + 1));
  38574. indices.push((firstIndex + 1));
  38575. indices.push((firstIndex + totalYRotationSteps + 2));
  38576. }
  38577. }
  38578. }
  38579. // Sides
  38580. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38581. // Result
  38582. var vertexData = new VertexData();
  38583. vertexData.indices = indices;
  38584. vertexData.positions = positions;
  38585. vertexData.normals = normals;
  38586. vertexData.uvs = uvs;
  38587. return vertexData;
  38588. };
  38589. /**
  38590. * Creates the VertexData for a cylinder, cone or prism
  38591. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38592. * * height sets the height (y direction) of the cylinder, optional, default 2
  38593. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38594. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38595. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38596. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38597. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38598. * * 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
  38599. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38600. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38601. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38602. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38603. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38604. * * 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)
  38605. * * 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)
  38606. * @returns the VertexData of the cylinder, cone or prism
  38607. */
  38608. VertexData.CreateCylinder = function (options) {
  38609. var height = options.height || 2;
  38610. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38611. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38612. var tessellation = options.tessellation || 24;
  38613. var subdivisions = options.subdivisions || 1;
  38614. var hasRings = options.hasRings ? true : false;
  38615. var enclose = options.enclose ? true : false;
  38616. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38617. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38618. var faceUV = options.faceUV || new Array(3);
  38619. var faceColors = options.faceColors;
  38620. // default face colors and UV if undefined
  38621. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38622. var ringNb = (hasRings) ? subdivisions : 1;
  38623. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38624. var f;
  38625. for (f = 0; f < surfaceNb; f++) {
  38626. if (faceColors && faceColors[f] === undefined) {
  38627. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38628. }
  38629. }
  38630. for (f = 0; f < surfaceNb; f++) {
  38631. if (faceUV && faceUV[f] === undefined) {
  38632. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38633. }
  38634. }
  38635. var indices = new Array();
  38636. var positions = new Array();
  38637. var normals = new Array();
  38638. var uvs = new Array();
  38639. var colors = new Array();
  38640. var angle_step = Math.PI * 2 * arc / tessellation;
  38641. var angle;
  38642. var h;
  38643. var radius;
  38644. var tan = (diameterBottom - diameterTop) / 2 / height;
  38645. var ringVertex = BABYLON.Vector3.Zero();
  38646. var ringNormal = BABYLON.Vector3.Zero();
  38647. var ringFirstVertex = BABYLON.Vector3.Zero();
  38648. var ringFirstNormal = BABYLON.Vector3.Zero();
  38649. var quadNormal = BABYLON.Vector3.Zero();
  38650. var Y = BABYLON.Axis.Y;
  38651. // positions, normals, uvs
  38652. var i;
  38653. var j;
  38654. var r;
  38655. var ringIdx = 1;
  38656. var s = 1; // surface index
  38657. var cs = 0;
  38658. var v = 0;
  38659. for (i = 0; i <= subdivisions; i++) {
  38660. h = i / subdivisions;
  38661. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38662. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38663. for (r = 0; r < ringIdx; r++) {
  38664. if (hasRings) {
  38665. s += r;
  38666. }
  38667. if (enclose) {
  38668. s += 2 * r;
  38669. }
  38670. for (j = 0; j <= tessellation; j++) {
  38671. angle = j * angle_step;
  38672. // position
  38673. ringVertex.x = Math.cos(-angle) * radius;
  38674. ringVertex.y = -height / 2 + h * height;
  38675. ringVertex.z = Math.sin(-angle) * radius;
  38676. // normal
  38677. if (diameterTop === 0 && i === subdivisions) {
  38678. // if no top cap, reuse former normals
  38679. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38680. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38681. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38682. }
  38683. else {
  38684. ringNormal.x = ringVertex.x;
  38685. ringNormal.z = ringVertex.z;
  38686. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38687. ringNormal.normalize();
  38688. }
  38689. // keep first ring vertex values for enclose
  38690. if (j === 0) {
  38691. ringFirstVertex.copyFrom(ringVertex);
  38692. ringFirstNormal.copyFrom(ringNormal);
  38693. }
  38694. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38695. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38696. if (hasRings) {
  38697. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38698. }
  38699. else {
  38700. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38701. }
  38702. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38703. if (faceColors) {
  38704. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38705. }
  38706. }
  38707. // if enclose, add four vertices and their dedicated normals
  38708. if (arc !== 1 && enclose) {
  38709. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38710. positions.push(0, ringVertex.y, 0);
  38711. positions.push(0, ringVertex.y, 0);
  38712. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38713. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38714. quadNormal.normalize();
  38715. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38716. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38717. quadNormal.normalize();
  38718. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38719. if (hasRings) {
  38720. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38721. }
  38722. else {
  38723. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38724. }
  38725. uvs.push(faceUV[s + 1].x, v);
  38726. uvs.push(faceUV[s + 1].z, v);
  38727. if (hasRings) {
  38728. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38729. }
  38730. else {
  38731. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38732. }
  38733. uvs.push(faceUV[s + 2].x, v);
  38734. uvs.push(faceUV[s + 2].z, v);
  38735. if (faceColors) {
  38736. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38737. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38738. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38739. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38740. }
  38741. }
  38742. if (cs !== s) {
  38743. cs = s;
  38744. }
  38745. }
  38746. }
  38747. // indices
  38748. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38749. var s;
  38750. i = 0;
  38751. for (s = 0; s < subdivisions; s++) {
  38752. var i0 = 0;
  38753. var i1 = 0;
  38754. var i2 = 0;
  38755. var i3 = 0;
  38756. for (j = 0; j < tessellation; j++) {
  38757. i0 = i * (e + 1) + j;
  38758. i1 = (i + 1) * (e + 1) + j;
  38759. i2 = i * (e + 1) + (j + 1);
  38760. i3 = (i + 1) * (e + 1) + (j + 1);
  38761. indices.push(i0, i1, i2);
  38762. indices.push(i3, i2, i1);
  38763. }
  38764. if (arc !== 1 && enclose) { // if enclose, add two quads
  38765. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38766. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38767. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38768. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38769. }
  38770. i = (hasRings) ? (i + 2) : (i + 1);
  38771. }
  38772. // Caps
  38773. var createCylinderCap = function (isTop) {
  38774. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38775. if (radius === 0) {
  38776. return;
  38777. }
  38778. // Cap positions, normals & uvs
  38779. var angle;
  38780. var circleVector;
  38781. var i;
  38782. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38783. var c = null;
  38784. if (faceColors) {
  38785. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38786. }
  38787. // cap center
  38788. var vbase = positions.length / 3;
  38789. var offset = isTop ? height / 2 : -height / 2;
  38790. var center = new BABYLON.Vector3(0, offset, 0);
  38791. positions.push(center.x, center.y, center.z);
  38792. normals.push(0, isTop ? 1 : -1, 0);
  38793. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38794. if (c) {
  38795. colors.push(c.r, c.g, c.b, c.a);
  38796. }
  38797. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38798. for (i = 0; i <= tessellation; i++) {
  38799. angle = Math.PI * 2 * i * arc / tessellation;
  38800. var cos = Math.cos(-angle);
  38801. var sin = Math.sin(-angle);
  38802. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38803. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38804. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38805. normals.push(0, isTop ? 1 : -1, 0);
  38806. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38807. if (c) {
  38808. colors.push(c.r, c.g, c.b, c.a);
  38809. }
  38810. }
  38811. // Cap indices
  38812. for (i = 0; i < tessellation; i++) {
  38813. if (!isTop) {
  38814. indices.push(vbase);
  38815. indices.push(vbase + (i + 1));
  38816. indices.push(vbase + (i + 2));
  38817. }
  38818. else {
  38819. indices.push(vbase);
  38820. indices.push(vbase + (i + 2));
  38821. indices.push(vbase + (i + 1));
  38822. }
  38823. }
  38824. };
  38825. // add caps to geometry
  38826. createCylinderCap(false);
  38827. createCylinderCap(true);
  38828. // Sides
  38829. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38830. var vertexData = new VertexData();
  38831. vertexData.indices = indices;
  38832. vertexData.positions = positions;
  38833. vertexData.normals = normals;
  38834. vertexData.uvs = uvs;
  38835. if (faceColors) {
  38836. vertexData.colors = colors;
  38837. }
  38838. return vertexData;
  38839. };
  38840. /**
  38841. * Creates the VertexData for a torus
  38842. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38843. * * diameter the diameter of the torus, optional default 1
  38844. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38845. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38846. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38847. * * 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)
  38848. * * 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)
  38849. * @returns the VertexData of the torus
  38850. */
  38851. VertexData.CreateTorus = function (options) {
  38852. var indices = [];
  38853. var positions = [];
  38854. var normals = [];
  38855. var uvs = [];
  38856. var diameter = options.diameter || 1;
  38857. var thickness = options.thickness || 0.5;
  38858. var tessellation = options.tessellation || 16;
  38859. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38860. var stride = tessellation + 1;
  38861. for (var i = 0; i <= tessellation; i++) {
  38862. var u = i / tessellation;
  38863. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38864. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38865. for (var j = 0; j <= tessellation; j++) {
  38866. var v = 1 - j / tessellation;
  38867. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38868. var dx = Math.cos(innerAngle);
  38869. var dy = Math.sin(innerAngle);
  38870. // Create a vertex.
  38871. var normal = new BABYLON.Vector3(dx, dy, 0);
  38872. var position = normal.scale(thickness / 2);
  38873. var textureCoordinate = new BABYLON.Vector2(u, v);
  38874. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38875. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38876. positions.push(position.x, position.y, position.z);
  38877. normals.push(normal.x, normal.y, normal.z);
  38878. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38879. // And create indices for two triangles.
  38880. var nextI = (i + 1) % stride;
  38881. var nextJ = (j + 1) % stride;
  38882. indices.push(i * stride + j);
  38883. indices.push(i * stride + nextJ);
  38884. indices.push(nextI * stride + j);
  38885. indices.push(i * stride + nextJ);
  38886. indices.push(nextI * stride + nextJ);
  38887. indices.push(nextI * stride + j);
  38888. }
  38889. }
  38890. // Sides
  38891. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38892. // Result
  38893. var vertexData = new VertexData();
  38894. vertexData.indices = indices;
  38895. vertexData.positions = positions;
  38896. vertexData.normals = normals;
  38897. vertexData.uvs = uvs;
  38898. return vertexData;
  38899. };
  38900. /**
  38901. * Creates the VertexData of the LineSystem
  38902. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38903. * - lines an array of lines, each line being an array of successive Vector3
  38904. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38905. * @returns the VertexData of the LineSystem
  38906. */
  38907. VertexData.CreateLineSystem = function (options) {
  38908. var indices = [];
  38909. var positions = [];
  38910. var lines = options.lines;
  38911. var colors = options.colors;
  38912. var vertexColors = [];
  38913. var idx = 0;
  38914. for (var l = 0; l < lines.length; l++) {
  38915. var points = lines[l];
  38916. for (var index = 0; index < points.length; index++) {
  38917. positions.push(points[index].x, points[index].y, points[index].z);
  38918. if (colors) {
  38919. var color = colors[l];
  38920. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38921. }
  38922. if (index > 0) {
  38923. indices.push(idx - 1);
  38924. indices.push(idx);
  38925. }
  38926. idx++;
  38927. }
  38928. }
  38929. var vertexData = new VertexData();
  38930. vertexData.indices = indices;
  38931. vertexData.positions = positions;
  38932. if (colors) {
  38933. vertexData.colors = vertexColors;
  38934. }
  38935. return vertexData;
  38936. };
  38937. /**
  38938. * Create the VertexData for a DashedLines
  38939. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38940. * - points an array successive Vector3
  38941. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38942. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38943. * - dashNb the intended total number of dashes, optional, default 200
  38944. * @returns the VertexData for the DashedLines
  38945. */
  38946. VertexData.CreateDashedLines = function (options) {
  38947. var dashSize = options.dashSize || 3;
  38948. var gapSize = options.gapSize || 1;
  38949. var dashNb = options.dashNb || 200;
  38950. var points = options.points;
  38951. var positions = new Array();
  38952. var indices = new Array();
  38953. var curvect = BABYLON.Vector3.Zero();
  38954. var lg = 0;
  38955. var nb = 0;
  38956. var shft = 0;
  38957. var dashshft = 0;
  38958. var curshft = 0;
  38959. var idx = 0;
  38960. var i = 0;
  38961. for (i = 0; i < points.length - 1; i++) {
  38962. points[i + 1].subtractToRef(points[i], curvect);
  38963. lg += curvect.length();
  38964. }
  38965. shft = lg / dashNb;
  38966. dashshft = dashSize * shft / (dashSize + gapSize);
  38967. for (i = 0; i < points.length - 1; i++) {
  38968. points[i + 1].subtractToRef(points[i], curvect);
  38969. nb = Math.floor(curvect.length() / shft);
  38970. curvect.normalize();
  38971. for (var j = 0; j < nb; j++) {
  38972. curshft = shft * j;
  38973. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38974. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38975. indices.push(idx, idx + 1);
  38976. idx += 2;
  38977. }
  38978. }
  38979. // Result
  38980. var vertexData = new VertexData();
  38981. vertexData.positions = positions;
  38982. vertexData.indices = indices;
  38983. return vertexData;
  38984. };
  38985. /**
  38986. * Creates the VertexData for a Ground
  38987. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38988. * - width the width (x direction) of the ground, optional, default 1
  38989. * - height the height (z direction) of the ground, optional, default 1
  38990. * - subdivisions the number of subdivisions per side, optional, default 1
  38991. * @returns the VertexData of the Ground
  38992. */
  38993. VertexData.CreateGround = function (options) {
  38994. var indices = [];
  38995. var positions = [];
  38996. var normals = [];
  38997. var uvs = [];
  38998. var row, col;
  38999. var width = options.width || 1;
  39000. var height = options.height || 1;
  39001. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39002. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39003. for (row = 0; row <= subdivisionsY; row++) {
  39004. for (col = 0; col <= subdivisionsX; col++) {
  39005. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39006. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39007. positions.push(position.x, position.y, position.z);
  39008. normals.push(normal.x, normal.y, normal.z);
  39009. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39010. }
  39011. }
  39012. for (row = 0; row < subdivisionsY; row++) {
  39013. for (col = 0; col < subdivisionsX; col++) {
  39014. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39015. indices.push(col + 1 + row * (subdivisionsX + 1));
  39016. indices.push(col + row * (subdivisionsX + 1));
  39017. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39018. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39019. indices.push(col + row * (subdivisionsX + 1));
  39020. }
  39021. }
  39022. // Result
  39023. var vertexData = new VertexData();
  39024. vertexData.indices = indices;
  39025. vertexData.positions = positions;
  39026. vertexData.normals = normals;
  39027. vertexData.uvs = uvs;
  39028. return vertexData;
  39029. };
  39030. /**
  39031. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39032. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39033. * * xmin the ground minimum X coordinate, optional, default -1
  39034. * * zmin the ground minimum Z coordinate, optional, default -1
  39035. * * xmax the ground maximum X coordinate, optional, default 1
  39036. * * zmax the ground maximum Z coordinate, optional, default 1
  39037. * * 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}
  39038. * * 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}
  39039. * @returns the VertexData of the TiledGround
  39040. */
  39041. VertexData.CreateTiledGround = function (options) {
  39042. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39043. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39044. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39045. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39046. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39047. var precision = options.precision || { w: 1, h: 1 };
  39048. var indices = new Array();
  39049. var positions = new Array();
  39050. var normals = new Array();
  39051. var uvs = new Array();
  39052. var row, col, tileRow, tileCol;
  39053. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39054. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39055. precision.w = (precision.w < 1) ? 1 : precision.w;
  39056. precision.h = (precision.h < 1) ? 1 : precision.h;
  39057. var tileSize = {
  39058. 'w': (xmax - xmin) / subdivisions.w,
  39059. 'h': (zmax - zmin) / subdivisions.h
  39060. };
  39061. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39062. // Indices
  39063. var base = positions.length / 3;
  39064. var rowLength = precision.w + 1;
  39065. for (row = 0; row < precision.h; row++) {
  39066. for (col = 0; col < precision.w; col++) {
  39067. var square = [
  39068. base + col + row * rowLength,
  39069. base + (col + 1) + row * rowLength,
  39070. base + (col + 1) + (row + 1) * rowLength,
  39071. base + col + (row + 1) * rowLength
  39072. ];
  39073. indices.push(square[1]);
  39074. indices.push(square[2]);
  39075. indices.push(square[3]);
  39076. indices.push(square[0]);
  39077. indices.push(square[1]);
  39078. indices.push(square[3]);
  39079. }
  39080. }
  39081. // Position, normals and uvs
  39082. var position = BABYLON.Vector3.Zero();
  39083. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39084. for (row = 0; row <= precision.h; row++) {
  39085. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39086. for (col = 0; col <= precision.w; col++) {
  39087. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39088. position.y = 0;
  39089. positions.push(position.x, position.y, position.z);
  39090. normals.push(normal.x, normal.y, normal.z);
  39091. uvs.push(col / precision.w, row / precision.h);
  39092. }
  39093. }
  39094. }
  39095. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39096. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39097. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39098. }
  39099. }
  39100. // Result
  39101. var vertexData = new VertexData();
  39102. vertexData.indices = indices;
  39103. vertexData.positions = positions;
  39104. vertexData.normals = normals;
  39105. vertexData.uvs = uvs;
  39106. return vertexData;
  39107. };
  39108. /**
  39109. * Creates the VertexData of the Ground designed from a heightmap
  39110. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39111. * * width the width (x direction) of the ground
  39112. * * height the height (z direction) of the ground
  39113. * * subdivisions the number of subdivisions per side
  39114. * * minHeight the minimum altitude on the ground, optional, default 0
  39115. * * maxHeight the maximum altitude on the ground, optional default 1
  39116. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39117. * * buffer the array holding the image color data
  39118. * * bufferWidth the width of image
  39119. * * bufferHeight the height of image
  39120. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39121. * @returns the VertexData of the Ground designed from a heightmap
  39122. */
  39123. VertexData.CreateGroundFromHeightMap = function (options) {
  39124. var indices = [];
  39125. var positions = [];
  39126. var normals = [];
  39127. var uvs = [];
  39128. var row, col;
  39129. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39130. var alphaFilter = options.alphaFilter || 0.0;
  39131. // Vertices
  39132. for (row = 0; row <= options.subdivisions; row++) {
  39133. for (col = 0; col <= options.subdivisions; col++) {
  39134. 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));
  39135. // Compute height
  39136. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39137. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39138. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39139. var r = options.buffer[pos] / 255.0;
  39140. var g = options.buffer[pos + 1] / 255.0;
  39141. var b = options.buffer[pos + 2] / 255.0;
  39142. var a = options.buffer[pos + 3] / 255.0;
  39143. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39144. // If our alpha channel is not within our filter then we will assign a 'special' height
  39145. // Then when building the indices, we will ignore any vertex that is using the special height
  39146. if (a >= alphaFilter) {
  39147. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39148. }
  39149. else {
  39150. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39151. }
  39152. // Add vertex
  39153. positions.push(position.x, position.y, position.z);
  39154. normals.push(0, 0, 0);
  39155. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39156. }
  39157. }
  39158. // Indices
  39159. for (row = 0; row < options.subdivisions; row++) {
  39160. for (col = 0; col < options.subdivisions; col++) {
  39161. // Calculate Indices
  39162. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39163. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39164. var idx3 = (col + row * (options.subdivisions + 1));
  39165. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39166. // Check that all indices are visible (based on our special height)
  39167. // Only display the vertex if all Indices are visible
  39168. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39169. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39170. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39171. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39172. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39173. indices.push(idx1);
  39174. indices.push(idx2);
  39175. indices.push(idx3);
  39176. }
  39177. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39178. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39179. indices.push(idx4);
  39180. indices.push(idx1);
  39181. indices.push(idx3);
  39182. }
  39183. }
  39184. }
  39185. // Normals
  39186. VertexData.ComputeNormals(positions, indices, normals);
  39187. // Result
  39188. var vertexData = new VertexData();
  39189. vertexData.indices = indices;
  39190. vertexData.positions = positions;
  39191. vertexData.normals = normals;
  39192. vertexData.uvs = uvs;
  39193. return vertexData;
  39194. };
  39195. /**
  39196. * Creates the VertexData for a Plane
  39197. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39198. * * size sets the width and height of the plane to the value of size, optional default 1
  39199. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39200. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39201. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39202. * * 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)
  39203. * * 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)
  39204. * @returns the VertexData of the box
  39205. */
  39206. VertexData.CreatePlane = function (options) {
  39207. var indices = [];
  39208. var positions = [];
  39209. var normals = [];
  39210. var uvs = [];
  39211. var width = options.width || options.size || 1;
  39212. var height = options.height || options.size || 1;
  39213. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39214. // Vertices
  39215. var halfWidth = width / 2.0;
  39216. var halfHeight = height / 2.0;
  39217. positions.push(-halfWidth, -halfHeight, 0);
  39218. normals.push(0, 0, -1.0);
  39219. uvs.push(0.0, 0.0);
  39220. positions.push(halfWidth, -halfHeight, 0);
  39221. normals.push(0, 0, -1.0);
  39222. uvs.push(1.0, 0.0);
  39223. positions.push(halfWidth, halfHeight, 0);
  39224. normals.push(0, 0, -1.0);
  39225. uvs.push(1.0, 1.0);
  39226. positions.push(-halfWidth, halfHeight, 0);
  39227. normals.push(0, 0, -1.0);
  39228. uvs.push(0.0, 1.0);
  39229. // Indices
  39230. indices.push(0);
  39231. indices.push(1);
  39232. indices.push(2);
  39233. indices.push(0);
  39234. indices.push(2);
  39235. indices.push(3);
  39236. // Sides
  39237. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39238. // Result
  39239. var vertexData = new VertexData();
  39240. vertexData.indices = indices;
  39241. vertexData.positions = positions;
  39242. vertexData.normals = normals;
  39243. vertexData.uvs = uvs;
  39244. return vertexData;
  39245. };
  39246. /**
  39247. * Creates the VertexData of the Disc or regular Polygon
  39248. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39249. * * radius the radius of the disc, optional default 0.5
  39250. * * tessellation the number of polygon sides, optional, default 64
  39251. * * 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
  39252. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39253. * * 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)
  39254. * * 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)
  39255. * @returns the VertexData of the box
  39256. */
  39257. VertexData.CreateDisc = function (options) {
  39258. var positions = new Array();
  39259. var indices = new Array();
  39260. var normals = new Array();
  39261. var uvs = new Array();
  39262. var radius = options.radius || 0.5;
  39263. var tessellation = options.tessellation || 64;
  39264. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39266. // positions and uvs
  39267. positions.push(0, 0, 0); // disc center first
  39268. uvs.push(0.5, 0.5);
  39269. var theta = Math.PI * 2 * arc;
  39270. var step = theta / tessellation;
  39271. for (var a = 0; a < theta; a += step) {
  39272. var x = Math.cos(a);
  39273. var y = Math.sin(a);
  39274. var u = (x + 1) / 2;
  39275. var v = (1 - y) / 2;
  39276. positions.push(radius * x, radius * y, 0);
  39277. uvs.push(u, v);
  39278. }
  39279. if (arc === 1) {
  39280. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39281. uvs.push(uvs[2], uvs[3]);
  39282. }
  39283. //indices
  39284. var vertexNb = positions.length / 3;
  39285. for (var i = 1; i < vertexNb - 1; i++) {
  39286. indices.push(i + 1, 0, i);
  39287. }
  39288. // result
  39289. VertexData.ComputeNormals(positions, indices, normals);
  39290. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39291. var vertexData = new VertexData();
  39292. vertexData.indices = indices;
  39293. vertexData.positions = positions;
  39294. vertexData.normals = normals;
  39295. vertexData.uvs = uvs;
  39296. return vertexData;
  39297. };
  39298. /**
  39299. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39300. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39301. * @param polygon a mesh built from polygonTriangulation.build()
  39302. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39303. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39304. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39305. * @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)
  39306. * @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)
  39307. * @returns the VertexData of the Polygon
  39308. */
  39309. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39310. var faceUV = fUV || new Array(3);
  39311. var faceColors = fColors;
  39312. var colors = [];
  39313. // default face colors and UV if undefined
  39314. for (var f = 0; f < 3; f++) {
  39315. if (faceUV[f] === undefined) {
  39316. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39317. }
  39318. if (faceColors && faceColors[f] === undefined) {
  39319. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39320. }
  39321. }
  39322. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39323. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39324. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39325. var indices = polygon.getIndices();
  39326. // set face colours and textures
  39327. var idx = 0;
  39328. var face = 0;
  39329. for (var index = 0; index < normals.length; index += 3) {
  39330. //Edge Face no. 1
  39331. if (Math.abs(normals[index + 1]) < 0.001) {
  39332. face = 1;
  39333. }
  39334. //Top Face no. 0
  39335. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39336. face = 0;
  39337. }
  39338. //Bottom Face no. 2
  39339. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39340. face = 2;
  39341. }
  39342. idx = index / 3;
  39343. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39344. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39345. if (faceColors) {
  39346. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39347. }
  39348. }
  39349. // sides
  39350. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39351. // Result
  39352. var vertexData = new VertexData();
  39353. vertexData.indices = indices;
  39354. vertexData.positions = positions;
  39355. vertexData.normals = normals;
  39356. vertexData.uvs = uvs;
  39357. if (faceColors) {
  39358. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39359. vertexData.colors = totalColors;
  39360. }
  39361. return vertexData;
  39362. };
  39363. /**
  39364. * Creates the VertexData of the IcoSphere
  39365. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39366. * * radius the radius of the IcoSphere, optional default 1
  39367. * * radiusX allows stretching in the x direction, optional, default radius
  39368. * * radiusY allows stretching in the y direction, optional, default radius
  39369. * * radiusZ allows stretching in the z direction, optional, default radius
  39370. * * flat when true creates a flat shaded mesh, optional, default true
  39371. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39372. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39373. * * 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)
  39374. * * 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)
  39375. * @returns the VertexData of the IcoSphere
  39376. */
  39377. VertexData.CreateIcoSphere = function (options) {
  39378. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39379. var radius = options.radius || 1;
  39380. var flat = (options.flat === undefined) ? true : options.flat;
  39381. var subdivisions = options.subdivisions || 4;
  39382. var radiusX = options.radiusX || radius;
  39383. var radiusY = options.radiusY || radius;
  39384. var radiusZ = options.radiusZ || radius;
  39385. var t = (1 + Math.sqrt(5)) / 2;
  39386. // 12 vertex x,y,z
  39387. var ico_vertices = [
  39388. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39389. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39390. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39391. ];
  39392. // index of 3 vertex makes a face of icopshere
  39393. var ico_indices = [
  39394. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39395. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39396. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39397. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39398. ];
  39399. // vertex for uv have aliased position, not for UV
  39400. var vertices_unalias_id = [
  39401. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39402. // vertex alias
  39403. 0,
  39404. 2,
  39405. 3,
  39406. 3,
  39407. 3,
  39408. 4,
  39409. 7,
  39410. 8,
  39411. 9,
  39412. 9,
  39413. 10,
  39414. 11 // 23: B + 12
  39415. ];
  39416. // uv as integer step (not pixels !)
  39417. var ico_vertexuv = [
  39418. 5, 1, 3, 1, 6, 4, 0, 0,
  39419. 5, 3, 4, 2, 2, 2, 4, 0,
  39420. 2, 0, 1, 1, 6, 0, 6, 2,
  39421. // vertex alias (for same vertex on different faces)
  39422. 0, 4,
  39423. 3, 3,
  39424. 4, 4,
  39425. 3, 1,
  39426. 4, 2,
  39427. 4, 4,
  39428. 0, 2,
  39429. 1, 1,
  39430. 2, 2,
  39431. 3, 3,
  39432. 1, 3,
  39433. 2, 4 // 23: B + 12
  39434. ];
  39435. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39436. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39437. // First island of uv mapping
  39438. // v = 4h 3+ 2
  39439. // v = 3h 9+ 4
  39440. // v = 2h 9+ 5 B
  39441. // v = 1h 9 1 0
  39442. // v = 0h 3 8 7 A
  39443. // u = 0 1 2 3 4 5 6 *a
  39444. // Second island of uv mapping
  39445. // v = 4h 0+ B+ 4+
  39446. // v = 3h A+ 2+
  39447. // v = 2h 7+ 6 3+
  39448. // v = 1h 8+ 3+
  39449. // v = 0h
  39450. // u = 0 1 2 3 4 5 6 *a
  39451. // Face layout on texture UV mapping
  39452. // ============
  39453. // \ 4 /\ 16 / ======
  39454. // \ / \ / /\ 11 /
  39455. // \/ 7 \/ / \ /
  39456. // ======= / 10 \/
  39457. // /\ 17 /\ =======
  39458. // / \ / \ \ 15 /\
  39459. // / 8 \/ 12 \ \ / \
  39460. // ============ \/ 6 \
  39461. // \ 18 /\ ============
  39462. // \ / \ \ 5 /\ 0 /
  39463. // \/ 13 \ \ / \ /
  39464. // ======= \/ 1 \/
  39465. // =============
  39466. // /\ 19 /\ 2 /\
  39467. // / \ / \ / \
  39468. // / 14 \/ 9 \/ 3 \
  39469. // ===================
  39470. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39471. var ustep = 138 / 1024;
  39472. var vstep = 239 / 1024;
  39473. var uoffset = 60 / 1024;
  39474. var voffset = 26 / 1024;
  39475. // Second island should have margin, not to touch the first island
  39476. // avoid any borderline artefact in pixel rounding
  39477. var island_u_offset = -40 / 1024;
  39478. var island_v_offset = +20 / 1024;
  39479. // face is either island 0 or 1 :
  39480. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39481. var island = [
  39482. 0, 0, 0, 0, 1,
  39483. 0, 0, 1, 1, 0,
  39484. 0, 0, 1, 1, 0,
  39485. 0, 1, 1, 1, 0 // 15 - 19
  39486. ];
  39487. var indices = new Array();
  39488. var positions = new Array();
  39489. var normals = new Array();
  39490. var uvs = new Array();
  39491. var current_indice = 0;
  39492. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39493. var face_vertex_pos = new Array(3);
  39494. var face_vertex_uv = new Array(3);
  39495. var v012;
  39496. for (v012 = 0; v012 < 3; v012++) {
  39497. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39498. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39499. }
  39500. // create all with normals
  39501. for (var face = 0; face < 20; face++) {
  39502. // 3 vertex per face
  39503. for (v012 = 0; v012 < 3; v012++) {
  39504. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39505. var v_id = ico_indices[3 * face + v012];
  39506. // vertex have 3D position (x,y,z)
  39507. 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]);
  39508. // Normalize to get normal, then scale to radius
  39509. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39510. // uv Coordinates from vertex ID
  39511. 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);
  39512. }
  39513. // Subdivide the face (interpolate pos, norm, uv)
  39514. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39515. // - norm is linear interpolation of vertex corner normal
  39516. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39517. // - uv is linear interpolation
  39518. //
  39519. // Topology is as below for sub-divide by 2
  39520. // vertex shown as v0,v1,v2
  39521. // interp index is i1 to progress in range [v0,v1[
  39522. // interp index is i2 to progress in range [v0,v2[
  39523. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39524. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39525. //
  39526. //
  39527. // i2 v2
  39528. // ^ ^
  39529. // / / \
  39530. // / / \
  39531. // / / \
  39532. // / / (0,1) \
  39533. // / #---------\
  39534. // / / \ (0,0)'/ \
  39535. // / / \ / \
  39536. // / / \ / \
  39537. // / / (0,0) \ / (1,0) \
  39538. // / #---------#---------\
  39539. // v0 v1
  39540. //
  39541. // --------------------> i1
  39542. //
  39543. // interp of (i1,i2):
  39544. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39545. // along i1 : lerp(x0,x1, i1/(S-i2))
  39546. //
  39547. // centroid of triangle is needed to get help normal computation
  39548. // (c1,c2) are used for centroid location
  39549. var interp_vertex = function (i1, i2, c1, c2) {
  39550. // vertex is interpolated from
  39551. // - face_vertex_pos[0..2]
  39552. // - face_vertex_uv[0..2]
  39553. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39554. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39555. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39556. pos_interp.normalize();
  39557. var vertex_normal;
  39558. if (flat) {
  39559. // in flat mode, recalculate normal as face centroid normal
  39560. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39561. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39562. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39563. }
  39564. else {
  39565. // in smooth mode, recalculate normal from each single vertex position
  39566. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39567. }
  39568. // Vertex normal need correction due to X,Y,Z radius scaling
  39569. vertex_normal.x /= radiusX;
  39570. vertex_normal.y /= radiusY;
  39571. vertex_normal.z /= radiusZ;
  39572. vertex_normal.normalize();
  39573. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39574. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39575. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39576. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39577. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39578. uvs.push(uv_interp.x, uv_interp.y);
  39579. // push each vertex has member of a face
  39580. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39581. indices.push(current_indice);
  39582. current_indice++;
  39583. };
  39584. for (var i2 = 0; i2 < subdivisions; i2++) {
  39585. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39586. // face : (i1,i2) for /\ :
  39587. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39588. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39589. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39590. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39591. if (i1 + i2 + 1 < subdivisions) {
  39592. // face : (i1,i2)' for \/ :
  39593. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39594. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39595. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39596. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39597. }
  39598. }
  39599. }
  39600. }
  39601. // Sides
  39602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39603. // Result
  39604. var vertexData = new VertexData();
  39605. vertexData.indices = indices;
  39606. vertexData.positions = positions;
  39607. vertexData.normals = normals;
  39608. vertexData.uvs = uvs;
  39609. return vertexData;
  39610. };
  39611. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39612. /**
  39613. * Creates the VertexData for a Polyhedron
  39614. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39615. * * type provided types are:
  39616. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39617. * * 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)
  39618. * * size the size of the IcoSphere, optional default 1
  39619. * * sizeX allows stretching in the x direction, optional, default size
  39620. * * sizeY allows stretching in the y direction, optional, default size
  39621. * * sizeZ allows stretching in the z direction, optional, default size
  39622. * * 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
  39623. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39624. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39625. * * flat when true creates a flat shaded mesh, optional, default true
  39626. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39627. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39628. * * 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)
  39629. * * 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)
  39630. * @returns the VertexData of the Polyhedron
  39631. */
  39632. VertexData.CreatePolyhedron = function (options) {
  39633. // provided polyhedron types :
  39634. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39635. // 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)
  39636. var polyhedra = [];
  39637. 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]] };
  39638. 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]] };
  39639. polyhedra[2] = {
  39640. 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]],
  39641. 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]]
  39642. };
  39643. polyhedra[3] = {
  39644. 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]],
  39645. 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]]
  39646. };
  39647. polyhedra[4] = {
  39648. 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]],
  39649. 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]]
  39650. };
  39651. 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]] };
  39652. 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]] };
  39653. 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]] };
  39654. 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]] };
  39655. 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]] };
  39656. 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]] };
  39657. 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]] };
  39658. 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]] };
  39659. 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]] };
  39660. polyhedra[14] = {
  39661. 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]],
  39662. 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]]
  39663. };
  39664. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39665. var size = options.size;
  39666. var sizeX = options.sizeX || size || 1;
  39667. var sizeY = options.sizeY || size || 1;
  39668. var sizeZ = options.sizeZ || size || 1;
  39669. var data = options.custom || polyhedra[type];
  39670. var nbfaces = data.face.length;
  39671. var faceUV = options.faceUV || new Array(nbfaces);
  39672. var faceColors = options.faceColors;
  39673. var flat = (options.flat === undefined) ? true : options.flat;
  39674. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39675. var positions = new Array();
  39676. var indices = new Array();
  39677. var normals = new Array();
  39678. var uvs = new Array();
  39679. var colors = new Array();
  39680. var index = 0;
  39681. var faceIdx = 0; // face cursor in the array "indexes"
  39682. var indexes = new Array();
  39683. var i = 0;
  39684. var f = 0;
  39685. var u, v, ang, x, y, tmp;
  39686. // default face colors and UV if undefined
  39687. if (flat) {
  39688. for (f = 0; f < nbfaces; f++) {
  39689. if (faceColors && faceColors[f] === undefined) {
  39690. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39691. }
  39692. if (faceUV && faceUV[f] === undefined) {
  39693. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39694. }
  39695. }
  39696. }
  39697. if (!flat) {
  39698. for (i = 0; i < data.vertex.length; i++) {
  39699. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39700. uvs.push(0, 0);
  39701. }
  39702. for (f = 0; f < nbfaces; f++) {
  39703. for (i = 0; i < data.face[f].length - 2; i++) {
  39704. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39705. }
  39706. }
  39707. }
  39708. else {
  39709. for (f = 0; f < nbfaces; f++) {
  39710. var fl = data.face[f].length; // number of vertices of the current face
  39711. ang = 2 * Math.PI / fl;
  39712. x = 0.5 * Math.tan(ang / 2);
  39713. y = 0.5;
  39714. // positions, uvs, colors
  39715. for (i = 0; i < fl; i++) {
  39716. // positions
  39717. 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);
  39718. indexes.push(index);
  39719. index++;
  39720. // uvs
  39721. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39722. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39723. uvs.push(u, v);
  39724. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39725. y = x * Math.sin(ang) + y * Math.cos(ang);
  39726. x = tmp;
  39727. // colors
  39728. if (faceColors) {
  39729. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39730. }
  39731. }
  39732. // indices from indexes
  39733. for (i = 0; i < fl - 2; i++) {
  39734. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39735. }
  39736. faceIdx += fl;
  39737. }
  39738. }
  39739. VertexData.ComputeNormals(positions, indices, normals);
  39740. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39741. var vertexData = new VertexData();
  39742. vertexData.positions = positions;
  39743. vertexData.indices = indices;
  39744. vertexData.normals = normals;
  39745. vertexData.uvs = uvs;
  39746. if (faceColors && flat) {
  39747. vertexData.colors = colors;
  39748. }
  39749. return vertexData;
  39750. };
  39751. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39752. /**
  39753. * Creates the VertexData for a TorusKnot
  39754. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39755. * * radius the radius of the torus knot, optional, default 2
  39756. * * tube the thickness of the tube, optional, default 0.5
  39757. * * radialSegments the number of sides on each tube segments, optional, default 32
  39758. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39759. * * p the number of windings around the z axis, optional, default 2
  39760. * * q the number of windings around the x axis, optional, default 3
  39761. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39762. * * 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)
  39763. * * 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)
  39764. * @returns the VertexData of the Torus Knot
  39765. */
  39766. VertexData.CreateTorusKnot = function (options) {
  39767. var indices = new Array();
  39768. var positions = new Array();
  39769. var normals = new Array();
  39770. var uvs = new Array();
  39771. var radius = options.radius || 2;
  39772. var tube = options.tube || 0.5;
  39773. var radialSegments = options.radialSegments || 32;
  39774. var tubularSegments = options.tubularSegments || 32;
  39775. var p = options.p || 2;
  39776. var q = options.q || 3;
  39777. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39778. // Helper
  39779. var getPos = function (angle) {
  39780. var cu = Math.cos(angle);
  39781. var su = Math.sin(angle);
  39782. var quOverP = q / p * angle;
  39783. var cs = Math.cos(quOverP);
  39784. var tx = radius * (2 + cs) * 0.5 * cu;
  39785. var ty = radius * (2 + cs) * su * 0.5;
  39786. var tz = radius * Math.sin(quOverP) * 0.5;
  39787. return new BABYLON.Vector3(tx, ty, tz);
  39788. };
  39789. // Vertices
  39790. var i;
  39791. var j;
  39792. for (i = 0; i <= radialSegments; i++) {
  39793. var modI = i % radialSegments;
  39794. var u = modI / radialSegments * 2 * p * Math.PI;
  39795. var p1 = getPos(u);
  39796. var p2 = getPos(u + 0.01);
  39797. var tang = p2.subtract(p1);
  39798. var n = p2.add(p1);
  39799. var bitan = BABYLON.Vector3.Cross(tang, n);
  39800. n = BABYLON.Vector3.Cross(bitan, tang);
  39801. bitan.normalize();
  39802. n.normalize();
  39803. for (j = 0; j < tubularSegments; j++) {
  39804. var modJ = j % tubularSegments;
  39805. var v = modJ / tubularSegments * 2 * Math.PI;
  39806. var cx = -tube * Math.cos(v);
  39807. var cy = tube * Math.sin(v);
  39808. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39809. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39810. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39811. uvs.push(i / radialSegments);
  39812. uvs.push(j / tubularSegments);
  39813. }
  39814. }
  39815. for (i = 0; i < radialSegments; i++) {
  39816. for (j = 0; j < tubularSegments; j++) {
  39817. var jNext = (j + 1) % tubularSegments;
  39818. var a = i * tubularSegments + j;
  39819. var b = (i + 1) * tubularSegments + j;
  39820. var c = (i + 1) * tubularSegments + jNext;
  39821. var d = i * tubularSegments + jNext;
  39822. indices.push(d);
  39823. indices.push(b);
  39824. indices.push(a);
  39825. indices.push(d);
  39826. indices.push(c);
  39827. indices.push(b);
  39828. }
  39829. }
  39830. // Normals
  39831. VertexData.ComputeNormals(positions, indices, normals);
  39832. // Sides
  39833. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39834. // Result
  39835. var vertexData = new VertexData();
  39836. vertexData.indices = indices;
  39837. vertexData.positions = positions;
  39838. vertexData.normals = normals;
  39839. vertexData.uvs = uvs;
  39840. return vertexData;
  39841. };
  39842. // Tools
  39843. /**
  39844. * Compute normals for given positions and indices
  39845. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39846. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39847. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39848. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39849. * * facetNormals : optional array of facet normals (vector3)
  39850. * * facetPositions : optional array of facet positions (vector3)
  39851. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39852. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39853. * * bInfo : optional bounding info, required for facetPartitioning computation
  39854. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39855. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39856. * * useRightHandedSystem: optional boolean to for right handed system computation
  39857. * * depthSort : optional boolean to enable the facet depth sort computation
  39858. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39859. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39860. */
  39861. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39862. // temporary scalar variables
  39863. var index = 0; // facet index
  39864. var p1p2x = 0.0; // p1p2 vector x coordinate
  39865. var p1p2y = 0.0; // p1p2 vector y coordinate
  39866. var p1p2z = 0.0; // p1p2 vector z coordinate
  39867. var p3p2x = 0.0; // p3p2 vector x coordinate
  39868. var p3p2y = 0.0; // p3p2 vector y coordinate
  39869. var p3p2z = 0.0; // p3p2 vector z coordinate
  39870. var faceNormalx = 0.0; // facet normal x coordinate
  39871. var faceNormaly = 0.0; // facet normal y coordinate
  39872. var faceNormalz = 0.0; // facet normal z coordinate
  39873. var length = 0.0; // facet normal length before normalization
  39874. var v1x = 0; // vector1 x index in the positions array
  39875. var v1y = 0; // vector1 y index in the positions array
  39876. var v1z = 0; // vector1 z index in the positions array
  39877. var v2x = 0; // vector2 x index in the positions array
  39878. var v2y = 0; // vector2 y index in the positions array
  39879. var v2z = 0; // vector2 z index in the positions array
  39880. var v3x = 0; // vector3 x index in the positions array
  39881. var v3y = 0; // vector3 y index in the positions array
  39882. var v3z = 0; // vector3 z index in the positions array
  39883. var computeFacetNormals = false;
  39884. var computeFacetPositions = false;
  39885. var computeFacetPartitioning = false;
  39886. var computeDepthSort = false;
  39887. var faceNormalSign = 1;
  39888. var ratio = 0;
  39889. var distanceTo = null;
  39890. if (options) {
  39891. computeFacetNormals = (options.facetNormals) ? true : false;
  39892. computeFacetPositions = (options.facetPositions) ? true : false;
  39893. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39894. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39895. ratio = options.ratio || 0;
  39896. computeDepthSort = (options.depthSort) ? true : false;
  39897. distanceTo = (options.distanceTo);
  39898. if (computeDepthSort) {
  39899. if (distanceTo === undefined) {
  39900. distanceTo = BABYLON.Vector3.Zero();
  39901. }
  39902. var depthSortedFacets = options.depthSortedFacets;
  39903. }
  39904. }
  39905. // facetPartitioning reinit if needed
  39906. var xSubRatio = 0;
  39907. var ySubRatio = 0;
  39908. var zSubRatio = 0;
  39909. var subSq = 0;
  39910. if (computeFacetPartitioning && options && options.bbSize) {
  39911. var ox = 0; // X partitioning index for facet position
  39912. var oy = 0; // Y partinioning index for facet position
  39913. var oz = 0; // Z partinioning index for facet position
  39914. var b1x = 0; // X partitioning index for facet v1 vertex
  39915. var b1y = 0; // Y partitioning index for facet v1 vertex
  39916. var b1z = 0; // z partitioning index for facet v1 vertex
  39917. var b2x = 0; // X partitioning index for facet v2 vertex
  39918. var b2y = 0; // Y partitioning index for facet v2 vertex
  39919. var b2z = 0; // Z partitioning index for facet v2 vertex
  39920. var b3x = 0; // X partitioning index for facet v3 vertex
  39921. var b3y = 0; // Y partitioning index for facet v3 vertex
  39922. var b3z = 0; // Z partitioning index for facet v3 vertex
  39923. var block_idx_o = 0; // facet barycenter block index
  39924. var block_idx_v1 = 0; // v1 vertex block index
  39925. var block_idx_v2 = 0; // v2 vertex block index
  39926. var block_idx_v3 = 0; // v3 vertex block index
  39927. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39928. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39929. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39930. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39931. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39932. subSq = options.subDiv.max * options.subDiv.max;
  39933. options.facetPartitioning.length = 0;
  39934. }
  39935. // reset the normals
  39936. for (index = 0; index < positions.length; index++) {
  39937. normals[index] = 0.0;
  39938. }
  39939. // Loop : 1 indice triplet = 1 facet
  39940. var nbFaces = (indices.length / 3) | 0;
  39941. for (index = 0; index < nbFaces; index++) {
  39942. // get the indexes of the coordinates of each vertex of the facet
  39943. v1x = indices[index * 3] * 3;
  39944. v1y = v1x + 1;
  39945. v1z = v1x + 2;
  39946. v2x = indices[index * 3 + 1] * 3;
  39947. v2y = v2x + 1;
  39948. v2z = v2x + 2;
  39949. v3x = indices[index * 3 + 2] * 3;
  39950. v3y = v3x + 1;
  39951. v3z = v3x + 2;
  39952. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39953. p1p2y = positions[v1y] - positions[v2y];
  39954. p1p2z = positions[v1z] - positions[v2z];
  39955. p3p2x = positions[v3x] - positions[v2x];
  39956. p3p2y = positions[v3y] - positions[v2y];
  39957. p3p2z = positions[v3z] - positions[v2z];
  39958. // compute the face normal with the cross product
  39959. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39960. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39961. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39962. // normalize this normal and store it in the array facetData
  39963. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39964. length = (length === 0) ? 1.0 : length;
  39965. faceNormalx /= length;
  39966. faceNormaly /= length;
  39967. faceNormalz /= length;
  39968. if (computeFacetNormals && options) {
  39969. options.facetNormals[index].x = faceNormalx;
  39970. options.facetNormals[index].y = faceNormaly;
  39971. options.facetNormals[index].z = faceNormalz;
  39972. }
  39973. if (computeFacetPositions && options) {
  39974. // compute and the facet barycenter coordinates in the array facetPositions
  39975. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39976. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39977. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39978. }
  39979. if (computeFacetPartitioning && options) {
  39980. // store the facet indexes in arrays in the main facetPartitioning array :
  39981. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39982. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39983. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39984. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39985. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39986. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39987. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39988. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39989. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39990. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39991. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39992. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39993. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39994. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39995. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39996. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39997. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39998. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39999. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40000. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40001. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40002. // push each facet index in each block containing the vertex
  40003. options.facetPartitioning[block_idx_v1].push(index);
  40004. if (block_idx_v2 != block_idx_v1) {
  40005. options.facetPartitioning[block_idx_v2].push(index);
  40006. }
  40007. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40008. options.facetPartitioning[block_idx_v3].push(index);
  40009. }
  40010. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40011. options.facetPartitioning[block_idx_o].push(index);
  40012. }
  40013. }
  40014. if (computeDepthSort && options && options.facetPositions) {
  40015. var dsf = depthSortedFacets[index];
  40016. dsf.ind = index * 3;
  40017. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40018. }
  40019. // compute the normals anyway
  40020. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40021. normals[v1y] += faceNormaly;
  40022. normals[v1z] += faceNormalz;
  40023. normals[v2x] += faceNormalx;
  40024. normals[v2y] += faceNormaly;
  40025. normals[v2z] += faceNormalz;
  40026. normals[v3x] += faceNormalx;
  40027. normals[v3y] += faceNormaly;
  40028. normals[v3z] += faceNormalz;
  40029. }
  40030. // last normalization of each normal
  40031. for (index = 0; index < normals.length / 3; index++) {
  40032. faceNormalx = normals[index * 3];
  40033. faceNormaly = normals[index * 3 + 1];
  40034. faceNormalz = normals[index * 3 + 2];
  40035. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40036. length = (length === 0) ? 1.0 : length;
  40037. faceNormalx /= length;
  40038. faceNormaly /= length;
  40039. faceNormalz /= length;
  40040. normals[index * 3] = faceNormalx;
  40041. normals[index * 3 + 1] = faceNormaly;
  40042. normals[index * 3 + 2] = faceNormalz;
  40043. }
  40044. };
  40045. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40046. var li = indices.length;
  40047. var ln = normals.length;
  40048. var i;
  40049. var n;
  40050. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40051. switch (sideOrientation) {
  40052. case BABYLON.Mesh.FRONTSIDE:
  40053. // nothing changed
  40054. break;
  40055. case BABYLON.Mesh.BACKSIDE:
  40056. var tmp;
  40057. // indices
  40058. for (i = 0; i < li; i += 3) {
  40059. tmp = indices[i];
  40060. indices[i] = indices[i + 2];
  40061. indices[i + 2] = tmp;
  40062. }
  40063. // normals
  40064. for (n = 0; n < ln; n++) {
  40065. normals[n] = -normals[n];
  40066. }
  40067. break;
  40068. case BABYLON.Mesh.DOUBLESIDE:
  40069. // positions
  40070. var lp = positions.length;
  40071. var l = lp / 3;
  40072. for (var p = 0; p < lp; p++) {
  40073. positions[lp + p] = positions[p];
  40074. }
  40075. // indices
  40076. for (i = 0; i < li; i += 3) {
  40077. indices[i + li] = indices[i + 2] + l;
  40078. indices[i + 1 + li] = indices[i + 1] + l;
  40079. indices[i + 2 + li] = indices[i] + l;
  40080. }
  40081. // normals
  40082. for (n = 0; n < ln; n++) {
  40083. normals[ln + n] = -normals[n];
  40084. }
  40085. // uvs
  40086. var lu = uvs.length;
  40087. var u = 0;
  40088. for (u = 0; u < lu; u++) {
  40089. uvs[u + lu] = uvs[u];
  40090. }
  40091. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40092. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40093. u = 0;
  40094. for (i = 0; i < lu / 2; i++) {
  40095. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40096. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40097. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40098. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40099. u += 2;
  40100. }
  40101. break;
  40102. }
  40103. };
  40104. /**
  40105. * Applies VertexData created from the imported parameters to the geometry
  40106. * @param parsedVertexData the parsed data from an imported file
  40107. * @param geometry the geometry to apply the VertexData to
  40108. */
  40109. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40110. var vertexData = new VertexData();
  40111. // positions
  40112. var positions = parsedVertexData.positions;
  40113. if (positions) {
  40114. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40115. }
  40116. // normals
  40117. var normals = parsedVertexData.normals;
  40118. if (normals) {
  40119. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40120. }
  40121. // tangents
  40122. var tangents = parsedVertexData.tangents;
  40123. if (tangents) {
  40124. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40125. }
  40126. // uvs
  40127. var uvs = parsedVertexData.uvs;
  40128. if (uvs) {
  40129. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40130. }
  40131. // uv2s
  40132. var uv2s = parsedVertexData.uv2s;
  40133. if (uv2s) {
  40134. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40135. }
  40136. // uv3s
  40137. var uv3s = parsedVertexData.uv3s;
  40138. if (uv3s) {
  40139. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40140. }
  40141. // uv4s
  40142. var uv4s = parsedVertexData.uv4s;
  40143. if (uv4s) {
  40144. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40145. }
  40146. // uv5s
  40147. var uv5s = parsedVertexData.uv5s;
  40148. if (uv5s) {
  40149. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40150. }
  40151. // uv6s
  40152. var uv6s = parsedVertexData.uv6s;
  40153. if (uv6s) {
  40154. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40155. }
  40156. // colors
  40157. var colors = parsedVertexData.colors;
  40158. if (colors) {
  40159. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40160. }
  40161. // matricesIndices
  40162. var matricesIndices = parsedVertexData.matricesIndices;
  40163. if (matricesIndices) {
  40164. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40165. }
  40166. // matricesWeights
  40167. var matricesWeights = parsedVertexData.matricesWeights;
  40168. if (matricesWeights) {
  40169. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40170. }
  40171. // indices
  40172. var indices = parsedVertexData.indices;
  40173. if (indices) {
  40174. vertexData.indices = indices;
  40175. }
  40176. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40177. };
  40178. return VertexData;
  40179. }());
  40180. BABYLON.VertexData = VertexData;
  40181. })(BABYLON || (BABYLON = {}));
  40182. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40183. var BABYLON;
  40184. (function (BABYLON) {
  40185. /**
  40186. * Class used to store geometry data (vertex buffers + index buffer)
  40187. */
  40188. var Geometry = /** @class */ (function () {
  40189. /**
  40190. * Creates a new geometry
  40191. * @param id defines the unique ID
  40192. * @param scene defines the hosting scene
  40193. * @param vertexData defines the VertexData used to get geometry data
  40194. * @param updatable defines if geometry must be updatable (false by default)
  40195. * @param mesh defines the mesh that will be associated with the geometry
  40196. */
  40197. function Geometry(id, scene, vertexData, updatable, mesh) {
  40198. if (updatable === void 0) { updatable = false; }
  40199. if (mesh === void 0) { mesh = null; }
  40200. /**
  40201. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40202. */
  40203. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40204. this._totalVertices = 0;
  40205. this._isDisposed = false;
  40206. this._indexBufferIsUpdatable = false;
  40207. this.id = id;
  40208. this._engine = scene.getEngine();
  40209. this._meshes = [];
  40210. this._scene = scene;
  40211. //Init vertex buffer cache
  40212. this._vertexBuffers = {};
  40213. this._indices = [];
  40214. this._updatable = updatable;
  40215. // vertexData
  40216. if (vertexData) {
  40217. this.setAllVerticesData(vertexData, updatable);
  40218. }
  40219. else {
  40220. this._totalVertices = 0;
  40221. this._indices = [];
  40222. }
  40223. if (this._engine.getCaps().vertexArrayObject) {
  40224. this._vertexArrayObjects = {};
  40225. }
  40226. // applyToMesh
  40227. if (mesh) {
  40228. if (mesh.getClassName() === "LinesMesh") {
  40229. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40230. this._updateExtend();
  40231. }
  40232. this.applyToMesh(mesh);
  40233. mesh.computeWorldMatrix(true);
  40234. }
  40235. }
  40236. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40237. /**
  40238. * 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
  40239. */
  40240. get: function () {
  40241. return this._boundingBias;
  40242. },
  40243. /**
  40244. * 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
  40245. */
  40246. set: function (value) {
  40247. if (this._boundingBias) {
  40248. if (this._boundingBias.equals(value)) {
  40249. return;
  40250. }
  40251. this._boundingBias.copyFrom(value);
  40252. }
  40253. else {
  40254. this._boundingBias = value.clone();
  40255. }
  40256. this._updateBoundingInfo(true, null);
  40257. },
  40258. enumerable: true,
  40259. configurable: true
  40260. });
  40261. /**
  40262. * Static function used to attach a new empty geometry to a mesh
  40263. * @param mesh defines the mesh to attach the geometry to
  40264. * @returns the new Geometry
  40265. */
  40266. Geometry.CreateGeometryForMesh = function (mesh) {
  40267. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40268. geometry.applyToMesh(mesh);
  40269. return geometry;
  40270. };
  40271. Object.defineProperty(Geometry.prototype, "extend", {
  40272. /**
  40273. * Gets the current extend of the geometry
  40274. */
  40275. get: function () {
  40276. return this._extend;
  40277. },
  40278. enumerable: true,
  40279. configurable: true
  40280. });
  40281. /**
  40282. * Gets the hosting scene
  40283. * @returns the hosting Scene
  40284. */
  40285. Geometry.prototype.getScene = function () {
  40286. return this._scene;
  40287. };
  40288. /**
  40289. * Gets the hosting engine
  40290. * @returns the hosting Engine
  40291. */
  40292. Geometry.prototype.getEngine = function () {
  40293. return this._engine;
  40294. };
  40295. /**
  40296. * Defines if the geometry is ready to use
  40297. * @returns true if the geometry is ready to be used
  40298. */
  40299. Geometry.prototype.isReady = function () {
  40300. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40301. };
  40302. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40303. /**
  40304. * Gets a value indicating that the geometry should not be serialized
  40305. */
  40306. get: function () {
  40307. for (var index = 0; index < this._meshes.length; index++) {
  40308. if (!this._meshes[index].doNotSerialize) {
  40309. return false;
  40310. }
  40311. }
  40312. return true;
  40313. },
  40314. enumerable: true,
  40315. configurable: true
  40316. });
  40317. /** @hidden */
  40318. Geometry.prototype._rebuild = function () {
  40319. if (this._vertexArrayObjects) {
  40320. this._vertexArrayObjects = {};
  40321. }
  40322. // Index buffer
  40323. if (this._meshes.length !== 0 && this._indices) {
  40324. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40325. }
  40326. // Vertex buffers
  40327. for (var key in this._vertexBuffers) {
  40328. var vertexBuffer = this._vertexBuffers[key];
  40329. vertexBuffer._rebuild();
  40330. }
  40331. };
  40332. /**
  40333. * Affects all geometry data in one call
  40334. * @param vertexData defines the geometry data
  40335. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40336. */
  40337. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40338. vertexData.applyToGeometry(this, updatable);
  40339. this.notifyUpdate();
  40340. };
  40341. /**
  40342. * Set specific vertex data
  40343. * @param kind defines the data kind (Position, normal, etc...)
  40344. * @param data defines the vertex data to use
  40345. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40346. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40347. */
  40348. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40349. if (updatable === void 0) { updatable = false; }
  40350. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40351. this.setVerticesBuffer(buffer);
  40352. };
  40353. /**
  40354. * Removes a specific vertex data
  40355. * @param kind defines the data kind (Position, normal, etc...)
  40356. */
  40357. Geometry.prototype.removeVerticesData = function (kind) {
  40358. if (this._vertexBuffers[kind]) {
  40359. this._vertexBuffers[kind].dispose();
  40360. delete this._vertexBuffers[kind];
  40361. }
  40362. };
  40363. /**
  40364. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40365. * @param buffer defines the vertex buffer to use
  40366. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40367. */
  40368. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40369. if (totalVertices === void 0) { totalVertices = null; }
  40370. var kind = buffer.getKind();
  40371. if (this._vertexBuffers[kind]) {
  40372. this._vertexBuffers[kind].dispose();
  40373. }
  40374. this._vertexBuffers[kind] = buffer;
  40375. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40376. var data = buffer.getData();
  40377. if (totalVertices != null) {
  40378. this._totalVertices = totalVertices;
  40379. }
  40380. else {
  40381. if (data != null) {
  40382. this._totalVertices = data.length / (buffer.byteStride / 4);
  40383. }
  40384. }
  40385. this._updateExtend(data);
  40386. this._resetPointsArrayCache();
  40387. var meshes = this._meshes;
  40388. var numOfMeshes = meshes.length;
  40389. for (var index = 0; index < numOfMeshes; index++) {
  40390. var mesh = meshes[index];
  40391. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40392. mesh._createGlobalSubMesh(false);
  40393. mesh.computeWorldMatrix(true);
  40394. }
  40395. }
  40396. this.notifyUpdate(kind);
  40397. if (this._vertexArrayObjects) {
  40398. this._disposeVertexArrayObjects();
  40399. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40400. }
  40401. };
  40402. /**
  40403. * Update a specific vertex buffer
  40404. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40405. * It will do nothing if the buffer is not updatable
  40406. * @param kind defines the data kind (Position, normal, etc...)
  40407. * @param data defines the data to use
  40408. * @param offset defines the offset in the target buffer where to store the data
  40409. * @param useBytes set to true if the offset is in bytes
  40410. */
  40411. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40412. if (useBytes === void 0) { useBytes = false; }
  40413. var vertexBuffer = this.getVertexBuffer(kind);
  40414. if (!vertexBuffer) {
  40415. return;
  40416. }
  40417. vertexBuffer.updateDirectly(data, offset, useBytes);
  40418. this.notifyUpdate(kind);
  40419. };
  40420. /**
  40421. * Update a specific vertex buffer
  40422. * This function will create a new buffer if the current one is not updatable
  40423. * @param kind defines the data kind (Position, normal, etc...)
  40424. * @param data defines the data to use
  40425. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40426. */
  40427. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40428. if (updateExtends === void 0) { updateExtends = false; }
  40429. var vertexBuffer = this.getVertexBuffer(kind);
  40430. if (!vertexBuffer) {
  40431. return;
  40432. }
  40433. vertexBuffer.update(data);
  40434. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40435. this._updateBoundingInfo(updateExtends, data);
  40436. }
  40437. this.notifyUpdate(kind);
  40438. };
  40439. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40440. if (updateExtends) {
  40441. this._updateExtend(data);
  40442. }
  40443. var meshes = this._meshes;
  40444. var numOfMeshes = meshes.length;
  40445. this._resetPointsArrayCache();
  40446. for (var index = 0; index < numOfMeshes; index++) {
  40447. var mesh = meshes[index];
  40448. if (updateExtends) {
  40449. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40450. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40451. var subMesh = mesh.subMeshes[subIndex];
  40452. subMesh.refreshBoundingInfo();
  40453. }
  40454. }
  40455. }
  40456. };
  40457. /** @hidden */
  40458. Geometry.prototype._bind = function (effect, indexToBind) {
  40459. if (!effect) {
  40460. return;
  40461. }
  40462. if (indexToBind === undefined) {
  40463. indexToBind = this._indexBuffer;
  40464. }
  40465. var vbs = this.getVertexBuffers();
  40466. if (!vbs) {
  40467. return;
  40468. }
  40469. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40470. this._engine.bindBuffers(vbs, indexToBind, effect);
  40471. return;
  40472. }
  40473. // Using VAO
  40474. if (!this._vertexArrayObjects[effect.key]) {
  40475. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40476. }
  40477. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40478. };
  40479. /**
  40480. * Gets total number of vertices
  40481. * @returns the total number of vertices
  40482. */
  40483. Geometry.prototype.getTotalVertices = function () {
  40484. if (!this.isReady()) {
  40485. return 0;
  40486. }
  40487. return this._totalVertices;
  40488. };
  40489. /**
  40490. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40491. * @param kind defines the data kind (Position, normal, etc...)
  40492. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40493. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40494. * @returns a float array containing vertex data
  40495. */
  40496. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40497. var vertexBuffer = this.getVertexBuffer(kind);
  40498. if (!vertexBuffer) {
  40499. return null;
  40500. }
  40501. var data = vertexBuffer.getData();
  40502. if (!data) {
  40503. return null;
  40504. }
  40505. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40506. var count = this._totalVertices * vertexBuffer.getSize();
  40507. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40508. var copy_1 = new Array(count);
  40509. vertexBuffer.forEach(count, function (value, index) {
  40510. copy_1[index] = value;
  40511. });
  40512. return copy_1;
  40513. }
  40514. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40515. if (data instanceof Array) {
  40516. var offset = vertexBuffer.byteOffset / 4;
  40517. return BABYLON.Tools.Slice(data, offset, offset + count);
  40518. }
  40519. else if (data instanceof ArrayBuffer) {
  40520. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40521. }
  40522. else {
  40523. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40524. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40525. var result = new Float32Array(count);
  40526. var source = new Float32Array(data.buffer, offset, count);
  40527. result.set(source);
  40528. return result;
  40529. }
  40530. return new Float32Array(data.buffer, offset, count);
  40531. }
  40532. }
  40533. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40534. return BABYLON.Tools.Slice(data);
  40535. }
  40536. return data;
  40537. };
  40538. /**
  40539. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40540. * @param kind defines the data kind (Position, normal, etc...)
  40541. * @returns true if the vertex buffer with the specified kind is updatable
  40542. */
  40543. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40544. var vb = this._vertexBuffers[kind];
  40545. if (!vb) {
  40546. return false;
  40547. }
  40548. return vb.isUpdatable();
  40549. };
  40550. /**
  40551. * Gets a specific vertex buffer
  40552. * @param kind defines the data kind (Position, normal, etc...)
  40553. * @returns a VertexBuffer
  40554. */
  40555. Geometry.prototype.getVertexBuffer = function (kind) {
  40556. if (!this.isReady()) {
  40557. return null;
  40558. }
  40559. return this._vertexBuffers[kind];
  40560. };
  40561. /**
  40562. * Returns all vertex buffers
  40563. * @return an object holding all vertex buffers indexed by kind
  40564. */
  40565. Geometry.prototype.getVertexBuffers = function () {
  40566. if (!this.isReady()) {
  40567. return null;
  40568. }
  40569. return this._vertexBuffers;
  40570. };
  40571. /**
  40572. * Gets a boolean indicating if specific vertex buffer is present
  40573. * @param kind defines the data kind (Position, normal, etc...)
  40574. * @returns true if data is present
  40575. */
  40576. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40577. if (!this._vertexBuffers) {
  40578. if (this._delayInfo) {
  40579. return this._delayInfo.indexOf(kind) !== -1;
  40580. }
  40581. return false;
  40582. }
  40583. return this._vertexBuffers[kind] !== undefined;
  40584. };
  40585. /**
  40586. * Gets a list of all attached data kinds (Position, normal, etc...)
  40587. * @returns a list of string containing all kinds
  40588. */
  40589. Geometry.prototype.getVerticesDataKinds = function () {
  40590. var result = [];
  40591. var kind;
  40592. if (!this._vertexBuffers && this._delayInfo) {
  40593. for (kind in this._delayInfo) {
  40594. result.push(kind);
  40595. }
  40596. }
  40597. else {
  40598. for (kind in this._vertexBuffers) {
  40599. result.push(kind);
  40600. }
  40601. }
  40602. return result;
  40603. };
  40604. /**
  40605. * Update index buffer
  40606. * @param indices defines the indices to store in the index buffer
  40607. * @param offset defines the offset in the target buffer where to store the data
  40608. */
  40609. Geometry.prototype.updateIndices = function (indices, offset) {
  40610. if (!this._indexBuffer) {
  40611. return;
  40612. }
  40613. if (!this._indexBufferIsUpdatable) {
  40614. this.setIndices(indices, null, true);
  40615. }
  40616. else {
  40617. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40618. }
  40619. };
  40620. /**
  40621. * Creates a new index buffer
  40622. * @param indices defines the indices to store in the index buffer
  40623. * @param totalVertices defines the total number of vertices (could be null)
  40624. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40625. */
  40626. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40627. if (totalVertices === void 0) { totalVertices = null; }
  40628. if (updatable === void 0) { updatable = false; }
  40629. if (this._indexBuffer) {
  40630. this._engine._releaseBuffer(this._indexBuffer);
  40631. }
  40632. this._disposeVertexArrayObjects();
  40633. this._indices = indices;
  40634. this._indexBufferIsUpdatable = updatable;
  40635. if (this._meshes.length !== 0 && this._indices) {
  40636. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40637. }
  40638. if (totalVertices != undefined) { // including null and undefined
  40639. this._totalVertices = totalVertices;
  40640. }
  40641. var meshes = this._meshes;
  40642. var numOfMeshes = meshes.length;
  40643. for (var index = 0; index < numOfMeshes; index++) {
  40644. meshes[index]._createGlobalSubMesh(true);
  40645. }
  40646. this.notifyUpdate();
  40647. };
  40648. /**
  40649. * Return the total number of indices
  40650. * @returns the total number of indices
  40651. */
  40652. Geometry.prototype.getTotalIndices = function () {
  40653. if (!this.isReady()) {
  40654. return 0;
  40655. }
  40656. return this._indices.length;
  40657. };
  40658. /**
  40659. * Gets the index buffer array
  40660. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40661. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40662. * @returns the index buffer array
  40663. */
  40664. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40665. if (!this.isReady()) {
  40666. return null;
  40667. }
  40668. var orig = this._indices;
  40669. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40670. return orig;
  40671. }
  40672. else {
  40673. var len = orig.length;
  40674. var copy = [];
  40675. for (var i = 0; i < len; i++) {
  40676. copy.push(orig[i]);
  40677. }
  40678. return copy;
  40679. }
  40680. };
  40681. /**
  40682. * Gets the index buffer
  40683. * @return the index buffer
  40684. */
  40685. Geometry.prototype.getIndexBuffer = function () {
  40686. if (!this.isReady()) {
  40687. return null;
  40688. }
  40689. return this._indexBuffer;
  40690. };
  40691. /** @hidden */
  40692. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40693. if (effect === void 0) { effect = null; }
  40694. if (!effect || !this._vertexArrayObjects) {
  40695. return;
  40696. }
  40697. if (this._vertexArrayObjects[effect.key]) {
  40698. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40699. delete this._vertexArrayObjects[effect.key];
  40700. }
  40701. };
  40702. /**
  40703. * Release the associated resources for a specific mesh
  40704. * @param mesh defines the source mesh
  40705. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40706. */
  40707. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40708. var meshes = this._meshes;
  40709. var index = meshes.indexOf(mesh);
  40710. if (index === -1) {
  40711. return;
  40712. }
  40713. meshes.splice(index, 1);
  40714. mesh._geometry = null;
  40715. if (meshes.length === 0 && shouldDispose) {
  40716. this.dispose();
  40717. }
  40718. };
  40719. /**
  40720. * Apply current geometry to a given mesh
  40721. * @param mesh defines the mesh to apply geometry to
  40722. */
  40723. Geometry.prototype.applyToMesh = function (mesh) {
  40724. if (mesh._geometry === this) {
  40725. return;
  40726. }
  40727. var previousGeometry = mesh._geometry;
  40728. if (previousGeometry) {
  40729. previousGeometry.releaseForMesh(mesh);
  40730. }
  40731. var meshes = this._meshes;
  40732. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40733. mesh._geometry = this;
  40734. this._scene.pushGeometry(this);
  40735. meshes.push(mesh);
  40736. if (this.isReady()) {
  40737. this._applyToMesh(mesh);
  40738. }
  40739. else {
  40740. mesh._boundingInfo = this._boundingInfo;
  40741. }
  40742. };
  40743. Geometry.prototype._updateExtend = function (data) {
  40744. if (data === void 0) { data = null; }
  40745. if (!data) {
  40746. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40747. }
  40748. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40749. };
  40750. Geometry.prototype._applyToMesh = function (mesh) {
  40751. var numOfMeshes = this._meshes.length;
  40752. // vertexBuffers
  40753. for (var kind in this._vertexBuffers) {
  40754. if (numOfMeshes === 1) {
  40755. this._vertexBuffers[kind].create();
  40756. }
  40757. var buffer = this._vertexBuffers[kind].getBuffer();
  40758. if (buffer) {
  40759. buffer.references = numOfMeshes;
  40760. }
  40761. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40762. if (!this._extend) {
  40763. this._updateExtend();
  40764. }
  40765. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40766. mesh._createGlobalSubMesh(false);
  40767. //bounding info was just created again, world matrix should be applied again.
  40768. mesh._updateBoundingInfo();
  40769. }
  40770. }
  40771. // indexBuffer
  40772. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40773. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40774. }
  40775. if (this._indexBuffer) {
  40776. this._indexBuffer.references = numOfMeshes;
  40777. }
  40778. };
  40779. Geometry.prototype.notifyUpdate = function (kind) {
  40780. if (this.onGeometryUpdated) {
  40781. this.onGeometryUpdated(this, kind);
  40782. }
  40783. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40784. var mesh = _a[_i];
  40785. mesh._markSubMeshesAsAttributesDirty();
  40786. }
  40787. };
  40788. /**
  40789. * Load the geometry if it was flagged as delay loaded
  40790. * @param scene defines the hosting scene
  40791. * @param onLoaded defines a callback called when the geometry is loaded
  40792. */
  40793. Geometry.prototype.load = function (scene, onLoaded) {
  40794. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40795. return;
  40796. }
  40797. if (this.isReady()) {
  40798. if (onLoaded) {
  40799. onLoaded();
  40800. }
  40801. return;
  40802. }
  40803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40804. this._queueLoad(scene, onLoaded);
  40805. };
  40806. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40807. var _this = this;
  40808. if (!this.delayLoadingFile) {
  40809. return;
  40810. }
  40811. scene._addPendingData(this);
  40812. scene._loadFile(this.delayLoadingFile, function (data) {
  40813. if (!_this._delayLoadingFunction) {
  40814. return;
  40815. }
  40816. _this._delayLoadingFunction(JSON.parse(data), _this);
  40817. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40818. _this._delayInfo = [];
  40819. scene._removePendingData(_this);
  40820. var meshes = _this._meshes;
  40821. var numOfMeshes = meshes.length;
  40822. for (var index = 0; index < numOfMeshes; index++) {
  40823. _this._applyToMesh(meshes[index]);
  40824. }
  40825. if (onLoaded) {
  40826. onLoaded();
  40827. }
  40828. }, undefined, true);
  40829. };
  40830. /**
  40831. * Invert the geometry to move from a right handed system to a left handed one.
  40832. */
  40833. Geometry.prototype.toLeftHanded = function () {
  40834. // Flip faces
  40835. var tIndices = this.getIndices(false);
  40836. if (tIndices != null && tIndices.length > 0) {
  40837. for (var i = 0; i < tIndices.length; i += 3) {
  40838. var tTemp = tIndices[i + 0];
  40839. tIndices[i + 0] = tIndices[i + 2];
  40840. tIndices[i + 2] = tTemp;
  40841. }
  40842. this.setIndices(tIndices);
  40843. }
  40844. // Negate position.z
  40845. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40846. if (tPositions != null && tPositions.length > 0) {
  40847. for (var i = 0; i < tPositions.length; i += 3) {
  40848. tPositions[i + 2] = -tPositions[i + 2];
  40849. }
  40850. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40851. }
  40852. // Negate normal.z
  40853. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40854. if (tNormals != null && tNormals.length > 0) {
  40855. for (var i = 0; i < tNormals.length; i += 3) {
  40856. tNormals[i + 2] = -tNormals[i + 2];
  40857. }
  40858. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40859. }
  40860. };
  40861. // Cache
  40862. /** @hidden */
  40863. Geometry.prototype._resetPointsArrayCache = function () {
  40864. this._positions = null;
  40865. };
  40866. /** @hidden */
  40867. Geometry.prototype._generatePointsArray = function () {
  40868. if (this._positions) {
  40869. return true;
  40870. }
  40871. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40872. if (!data || data.length === 0) {
  40873. return false;
  40874. }
  40875. this._positions = [];
  40876. for (var index = 0; index < data.length; index += 3) {
  40877. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40878. }
  40879. return true;
  40880. };
  40881. /**
  40882. * Gets a value indicating if the geometry is disposed
  40883. * @returns true if the geometry was disposed
  40884. */
  40885. Geometry.prototype.isDisposed = function () {
  40886. return this._isDisposed;
  40887. };
  40888. Geometry.prototype._disposeVertexArrayObjects = function () {
  40889. if (this._vertexArrayObjects) {
  40890. for (var kind in this._vertexArrayObjects) {
  40891. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40892. }
  40893. this._vertexArrayObjects = {};
  40894. }
  40895. };
  40896. /**
  40897. * Free all associated resources
  40898. */
  40899. Geometry.prototype.dispose = function () {
  40900. var meshes = this._meshes;
  40901. var numOfMeshes = meshes.length;
  40902. var index;
  40903. for (index = 0; index < numOfMeshes; index++) {
  40904. this.releaseForMesh(meshes[index]);
  40905. }
  40906. this._meshes = [];
  40907. this._disposeVertexArrayObjects();
  40908. for (var kind in this._vertexBuffers) {
  40909. this._vertexBuffers[kind].dispose();
  40910. }
  40911. this._vertexBuffers = {};
  40912. this._totalVertices = 0;
  40913. if (this._indexBuffer) {
  40914. this._engine._releaseBuffer(this._indexBuffer);
  40915. }
  40916. this._indexBuffer = null;
  40917. this._indices = [];
  40918. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40919. this.delayLoadingFile = null;
  40920. this._delayLoadingFunction = null;
  40921. this._delayInfo = [];
  40922. this._boundingInfo = null;
  40923. this._scene.removeGeometry(this);
  40924. this._isDisposed = true;
  40925. };
  40926. /**
  40927. * Clone the current geometry into a new geometry
  40928. * @param id defines the unique ID of the new geometry
  40929. * @returns a new geometry object
  40930. */
  40931. Geometry.prototype.copy = function (id) {
  40932. var vertexData = new BABYLON.VertexData();
  40933. vertexData.indices = [];
  40934. var indices = this.getIndices();
  40935. if (indices) {
  40936. for (var index = 0; index < indices.length; index++) {
  40937. vertexData.indices.push(indices[index]);
  40938. }
  40939. }
  40940. var updatable = false;
  40941. var stopChecking = false;
  40942. var kind;
  40943. for (kind in this._vertexBuffers) {
  40944. // using slice() to make a copy of the array and not just reference it
  40945. var data = this.getVerticesData(kind);
  40946. if (data instanceof Float32Array) {
  40947. vertexData.set(new Float32Array(data), kind);
  40948. }
  40949. else {
  40950. vertexData.set(data.slice(0), kind);
  40951. }
  40952. if (!stopChecking) {
  40953. var vb = this.getVertexBuffer(kind);
  40954. if (vb) {
  40955. updatable = vb.isUpdatable();
  40956. stopChecking = !updatable;
  40957. }
  40958. }
  40959. }
  40960. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40961. geometry.delayLoadState = this.delayLoadState;
  40962. geometry.delayLoadingFile = this.delayLoadingFile;
  40963. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40964. for (kind in this._delayInfo) {
  40965. geometry._delayInfo = geometry._delayInfo || [];
  40966. geometry._delayInfo.push(kind);
  40967. }
  40968. // Bounding info
  40969. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40970. return geometry;
  40971. };
  40972. /**
  40973. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40974. * @return a JSON representation of the current geometry data (without the vertices data)
  40975. */
  40976. Geometry.prototype.serialize = function () {
  40977. var serializationObject = {};
  40978. serializationObject.id = this.id;
  40979. serializationObject.updatable = this._updatable;
  40980. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40981. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40982. }
  40983. return serializationObject;
  40984. };
  40985. Geometry.prototype.toNumberArray = function (origin) {
  40986. if (Array.isArray(origin)) {
  40987. return origin;
  40988. }
  40989. else {
  40990. return Array.prototype.slice.call(origin);
  40991. }
  40992. };
  40993. /**
  40994. * Serialize all vertices data into a JSON oject
  40995. * @returns a JSON representation of the current geometry data
  40996. */
  40997. Geometry.prototype.serializeVerticeData = function () {
  40998. var serializationObject = this.serialize();
  40999. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41000. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41001. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41002. serializationObject.positions._updatable = true;
  41003. }
  41004. }
  41005. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41006. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41007. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41008. serializationObject.normals._updatable = true;
  41009. }
  41010. }
  41011. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41012. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41013. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41014. serializationObject.tangets._updatable = true;
  41015. }
  41016. }
  41017. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41018. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41019. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41020. serializationObject.uvs._updatable = true;
  41021. }
  41022. }
  41023. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41024. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41025. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41026. serializationObject.uv2s._updatable = true;
  41027. }
  41028. }
  41029. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41030. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41031. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41032. serializationObject.uv3s._updatable = true;
  41033. }
  41034. }
  41035. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41036. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41037. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41038. serializationObject.uv4s._updatable = true;
  41039. }
  41040. }
  41041. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41042. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41043. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41044. serializationObject.uv5s._updatable = true;
  41045. }
  41046. }
  41047. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41048. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41049. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41050. serializationObject.uv6s._updatable = true;
  41051. }
  41052. }
  41053. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41054. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41055. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41056. serializationObject.colors._updatable = true;
  41057. }
  41058. }
  41059. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41060. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41061. serializationObject.matricesIndices._isExpanded = true;
  41062. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41063. serializationObject.matricesIndices._updatable = true;
  41064. }
  41065. }
  41066. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41067. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41068. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41069. serializationObject.matricesWeights._updatable = true;
  41070. }
  41071. }
  41072. serializationObject.indices = this.toNumberArray(this.getIndices());
  41073. return serializationObject;
  41074. };
  41075. // Statics
  41076. /**
  41077. * Extracts a clone of a mesh geometry
  41078. * @param mesh defines the source mesh
  41079. * @param id defines the unique ID of the new geometry object
  41080. * @returns the new geometry object
  41081. */
  41082. Geometry.ExtractFromMesh = function (mesh, id) {
  41083. var geometry = mesh._geometry;
  41084. if (!geometry) {
  41085. return null;
  41086. }
  41087. return geometry.copy(id);
  41088. };
  41089. /**
  41090. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41091. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41092. * Be aware Math.random() could cause collisions, but:
  41093. * "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"
  41094. * @returns a string containing a new GUID
  41095. */
  41096. Geometry.RandomId = function () {
  41097. return BABYLON.Tools.RandomId();
  41098. };
  41099. /** @hidden */
  41100. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41101. var scene = mesh.getScene();
  41102. // Geometry
  41103. var geometryId = parsedGeometry.geometryId;
  41104. if (geometryId) {
  41105. var geometry = scene.getGeometryByID(geometryId);
  41106. if (geometry) {
  41107. geometry.applyToMesh(mesh);
  41108. }
  41109. }
  41110. else if (parsedGeometry instanceof ArrayBuffer) {
  41111. var binaryInfo = mesh._binaryInfo;
  41112. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41113. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41114. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41115. }
  41116. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41117. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41118. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41119. }
  41120. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41121. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41122. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41123. }
  41124. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41125. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41126. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41127. }
  41128. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41129. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41130. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41131. }
  41132. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41133. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41134. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41135. }
  41136. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41137. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41138. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41139. }
  41140. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41141. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41142. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41143. }
  41144. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41145. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41146. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41147. }
  41148. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41149. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41150. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41151. }
  41152. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41153. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41154. var floatIndices = [];
  41155. for (var i = 0; i < matricesIndicesData.length; i++) {
  41156. var index = matricesIndicesData[i];
  41157. floatIndices.push(index & 0x000000FF);
  41158. floatIndices.push((index & 0x0000FF00) >> 8);
  41159. floatIndices.push((index & 0x00FF0000) >> 16);
  41160. floatIndices.push(index >> 24);
  41161. }
  41162. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41163. }
  41164. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41165. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41166. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41167. }
  41168. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41169. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41170. mesh.setIndices(indicesData, null);
  41171. }
  41172. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41173. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41174. mesh.subMeshes = [];
  41175. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41176. var materialIndex = subMeshesData[(i * 5) + 0];
  41177. var verticesStart = subMeshesData[(i * 5) + 1];
  41178. var verticesCount = subMeshesData[(i * 5) + 2];
  41179. var indexStart = subMeshesData[(i * 5) + 3];
  41180. var indexCount = subMeshesData[(i * 5) + 4];
  41181. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41182. }
  41183. }
  41184. }
  41185. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41186. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41187. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41188. if (parsedGeometry.tangents) {
  41189. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41190. }
  41191. if (parsedGeometry.uvs) {
  41192. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41193. }
  41194. if (parsedGeometry.uvs2) {
  41195. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41196. }
  41197. if (parsedGeometry.uvs3) {
  41198. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41199. }
  41200. if (parsedGeometry.uvs4) {
  41201. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41202. }
  41203. if (parsedGeometry.uvs5) {
  41204. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41205. }
  41206. if (parsedGeometry.uvs6) {
  41207. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41208. }
  41209. if (parsedGeometry.colors) {
  41210. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41211. }
  41212. if (parsedGeometry.matricesIndices) {
  41213. if (!parsedGeometry.matricesIndices._isExpanded) {
  41214. var floatIndices = [];
  41215. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41216. var matricesIndex = parsedGeometry.matricesIndices[i];
  41217. floatIndices.push(matricesIndex & 0x000000FF);
  41218. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41219. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41220. floatIndices.push(matricesIndex >> 24);
  41221. }
  41222. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41223. }
  41224. else {
  41225. delete parsedGeometry.matricesIndices._isExpanded;
  41226. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41227. }
  41228. }
  41229. if (parsedGeometry.matricesIndicesExtra) {
  41230. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41231. var floatIndices = [];
  41232. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41233. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41234. floatIndices.push(matricesIndex & 0x000000FF);
  41235. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41236. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41237. floatIndices.push(matricesIndex >> 24);
  41238. }
  41239. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41240. }
  41241. else {
  41242. delete parsedGeometry.matricesIndices._isExpanded;
  41243. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41244. }
  41245. }
  41246. if (parsedGeometry.matricesWeights) {
  41247. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41248. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41249. }
  41250. if (parsedGeometry.matricesWeightsExtra) {
  41251. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41252. }
  41253. mesh.setIndices(parsedGeometry.indices, null);
  41254. }
  41255. // SubMeshes
  41256. if (parsedGeometry.subMeshes) {
  41257. mesh.subMeshes = [];
  41258. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41259. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41260. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41261. }
  41262. }
  41263. // Flat shading
  41264. if (mesh._shouldGenerateFlatShading) {
  41265. mesh.convertToFlatShadedMesh();
  41266. delete mesh._shouldGenerateFlatShading;
  41267. }
  41268. // Update
  41269. mesh.computeWorldMatrix(true);
  41270. scene.onMeshImportedObservable.notifyObservers(mesh);
  41271. };
  41272. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41273. var epsilon = 1e-3;
  41274. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41275. return;
  41276. }
  41277. var noInfluenceBoneIndex = 0.0;
  41278. if (parsedGeometry.skeletonId > -1) {
  41279. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41280. if (!skeleton) {
  41281. return;
  41282. }
  41283. noInfluenceBoneIndex = skeleton.bones.length;
  41284. }
  41285. else {
  41286. return;
  41287. }
  41288. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41289. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41290. var matricesWeights = parsedGeometry.matricesWeights;
  41291. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41292. var influencers = parsedGeometry.numBoneInfluencer;
  41293. var size = matricesWeights.length;
  41294. for (var i = 0; i < size; i += 4) {
  41295. var weight = 0.0;
  41296. var firstZeroWeight = -1;
  41297. for (var j = 0; j < 4; j++) {
  41298. var w = matricesWeights[i + j];
  41299. weight += w;
  41300. if (w < epsilon && firstZeroWeight < 0) {
  41301. firstZeroWeight = j;
  41302. }
  41303. }
  41304. if (matricesWeightsExtra) {
  41305. for (var j = 0; j < 4; j++) {
  41306. var w = matricesWeightsExtra[i + j];
  41307. weight += w;
  41308. if (w < epsilon && firstZeroWeight < 0) {
  41309. firstZeroWeight = j + 4;
  41310. }
  41311. }
  41312. }
  41313. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41314. firstZeroWeight = influencers - 1;
  41315. }
  41316. if (weight > epsilon) {
  41317. var mweight = 1.0 / weight;
  41318. for (var j = 0; j < 4; j++) {
  41319. matricesWeights[i + j] *= mweight;
  41320. }
  41321. if (matricesWeightsExtra) {
  41322. for (var j = 0; j < 4; j++) {
  41323. matricesWeightsExtra[i + j] *= mweight;
  41324. }
  41325. }
  41326. }
  41327. else {
  41328. if (firstZeroWeight >= 4) {
  41329. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41330. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41331. }
  41332. else {
  41333. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41334. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41335. }
  41336. }
  41337. }
  41338. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41339. if (parsedGeometry.matricesWeightsExtra) {
  41340. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41341. }
  41342. };
  41343. /**
  41344. * Create a new geometry from persisted data (Using .babylon file format)
  41345. * @param parsedVertexData defines the persisted data
  41346. * @param scene defines the hosting scene
  41347. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41348. * @returns the new geometry object
  41349. */
  41350. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41351. if (scene.getGeometryByID(parsedVertexData.id)) {
  41352. return null; // null since geometry could be something else than a box...
  41353. }
  41354. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41355. if (BABYLON.Tags) {
  41356. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41357. }
  41358. if (parsedVertexData.delayLoadingFile) {
  41359. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41360. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41361. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41362. geometry._delayInfo = [];
  41363. if (parsedVertexData.hasUVs) {
  41364. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41365. }
  41366. if (parsedVertexData.hasUVs2) {
  41367. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41368. }
  41369. if (parsedVertexData.hasUVs3) {
  41370. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41371. }
  41372. if (parsedVertexData.hasUVs4) {
  41373. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41374. }
  41375. if (parsedVertexData.hasUVs5) {
  41376. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41377. }
  41378. if (parsedVertexData.hasUVs6) {
  41379. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41380. }
  41381. if (parsedVertexData.hasColors) {
  41382. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41383. }
  41384. if (parsedVertexData.hasMatricesIndices) {
  41385. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41386. }
  41387. if (parsedVertexData.hasMatricesWeights) {
  41388. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41389. }
  41390. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41391. }
  41392. else {
  41393. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41394. }
  41395. scene.pushGeometry(geometry, true);
  41396. return geometry;
  41397. };
  41398. return Geometry;
  41399. }());
  41400. BABYLON.Geometry = Geometry;
  41401. // Primitives
  41402. /// Abstract class
  41403. /**
  41404. * Abstract class used to provide common services for all typed geometries
  41405. * @hidden
  41406. */
  41407. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41408. __extends(_PrimitiveGeometry, _super);
  41409. /**
  41410. * Creates a new typed geometry
  41411. * @param id defines the unique ID of the geometry
  41412. * @param scene defines the hosting scene
  41413. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41414. * @param mesh defines the hosting mesh (can be null)
  41415. */
  41416. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41417. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41418. if (mesh === void 0) { mesh = null; }
  41419. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41420. _this._canBeRegenerated = _canBeRegenerated;
  41421. _this._beingRegenerated = true;
  41422. _this.regenerate();
  41423. _this._beingRegenerated = false;
  41424. return _this;
  41425. }
  41426. /**
  41427. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41428. * @returns true if the geometry can be regenerated
  41429. */
  41430. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41431. return this._canBeRegenerated;
  41432. };
  41433. /**
  41434. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41435. */
  41436. _PrimitiveGeometry.prototype.regenerate = function () {
  41437. if (!this._canBeRegenerated) {
  41438. return;
  41439. }
  41440. this._beingRegenerated = true;
  41441. this.setAllVerticesData(this._regenerateVertexData(), false);
  41442. this._beingRegenerated = false;
  41443. };
  41444. /**
  41445. * Clone the geometry
  41446. * @param id defines the unique ID of the new geometry
  41447. * @returns the new geometry
  41448. */
  41449. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41450. return _super.prototype.copy.call(this, id);
  41451. };
  41452. // overrides
  41453. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41454. if (!this._beingRegenerated) {
  41455. return;
  41456. }
  41457. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41458. };
  41459. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41460. if (!this._beingRegenerated) {
  41461. return;
  41462. }
  41463. _super.prototype.setVerticesData.call(this, kind, data, false);
  41464. };
  41465. // to override
  41466. /** @hidden */
  41467. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41468. throw new Error("Abstract method");
  41469. };
  41470. _PrimitiveGeometry.prototype.copy = function (id) {
  41471. throw new Error("Must be overriden in sub-classes.");
  41472. };
  41473. _PrimitiveGeometry.prototype.serialize = function () {
  41474. var serializationObject = _super.prototype.serialize.call(this);
  41475. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41476. return serializationObject;
  41477. };
  41478. return _PrimitiveGeometry;
  41479. }(Geometry));
  41480. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41481. /**
  41482. * Creates a ribbon geometry
  41483. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41484. */
  41485. var RibbonGeometry = /** @class */ (function (_super) {
  41486. __extends(RibbonGeometry, _super);
  41487. /**
  41488. * Creates a ribbon geometry
  41489. * @param id defines the unique ID of the geometry
  41490. * @param scene defines the hosting scene
  41491. * @param pathArray defines the array of paths to use
  41492. * @param closeArray defines if the last path and the first path must be joined
  41493. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41494. * @param offset defines the offset between points
  41495. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41496. * @param mesh defines the hosting mesh (can be null)
  41497. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41498. */
  41499. function RibbonGeometry(id, scene,
  41500. /**
  41501. * Defines the array of paths to use
  41502. */
  41503. pathArray,
  41504. /**
  41505. * Defines if the last and first points of each path in your pathArray must be joined
  41506. */
  41507. closeArray,
  41508. /**
  41509. * Defines if the last and first points of each path in your pathArray must be joined
  41510. */
  41511. closePath,
  41512. /**
  41513. * Defines the offset between points
  41514. */
  41515. offset, canBeRegenerated, mesh,
  41516. /**
  41517. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41518. */
  41519. side) {
  41520. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41521. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41522. _this.pathArray = pathArray;
  41523. _this.closeArray = closeArray;
  41524. _this.closePath = closePath;
  41525. _this.offset = offset;
  41526. _this.side = side;
  41527. return _this;
  41528. }
  41529. /** @hidden */
  41530. RibbonGeometry.prototype._regenerateVertexData = function () {
  41531. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41532. };
  41533. RibbonGeometry.prototype.copy = function (id) {
  41534. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41535. };
  41536. return RibbonGeometry;
  41537. }(_PrimitiveGeometry));
  41538. BABYLON.RibbonGeometry = RibbonGeometry;
  41539. /**
  41540. * Creates a box geometry
  41541. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41542. */
  41543. var BoxGeometry = /** @class */ (function (_super) {
  41544. __extends(BoxGeometry, _super);
  41545. /**
  41546. * Creates a box geometry
  41547. * @param id defines the unique ID of the geometry
  41548. * @param scene defines the hosting scene
  41549. * @param size defines the zise of the box (width, height and depth are the same)
  41550. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41551. * @param mesh defines the hosting mesh (can be null)
  41552. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41553. */
  41554. function BoxGeometry(id, scene,
  41555. /**
  41556. * Defines the zise of the box (width, height and depth are the same)
  41557. */
  41558. size, canBeRegenerated, mesh,
  41559. /**
  41560. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41561. */
  41562. side) {
  41563. if (mesh === void 0) { mesh = null; }
  41564. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41565. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41566. _this.size = size;
  41567. _this.side = side;
  41568. return _this;
  41569. }
  41570. /** @hidden */
  41571. BoxGeometry.prototype._regenerateVertexData = function () {
  41572. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41573. };
  41574. BoxGeometry.prototype.copy = function (id) {
  41575. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41576. };
  41577. BoxGeometry.prototype.serialize = function () {
  41578. var serializationObject = _super.prototype.serialize.call(this);
  41579. serializationObject.size = this.size;
  41580. return serializationObject;
  41581. };
  41582. BoxGeometry.Parse = function (parsedBox, scene) {
  41583. if (scene.getGeometryByID(parsedBox.id)) {
  41584. return null; // null since geometry could be something else than a box...
  41585. }
  41586. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41587. if (BABYLON.Tags) {
  41588. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41589. }
  41590. scene.pushGeometry(box, true);
  41591. return box;
  41592. };
  41593. return BoxGeometry;
  41594. }(_PrimitiveGeometry));
  41595. BABYLON.BoxGeometry = BoxGeometry;
  41596. /**
  41597. * Creates a sphere geometry
  41598. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41599. */
  41600. var SphereGeometry = /** @class */ (function (_super) {
  41601. __extends(SphereGeometry, _super);
  41602. /**
  41603. * Create a new sphere geometry
  41604. * @param id defines the unique ID of the geometry
  41605. * @param scene defines the hosting scene
  41606. * @param segments defines the number of segments to use to create the sphere
  41607. * @param diameter defines the diameter of the sphere
  41608. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41609. * @param mesh defines the hosting mesh (can be null)
  41610. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41611. */
  41612. function SphereGeometry(id, scene,
  41613. /**
  41614. * Defines the number of segments to use to create the sphere
  41615. */
  41616. segments,
  41617. /**
  41618. * Defines the diameter of the sphere
  41619. */
  41620. diameter, canBeRegenerated, mesh,
  41621. /**
  41622. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41623. */
  41624. side) {
  41625. if (mesh === void 0) { mesh = null; }
  41626. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41627. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41628. _this.segments = segments;
  41629. _this.diameter = diameter;
  41630. _this.side = side;
  41631. return _this;
  41632. }
  41633. /** @hidden */
  41634. SphereGeometry.prototype._regenerateVertexData = function () {
  41635. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41636. };
  41637. SphereGeometry.prototype.copy = function (id) {
  41638. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41639. };
  41640. SphereGeometry.prototype.serialize = function () {
  41641. var serializationObject = _super.prototype.serialize.call(this);
  41642. serializationObject.segments = this.segments;
  41643. serializationObject.diameter = this.diameter;
  41644. return serializationObject;
  41645. };
  41646. SphereGeometry.Parse = function (parsedSphere, scene) {
  41647. if (scene.getGeometryByID(parsedSphere.id)) {
  41648. return null; // null since geometry could be something else than a sphere...
  41649. }
  41650. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41651. if (BABYLON.Tags) {
  41652. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41653. }
  41654. scene.pushGeometry(sphere, true);
  41655. return sphere;
  41656. };
  41657. return SphereGeometry;
  41658. }(_PrimitiveGeometry));
  41659. BABYLON.SphereGeometry = SphereGeometry;
  41660. /**
  41661. * Creates a disc geometry
  41662. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41663. */
  41664. var DiscGeometry = /** @class */ (function (_super) {
  41665. __extends(DiscGeometry, _super);
  41666. /**
  41667. * Creates a new disc geometry
  41668. * @param id defines the unique ID of the geometry
  41669. * @param scene defines the hosting scene
  41670. * @param radius defines the radius of the disc
  41671. * @param tessellation defines the tesselation factor to apply to the disc
  41672. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41673. * @param mesh defines the hosting mesh (can be null)
  41674. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41675. */
  41676. function DiscGeometry(id, scene,
  41677. /**
  41678. * Defines the radius of the disc
  41679. */
  41680. radius,
  41681. /**
  41682. * Defines the tesselation factor to apply to the disc
  41683. */
  41684. tessellation, canBeRegenerated, mesh,
  41685. /**
  41686. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41687. */
  41688. side) {
  41689. if (mesh === void 0) { mesh = null; }
  41690. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41691. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41692. _this.radius = radius;
  41693. _this.tessellation = tessellation;
  41694. _this.side = side;
  41695. return _this;
  41696. }
  41697. /** @hidden */
  41698. DiscGeometry.prototype._regenerateVertexData = function () {
  41699. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41700. };
  41701. DiscGeometry.prototype.copy = function (id) {
  41702. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41703. };
  41704. return DiscGeometry;
  41705. }(_PrimitiveGeometry));
  41706. BABYLON.DiscGeometry = DiscGeometry;
  41707. /**
  41708. * Creates a new cylinder geometry
  41709. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41710. */
  41711. var CylinderGeometry = /** @class */ (function (_super) {
  41712. __extends(CylinderGeometry, _super);
  41713. /**
  41714. * Creates a new cylinder geometry
  41715. * @param id defines the unique ID of the geometry
  41716. * @param scene defines the hosting scene
  41717. * @param height defines the height of the cylinder
  41718. * @param diameterTop defines the diameter of the cylinder's top cap
  41719. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41720. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41721. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41722. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41723. * @param mesh defines the hosting mesh (can be null)
  41724. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41725. */
  41726. function CylinderGeometry(id, scene,
  41727. /**
  41728. * Defines the height of the cylinder
  41729. */
  41730. height,
  41731. /**
  41732. * Defines the diameter of the cylinder's top cap
  41733. */
  41734. diameterTop,
  41735. /**
  41736. * Defines the diameter of the cylinder's bottom cap
  41737. */
  41738. diameterBottom,
  41739. /**
  41740. * Defines the tessellation factor to apply to the cylinder
  41741. */
  41742. tessellation,
  41743. /**
  41744. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41745. */
  41746. subdivisions, canBeRegenerated, mesh,
  41747. /**
  41748. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41749. */
  41750. side) {
  41751. if (subdivisions === void 0) { subdivisions = 1; }
  41752. if (mesh === void 0) { mesh = null; }
  41753. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41754. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41755. _this.height = height;
  41756. _this.diameterTop = diameterTop;
  41757. _this.diameterBottom = diameterBottom;
  41758. _this.tessellation = tessellation;
  41759. _this.subdivisions = subdivisions;
  41760. _this.side = side;
  41761. return _this;
  41762. }
  41763. /** @hidden */
  41764. CylinderGeometry.prototype._regenerateVertexData = function () {
  41765. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41766. };
  41767. CylinderGeometry.prototype.copy = function (id) {
  41768. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41769. };
  41770. CylinderGeometry.prototype.serialize = function () {
  41771. var serializationObject = _super.prototype.serialize.call(this);
  41772. serializationObject.height = this.height;
  41773. serializationObject.diameterTop = this.diameterTop;
  41774. serializationObject.diameterBottom = this.diameterBottom;
  41775. serializationObject.tessellation = this.tessellation;
  41776. return serializationObject;
  41777. };
  41778. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41779. if (scene.getGeometryByID(parsedCylinder.id)) {
  41780. return null; // null since geometry could be something else than a cylinder...
  41781. }
  41782. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41783. if (BABYLON.Tags) {
  41784. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41785. }
  41786. scene.pushGeometry(cylinder, true);
  41787. return cylinder;
  41788. };
  41789. return CylinderGeometry;
  41790. }(_PrimitiveGeometry));
  41791. BABYLON.CylinderGeometry = CylinderGeometry;
  41792. /**
  41793. * Creates a new torus geometry
  41794. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41795. */
  41796. var TorusGeometry = /** @class */ (function (_super) {
  41797. __extends(TorusGeometry, _super);
  41798. /**
  41799. * Creates a new torus geometry
  41800. * @param id defines the unique ID of the geometry
  41801. * @param scene defines the hosting scene
  41802. * @param diameter defines the diameter of the torus
  41803. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41804. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41805. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41806. * @param mesh defines the hosting mesh (can be null)
  41807. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41808. */
  41809. function TorusGeometry(id, scene,
  41810. /**
  41811. * Defines the diameter of the torus
  41812. */
  41813. diameter,
  41814. /**
  41815. * Defines the thickness of the torus (ie. internal diameter)
  41816. */
  41817. thickness,
  41818. /**
  41819. * Defines the tesselation factor to apply to the torus
  41820. */
  41821. tessellation, canBeRegenerated, mesh,
  41822. /**
  41823. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41824. */
  41825. side) {
  41826. if (mesh === void 0) { mesh = null; }
  41827. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41828. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41829. _this.diameter = diameter;
  41830. _this.thickness = thickness;
  41831. _this.tessellation = tessellation;
  41832. _this.side = side;
  41833. return _this;
  41834. }
  41835. /** @hidden */
  41836. TorusGeometry.prototype._regenerateVertexData = function () {
  41837. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41838. };
  41839. TorusGeometry.prototype.copy = function (id) {
  41840. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41841. };
  41842. TorusGeometry.prototype.serialize = function () {
  41843. var serializationObject = _super.prototype.serialize.call(this);
  41844. serializationObject.diameter = this.diameter;
  41845. serializationObject.thickness = this.thickness;
  41846. serializationObject.tessellation = this.tessellation;
  41847. return serializationObject;
  41848. };
  41849. TorusGeometry.Parse = function (parsedTorus, scene) {
  41850. if (scene.getGeometryByID(parsedTorus.id)) {
  41851. return null; // null since geometry could be something else than a torus...
  41852. }
  41853. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41854. if (BABYLON.Tags) {
  41855. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41856. }
  41857. scene.pushGeometry(torus, true);
  41858. return torus;
  41859. };
  41860. return TorusGeometry;
  41861. }(_PrimitiveGeometry));
  41862. BABYLON.TorusGeometry = TorusGeometry;
  41863. /**
  41864. * Creates a new ground geometry
  41865. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41866. */
  41867. var GroundGeometry = /** @class */ (function (_super) {
  41868. __extends(GroundGeometry, _super);
  41869. /**
  41870. * Creates a new ground geometry
  41871. * @param id defines the unique ID of the geometry
  41872. * @param scene defines the hosting scene
  41873. * @param width defines the width of the ground
  41874. * @param height defines the height of the ground
  41875. * @param subdivisions defines the subdivisions to apply to the ground
  41876. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41877. * @param mesh defines the hosting mesh (can be null)
  41878. */
  41879. function GroundGeometry(id, scene,
  41880. /**
  41881. * Defines the width of the ground
  41882. */
  41883. width,
  41884. /**
  41885. * Defines the height of the ground
  41886. */
  41887. height,
  41888. /**
  41889. * Defines the subdivisions to apply to the ground
  41890. */
  41891. subdivisions, canBeRegenerated, mesh) {
  41892. if (mesh === void 0) { mesh = null; }
  41893. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41894. _this.width = width;
  41895. _this.height = height;
  41896. _this.subdivisions = subdivisions;
  41897. return _this;
  41898. }
  41899. /** @hidden */
  41900. GroundGeometry.prototype._regenerateVertexData = function () {
  41901. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41902. };
  41903. GroundGeometry.prototype.copy = function (id) {
  41904. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41905. };
  41906. GroundGeometry.prototype.serialize = function () {
  41907. var serializationObject = _super.prototype.serialize.call(this);
  41908. serializationObject.width = this.width;
  41909. serializationObject.height = this.height;
  41910. serializationObject.subdivisions = this.subdivisions;
  41911. return serializationObject;
  41912. };
  41913. GroundGeometry.Parse = function (parsedGround, scene) {
  41914. if (scene.getGeometryByID(parsedGround.id)) {
  41915. return null; // null since geometry could be something else than a ground...
  41916. }
  41917. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41918. if (BABYLON.Tags) {
  41919. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41920. }
  41921. scene.pushGeometry(ground, true);
  41922. return ground;
  41923. };
  41924. return GroundGeometry;
  41925. }(_PrimitiveGeometry));
  41926. BABYLON.GroundGeometry = GroundGeometry;
  41927. /**
  41928. * Creates a tiled ground geometry
  41929. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41930. */
  41931. var TiledGroundGeometry = /** @class */ (function (_super) {
  41932. __extends(TiledGroundGeometry, _super);
  41933. /**
  41934. * Creates a tiled ground geometry
  41935. * @param id defines the unique ID of the geometry
  41936. * @param scene defines the hosting scene
  41937. * @param xmin defines the minimum value on X axis
  41938. * @param zmin defines the minimum value on Z axis
  41939. * @param xmax defines the maximum value on X axis
  41940. * @param zmax defines the maximum value on Z axis
  41941. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41942. * @param precision defines the precision to use when computing the tiles
  41943. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41944. * @param mesh defines the hosting mesh (can be null)
  41945. */
  41946. function TiledGroundGeometry(id, scene,
  41947. /**
  41948. * Defines the minimum value on X axis
  41949. */
  41950. xmin,
  41951. /**
  41952. * Defines the minimum value on Z axis
  41953. */
  41954. zmin,
  41955. /**
  41956. * Defines the maximum value on X axis
  41957. */
  41958. xmax,
  41959. /**
  41960. * Defines the maximum value on Z axis
  41961. */
  41962. zmax,
  41963. /**
  41964. * Defines the subdivisions to apply to the ground
  41965. */
  41966. subdivisions,
  41967. /**
  41968. * Defines the precision to use when computing the tiles
  41969. */
  41970. precision, canBeRegenerated, mesh) {
  41971. if (mesh === void 0) { mesh = null; }
  41972. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41973. _this.xmin = xmin;
  41974. _this.zmin = zmin;
  41975. _this.xmax = xmax;
  41976. _this.zmax = zmax;
  41977. _this.subdivisions = subdivisions;
  41978. _this.precision = precision;
  41979. return _this;
  41980. }
  41981. /** @hidden */
  41982. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41983. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41984. };
  41985. TiledGroundGeometry.prototype.copy = function (id) {
  41986. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41987. };
  41988. return TiledGroundGeometry;
  41989. }(_PrimitiveGeometry));
  41990. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41991. /**
  41992. * Creates a plane geometry
  41993. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41994. */
  41995. var PlaneGeometry = /** @class */ (function (_super) {
  41996. __extends(PlaneGeometry, _super);
  41997. /**
  41998. * Creates a plane geometry
  41999. * @param id defines the unique ID of the geometry
  42000. * @param scene defines the hosting scene
  42001. * @param size defines the size of the plane (width === height)
  42002. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42003. * @param mesh defines the hosting mesh (can be null)
  42004. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42005. */
  42006. function PlaneGeometry(id, scene,
  42007. /**
  42008. * Defines the size of the plane (width === height)
  42009. */
  42010. size, canBeRegenerated, mesh,
  42011. /**
  42012. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42013. */
  42014. side) {
  42015. if (mesh === void 0) { mesh = null; }
  42016. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42017. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42018. _this.size = size;
  42019. _this.side = side;
  42020. return _this;
  42021. }
  42022. /** @hidden */
  42023. PlaneGeometry.prototype._regenerateVertexData = function () {
  42024. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42025. };
  42026. PlaneGeometry.prototype.copy = function (id) {
  42027. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42028. };
  42029. PlaneGeometry.prototype.serialize = function () {
  42030. var serializationObject = _super.prototype.serialize.call(this);
  42031. serializationObject.size = this.size;
  42032. return serializationObject;
  42033. };
  42034. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42035. if (scene.getGeometryByID(parsedPlane.id)) {
  42036. return null; // null since geometry could be something else than a ground...
  42037. }
  42038. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42039. if (BABYLON.Tags) {
  42040. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42041. }
  42042. scene.pushGeometry(plane, true);
  42043. return plane;
  42044. };
  42045. return PlaneGeometry;
  42046. }(_PrimitiveGeometry));
  42047. BABYLON.PlaneGeometry = PlaneGeometry;
  42048. /**
  42049. * Creates a torus knot geometry
  42050. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42051. */
  42052. var TorusKnotGeometry = /** @class */ (function (_super) {
  42053. __extends(TorusKnotGeometry, _super);
  42054. /**
  42055. * Creates a torus knot geometry
  42056. * @param id defines the unique ID of the geometry
  42057. * @param scene defines the hosting scene
  42058. * @param radius defines the radius of the torus knot
  42059. * @param tube defines the thickness of the torus knot tube
  42060. * @param radialSegments defines the number of radial segments
  42061. * @param tubularSegments defines the number of tubular segments
  42062. * @param p defines the first number of windings
  42063. * @param q defines the second number of windings
  42064. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42065. * @param mesh defines the hosting mesh (can be null)
  42066. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42067. */
  42068. function TorusKnotGeometry(id, scene,
  42069. /**
  42070. * Defines the radius of the torus knot
  42071. */
  42072. radius,
  42073. /**
  42074. * Defines the thickness of the torus knot tube
  42075. */
  42076. tube,
  42077. /**
  42078. * Defines the number of radial segments
  42079. */
  42080. radialSegments,
  42081. /**
  42082. * Defines the number of tubular segments
  42083. */
  42084. tubularSegments,
  42085. /**
  42086. * Defines the first number of windings
  42087. */
  42088. p,
  42089. /**
  42090. * Defines the second number of windings
  42091. */
  42092. q, canBeRegenerated, mesh,
  42093. /**
  42094. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42095. */
  42096. side) {
  42097. if (mesh === void 0) { mesh = null; }
  42098. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42099. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42100. _this.radius = radius;
  42101. _this.tube = tube;
  42102. _this.radialSegments = radialSegments;
  42103. _this.tubularSegments = tubularSegments;
  42104. _this.p = p;
  42105. _this.q = q;
  42106. _this.side = side;
  42107. return _this;
  42108. }
  42109. /** @hidden */
  42110. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42111. 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 });
  42112. };
  42113. TorusKnotGeometry.prototype.copy = function (id) {
  42114. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42115. };
  42116. TorusKnotGeometry.prototype.serialize = function () {
  42117. var serializationObject = _super.prototype.serialize.call(this);
  42118. serializationObject.radius = this.radius;
  42119. serializationObject.tube = this.tube;
  42120. serializationObject.radialSegments = this.radialSegments;
  42121. serializationObject.tubularSegments = this.tubularSegments;
  42122. serializationObject.p = this.p;
  42123. serializationObject.q = this.q;
  42124. return serializationObject;
  42125. };
  42126. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42127. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42128. return null; // null since geometry could be something else than a ground...
  42129. }
  42130. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42131. if (BABYLON.Tags) {
  42132. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42133. }
  42134. scene.pushGeometry(torusKnot, true);
  42135. return torusKnot;
  42136. };
  42137. return TorusKnotGeometry;
  42138. }(_PrimitiveGeometry));
  42139. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42140. //}
  42141. })(BABYLON || (BABYLON = {}));
  42142. //# sourceMappingURL=babylon.geometry.js.map
  42143. var BABYLON;
  42144. (function (BABYLON) {
  42145. /**
  42146. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42147. */
  42148. var PerformanceMonitor = /** @class */ (function () {
  42149. /**
  42150. * constructor
  42151. * @param frameSampleSize The number of samples required to saturate the sliding window
  42152. */
  42153. function PerformanceMonitor(frameSampleSize) {
  42154. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42155. this._enabled = true;
  42156. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42157. }
  42158. /**
  42159. * Samples current frame
  42160. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42161. */
  42162. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42163. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42164. if (!this._enabled) {
  42165. return;
  42166. }
  42167. if (this._lastFrameTimeMs != null) {
  42168. var dt = timeMs - this._lastFrameTimeMs;
  42169. this._rollingFrameTime.add(dt);
  42170. }
  42171. this._lastFrameTimeMs = timeMs;
  42172. };
  42173. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42174. /**
  42175. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42176. */
  42177. get: function () {
  42178. return this._rollingFrameTime.average;
  42179. },
  42180. enumerable: true,
  42181. configurable: true
  42182. });
  42183. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42184. /**
  42185. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42186. */
  42187. get: function () {
  42188. return this._rollingFrameTime.variance;
  42189. },
  42190. enumerable: true,
  42191. configurable: true
  42192. });
  42193. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42194. /**
  42195. * Returns the frame time of the most recent frame
  42196. */
  42197. get: function () {
  42198. return this._rollingFrameTime.history(0);
  42199. },
  42200. enumerable: true,
  42201. configurable: true
  42202. });
  42203. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42204. /**
  42205. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42206. */
  42207. get: function () {
  42208. return 1000.0 / this._rollingFrameTime.average;
  42209. },
  42210. enumerable: true,
  42211. configurable: true
  42212. });
  42213. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42214. /**
  42215. * Returns the average framerate in frames per second using the most recent frame time
  42216. */
  42217. get: function () {
  42218. var history = this._rollingFrameTime.history(0);
  42219. if (history === 0) {
  42220. return 0;
  42221. }
  42222. return 1000.0 / history;
  42223. },
  42224. enumerable: true,
  42225. configurable: true
  42226. });
  42227. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42228. /**
  42229. * Returns true if enough samples have been taken to completely fill the sliding window
  42230. */
  42231. get: function () {
  42232. return this._rollingFrameTime.isSaturated();
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. /**
  42238. * Enables contributions to the sliding window sample set
  42239. */
  42240. PerformanceMonitor.prototype.enable = function () {
  42241. this._enabled = true;
  42242. };
  42243. /**
  42244. * Disables contributions to the sliding window sample set
  42245. * Samples will not be interpolated over the disabled period
  42246. */
  42247. PerformanceMonitor.prototype.disable = function () {
  42248. this._enabled = false;
  42249. //clear last sample to avoid interpolating over the disabled period when next enabled
  42250. this._lastFrameTimeMs = null;
  42251. };
  42252. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42253. /**
  42254. * Returns true if sampling is enabled
  42255. */
  42256. get: function () {
  42257. return this._enabled;
  42258. },
  42259. enumerable: true,
  42260. configurable: true
  42261. });
  42262. /**
  42263. * Resets performance monitor
  42264. */
  42265. PerformanceMonitor.prototype.reset = function () {
  42266. //clear last sample to avoid interpolating over the disabled period when next enabled
  42267. this._lastFrameTimeMs = null;
  42268. //wipe record
  42269. this._rollingFrameTime.reset();
  42270. };
  42271. return PerformanceMonitor;
  42272. }());
  42273. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42274. /**
  42275. * RollingAverage
  42276. *
  42277. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42278. */
  42279. var RollingAverage = /** @class */ (function () {
  42280. /**
  42281. * constructor
  42282. * @param length The number of samples required to saturate the sliding window
  42283. */
  42284. function RollingAverage(length) {
  42285. this._samples = new Array(length);
  42286. this.reset();
  42287. }
  42288. /**
  42289. * Adds a sample to the sample set
  42290. * @param v The sample value
  42291. */
  42292. RollingAverage.prototype.add = function (v) {
  42293. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42294. var delta;
  42295. //we need to check if we've already wrapped round
  42296. if (this.isSaturated()) {
  42297. //remove bottom of stack from mean
  42298. var bottomValue = this._samples[this._pos];
  42299. delta = bottomValue - this.average;
  42300. this.average -= delta / (this._sampleCount - 1);
  42301. this._m2 -= delta * (bottomValue - this.average);
  42302. }
  42303. else {
  42304. this._sampleCount++;
  42305. }
  42306. //add new value to mean
  42307. delta = v - this.average;
  42308. this.average += delta / (this._sampleCount);
  42309. this._m2 += delta * (v - this.average);
  42310. //set the new variance
  42311. this.variance = this._m2 / (this._sampleCount - 1);
  42312. this._samples[this._pos] = v;
  42313. this._pos++;
  42314. this._pos %= this._samples.length; //positive wrap around
  42315. };
  42316. /**
  42317. * Returns previously added values or null if outside of history or outside the sliding window domain
  42318. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42319. * @return Value previously recorded with add() or null if outside of range
  42320. */
  42321. RollingAverage.prototype.history = function (i) {
  42322. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42323. return 0;
  42324. }
  42325. var i0 = this._wrapPosition(this._pos - 1.0);
  42326. return this._samples[this._wrapPosition(i0 - i)];
  42327. };
  42328. /**
  42329. * Returns true if enough samples have been taken to completely fill the sliding window
  42330. * @return true if sample-set saturated
  42331. */
  42332. RollingAverage.prototype.isSaturated = function () {
  42333. return this._sampleCount >= this._samples.length;
  42334. };
  42335. /**
  42336. * Resets the rolling average (equivalent to 0 samples taken so far)
  42337. */
  42338. RollingAverage.prototype.reset = function () {
  42339. this.average = 0;
  42340. this.variance = 0;
  42341. this._sampleCount = 0;
  42342. this._pos = 0;
  42343. this._m2 = 0;
  42344. };
  42345. /**
  42346. * Wraps a value around the sample range boundaries
  42347. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42348. * @return Wrapped position in sample range
  42349. */
  42350. RollingAverage.prototype._wrapPosition = function (i) {
  42351. var max = this._samples.length;
  42352. return ((i % max) + max) % max;
  42353. };
  42354. return RollingAverage;
  42355. }());
  42356. BABYLON.RollingAverage = RollingAverage;
  42357. })(BABYLON || (BABYLON = {}));
  42358. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42359. var BABYLON;
  42360. (function (BABYLON) {
  42361. /**
  42362. * "Static Class" containing the most commonly used helper while dealing with material for
  42363. * rendering purpose.
  42364. *
  42365. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42366. *
  42367. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42368. */
  42369. var MaterialHelper = /** @class */ (function () {
  42370. function MaterialHelper() {
  42371. }
  42372. /**
  42373. * Bind the current view position to an effect.
  42374. * @param effect The effect to be bound
  42375. * @param scene The scene the eyes position is used from
  42376. */
  42377. MaterialHelper.BindEyePosition = function (effect, scene) {
  42378. if (scene._forcedViewPosition) {
  42379. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42380. return;
  42381. }
  42382. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42383. };
  42384. /**
  42385. * Helps preparing the defines values about the UVs in used in the effect.
  42386. * UVs are shared as much as we can accross channels in the shaders.
  42387. * @param texture The texture we are preparing the UVs for
  42388. * @param defines The defines to update
  42389. * @param key The channel key "diffuse", "specular"... used in the shader
  42390. */
  42391. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42392. defines._needUVs = true;
  42393. defines[key] = true;
  42394. if (texture.getTextureMatrix().isIdentity(true)) {
  42395. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42396. if (texture.coordinatesIndex === 0) {
  42397. defines["MAINUV1"] = true;
  42398. }
  42399. else {
  42400. defines["MAINUV2"] = true;
  42401. }
  42402. }
  42403. else {
  42404. defines[key + "DIRECTUV"] = 0;
  42405. }
  42406. };
  42407. /**
  42408. * Binds a texture matrix value to its corrsponding uniform
  42409. * @param texture The texture to bind the matrix for
  42410. * @param uniformBuffer The uniform buffer receivin the data
  42411. * @param key The channel key "diffuse", "specular"... used in the shader
  42412. */
  42413. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42414. var matrix = texture.getTextureMatrix();
  42415. if (!matrix.isIdentity(true)) {
  42416. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42417. }
  42418. };
  42419. /**
  42420. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42421. * @param mesh defines the current mesh
  42422. * @param scene defines the current scene
  42423. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42424. * @param pointsCloud defines if point cloud rendering has to be turned on
  42425. * @param fogEnabled defines if fog has to be turned on
  42426. * @param alphaTest defines if alpha testing has to be turned on
  42427. * @param defines defines the current list of defines
  42428. */
  42429. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42430. if (defines._areMiscDirty) {
  42431. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42432. defines["POINTSIZE"] = pointsCloud;
  42433. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42434. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42435. defines["ALPHATEST"] = alphaTest;
  42436. }
  42437. };
  42438. /**
  42439. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42440. * @param scene defines the current scene
  42441. * @param engine defines the current engine
  42442. * @param defines specifies the list of active defines
  42443. * @param useInstances defines if instances have to be turned on
  42444. * @param useClipPlane defines if clip plane have to be turned on
  42445. */
  42446. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42447. if (useClipPlane === void 0) { useClipPlane = null; }
  42448. var changed = false;
  42449. var useClipPlane1 = false;
  42450. var useClipPlane2 = false;
  42451. var useClipPlane3 = false;
  42452. var useClipPlane4 = false;
  42453. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42454. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42455. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42456. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42457. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42458. defines["CLIPPLANE"] = useClipPlane1;
  42459. changed = true;
  42460. }
  42461. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42462. defines["CLIPPLANE2"] = useClipPlane2;
  42463. changed = true;
  42464. }
  42465. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42466. defines["CLIPPLANE3"] = useClipPlane3;
  42467. changed = true;
  42468. }
  42469. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42470. defines["CLIPPLANE4"] = useClipPlane4;
  42471. changed = true;
  42472. }
  42473. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42474. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42475. changed = true;
  42476. }
  42477. if (defines["INSTANCES"] !== useInstances) {
  42478. defines["INSTANCES"] = useInstances;
  42479. changed = true;
  42480. }
  42481. if (changed) {
  42482. defines.markAsUnprocessed();
  42483. }
  42484. };
  42485. /**
  42486. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42487. * @param mesh The mesh containing the geometry data we will draw
  42488. * @param defines The defines to update
  42489. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42490. * @param useBones Precise whether bones should be used or not (override mesh info)
  42491. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42492. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42493. * @returns false if defines are considered not dirty and have not been checked
  42494. */
  42495. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42496. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42497. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42498. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42499. return false;
  42500. }
  42501. defines._normals = defines._needNormals;
  42502. defines._uvs = defines._needUVs;
  42503. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42504. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42505. defines["TANGENT"] = true;
  42506. }
  42507. if (defines._needUVs) {
  42508. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42509. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42510. }
  42511. else {
  42512. defines["UV1"] = false;
  42513. defines["UV2"] = false;
  42514. }
  42515. if (useVertexColor) {
  42516. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42517. defines["VERTEXCOLOR"] = hasVertexColors;
  42518. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42519. }
  42520. if (useBones) {
  42521. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42522. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42523. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42524. }
  42525. else {
  42526. defines["NUM_BONE_INFLUENCERS"] = 0;
  42527. defines["BonesPerMesh"] = 0;
  42528. }
  42529. }
  42530. if (useMorphTargets) {
  42531. var manager = mesh.morphTargetManager;
  42532. if (manager) {
  42533. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42534. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42535. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42536. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42537. }
  42538. else {
  42539. defines["MORPHTARGETS_TANGENT"] = false;
  42540. defines["MORPHTARGETS_NORMAL"] = false;
  42541. defines["MORPHTARGETS"] = false;
  42542. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42543. }
  42544. }
  42545. return true;
  42546. };
  42547. /**
  42548. * Prepares the defines related to the light information passed in parameter
  42549. * @param scene The scene we are intending to draw
  42550. * @param mesh The mesh the effect is compiling for
  42551. * @param defines The defines to update
  42552. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42553. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42554. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42555. * @returns true if normals will be required for the rest of the effect
  42556. */
  42557. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42558. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42559. if (disableLighting === void 0) { disableLighting = false; }
  42560. if (!defines._areLightsDirty) {
  42561. return defines._needNormals;
  42562. }
  42563. var lightIndex = 0;
  42564. var needNormals = false;
  42565. var needRebuild = false;
  42566. var lightmapMode = false;
  42567. var shadowEnabled = false;
  42568. var specularEnabled = false;
  42569. if (scene.lightsEnabled && !disableLighting) {
  42570. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42571. var light = _a[_i];
  42572. needNormals = true;
  42573. if (defines["LIGHT" + lightIndex] === undefined) {
  42574. needRebuild = true;
  42575. }
  42576. defines["LIGHT" + lightIndex] = true;
  42577. defines["SPOTLIGHT" + lightIndex] = false;
  42578. defines["HEMILIGHT" + lightIndex] = false;
  42579. defines["POINTLIGHT" + lightIndex] = false;
  42580. defines["DIRLIGHT" + lightIndex] = false;
  42581. light.prepareLightSpecificDefines(defines, lightIndex);
  42582. // FallOff.
  42583. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42584. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42585. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42586. switch (light.falloffType) {
  42587. case BABYLON.Light.FALLOFF_GLTF:
  42588. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42589. break;
  42590. case BABYLON.Light.FALLOFF_PHYSICAL:
  42591. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42592. break;
  42593. case BABYLON.Light.FALLOFF_STANDARD:
  42594. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42595. break;
  42596. }
  42597. // Specular
  42598. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42599. specularEnabled = true;
  42600. }
  42601. // Shadows
  42602. defines["SHADOW" + lightIndex] = false;
  42603. defines["SHADOWPCF" + lightIndex] = false;
  42604. defines["SHADOWPCSS" + lightIndex] = false;
  42605. defines["SHADOWPOISSON" + lightIndex] = false;
  42606. defines["SHADOWESM" + lightIndex] = false;
  42607. defines["SHADOWCUBE" + lightIndex] = false;
  42608. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42609. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42610. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42611. var shadowGenerator = light.getShadowGenerator();
  42612. if (shadowGenerator) {
  42613. var shadowMap = shadowGenerator.getShadowMap();
  42614. if (shadowMap) {
  42615. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42616. shadowEnabled = true;
  42617. shadowGenerator.prepareDefines(defines, lightIndex);
  42618. }
  42619. }
  42620. }
  42621. }
  42622. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42623. lightmapMode = true;
  42624. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42625. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42626. }
  42627. else {
  42628. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42629. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42630. }
  42631. lightIndex++;
  42632. if (lightIndex === maxSimultaneousLights) {
  42633. break;
  42634. }
  42635. }
  42636. }
  42637. defines["SPECULARTERM"] = specularEnabled;
  42638. defines["SHADOWS"] = shadowEnabled;
  42639. // Resetting all other lights if any
  42640. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42641. if (defines["LIGHT" + index] !== undefined) {
  42642. defines["LIGHT" + index] = false;
  42643. defines["HEMILIGHT" + lightIndex] = false;
  42644. defines["POINTLIGHT" + lightIndex] = false;
  42645. defines["DIRLIGHT" + lightIndex] = false;
  42646. defines["SPOTLIGHT" + lightIndex] = false;
  42647. defines["SHADOW" + lightIndex] = false;
  42648. }
  42649. }
  42650. var caps = scene.getEngine().getCaps();
  42651. if (defines["SHADOWFLOAT"] === undefined) {
  42652. needRebuild = true;
  42653. }
  42654. defines["SHADOWFLOAT"] = shadowEnabled &&
  42655. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42656. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42657. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42658. if (needRebuild) {
  42659. defines.rebuild();
  42660. }
  42661. return needNormals;
  42662. };
  42663. /**
  42664. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42665. * that won t be acctive due to defines being turned off.
  42666. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42667. * @param samplersList The samplers list
  42668. * @param defines The defines helping in the list generation
  42669. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42670. */
  42671. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42672. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42673. var uniformsList;
  42674. var uniformBuffersList = null;
  42675. if (uniformsListOrOptions.uniformsNames) {
  42676. var options = uniformsListOrOptions;
  42677. uniformsList = options.uniformsNames;
  42678. uniformBuffersList = options.uniformBuffersNames;
  42679. samplersList = options.samplers;
  42680. defines = options.defines;
  42681. maxSimultaneousLights = options.maxSimultaneousLights;
  42682. }
  42683. else {
  42684. uniformsList = uniformsListOrOptions;
  42685. if (!samplersList) {
  42686. samplersList = [];
  42687. }
  42688. }
  42689. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42690. if (!defines["LIGHT" + lightIndex]) {
  42691. break;
  42692. }
  42693. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42694. if (uniformBuffersList) {
  42695. uniformBuffersList.push("Light" + lightIndex);
  42696. }
  42697. samplersList.push("shadowSampler" + lightIndex);
  42698. samplersList.push("depthSampler" + lightIndex);
  42699. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42700. samplersList.push("projectionLightSampler" + lightIndex);
  42701. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42702. }
  42703. }
  42704. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42705. uniformsList.push("morphTargetInfluences");
  42706. }
  42707. };
  42708. /**
  42709. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42710. * @param defines The defines to update while falling back
  42711. * @param fallbacks The authorized effect fallbacks
  42712. * @param maxSimultaneousLights The maximum number of lights allowed
  42713. * @param rank the current rank of the Effect
  42714. * @returns The newly affected rank
  42715. */
  42716. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42717. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42718. if (rank === void 0) { rank = 0; }
  42719. var lightFallbackRank = 0;
  42720. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42721. if (!defines["LIGHT" + lightIndex]) {
  42722. break;
  42723. }
  42724. if (lightIndex > 0) {
  42725. lightFallbackRank = rank + lightIndex;
  42726. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42727. }
  42728. if (!defines["SHADOWS"]) {
  42729. if (defines["SHADOW" + lightIndex]) {
  42730. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42731. }
  42732. if (defines["SHADOWPCF" + lightIndex]) {
  42733. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42734. }
  42735. if (defines["SHADOWPCSS" + lightIndex]) {
  42736. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42737. }
  42738. if (defines["SHADOWPOISSON" + lightIndex]) {
  42739. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42740. }
  42741. if (defines["SHADOWESM" + lightIndex]) {
  42742. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42743. }
  42744. }
  42745. }
  42746. return lightFallbackRank++;
  42747. };
  42748. /**
  42749. * Prepares the list of attributes required for morph targets according to the effect defines.
  42750. * @param attribs The current list of supported attribs
  42751. * @param mesh The mesh to prepare the morph targets attributes for
  42752. * @param defines The current Defines of the effect
  42753. */
  42754. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42755. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42756. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42757. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42758. var manager = mesh.morphTargetManager;
  42759. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42760. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42761. for (var index = 0; index < influencers; index++) {
  42762. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42763. if (normal) {
  42764. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42765. }
  42766. if (tangent) {
  42767. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42768. }
  42769. if (attribs.length > maxAttributesCount) {
  42770. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42771. }
  42772. }
  42773. }
  42774. };
  42775. /**
  42776. * Prepares the list of attributes required for bones according to the effect defines.
  42777. * @param attribs The current list of supported attribs
  42778. * @param mesh The mesh to prepare the bones attributes for
  42779. * @param defines The current Defines of the effect
  42780. * @param fallbacks The current efffect fallback strategy
  42781. */
  42782. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42783. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42784. fallbacks.addCPUSkinningFallback(0, mesh);
  42785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42787. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42788. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42789. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42790. }
  42791. }
  42792. };
  42793. /**
  42794. * Prepares the list of attributes required for instances according to the effect defines.
  42795. * @param attribs The current list of supported attribs
  42796. * @param defines The current Defines of the effect
  42797. */
  42798. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42799. if (defines["INSTANCES"]) {
  42800. attribs.push("world0");
  42801. attribs.push("world1");
  42802. attribs.push("world2");
  42803. attribs.push("world3");
  42804. }
  42805. };
  42806. /**
  42807. * Binds the light shadow information to the effect for the given mesh.
  42808. * @param light The light containing the generator
  42809. * @param scene The scene the lights belongs to
  42810. * @param mesh The mesh we are binding the information to render
  42811. * @param lightIndex The light index in the effect used to render the mesh
  42812. * @param effect The effect we are binding the data to
  42813. */
  42814. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42815. if (light.shadowEnabled && mesh.receiveShadows) {
  42816. var shadowGenerator = light.getShadowGenerator();
  42817. if (shadowGenerator) {
  42818. shadowGenerator.bindShadowLight(lightIndex, effect);
  42819. }
  42820. }
  42821. };
  42822. /**
  42823. * Binds the light information to the effect.
  42824. * @param light The light containing the generator
  42825. * @param effect The effect we are binding the data to
  42826. * @param lightIndex The light index in the effect used to render
  42827. */
  42828. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42829. light.transferToEffect(effect, lightIndex + "");
  42830. };
  42831. /**
  42832. * Binds the lights information from the scene to the effect for the given mesh.
  42833. * @param scene The scene the lights belongs to
  42834. * @param mesh The mesh we are binding the information to render
  42835. * @param effect The effect we are binding the data to
  42836. * @param defines The generated defines for the effect
  42837. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42838. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42839. */
  42840. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42841. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42842. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42843. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42844. for (var i = 0; i < len; i++) {
  42845. var light = mesh._lightSources[i];
  42846. var iAsString = i.toString();
  42847. var scaledIntensity = light.getScaledIntensity();
  42848. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42849. MaterialHelper.BindLightProperties(light, effect, i);
  42850. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42851. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42852. if (defines["SPECULARTERM"]) {
  42853. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42854. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42855. }
  42856. // Shadows
  42857. if (scene.shadowsEnabled) {
  42858. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42859. }
  42860. light._uniformBuffer.update();
  42861. }
  42862. };
  42863. /**
  42864. * Binds the fog information from the scene to the effect for the given mesh.
  42865. * @param scene The scene the lights belongs to
  42866. * @param mesh The mesh we are binding the information to render
  42867. * @param effect The effect we are binding the data to
  42868. * @param linearSpace Defines if the fog effect is applied in linear space
  42869. */
  42870. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42871. if (linearSpace === void 0) { linearSpace = false; }
  42872. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42873. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42874. // Convert fog color to linear space if used in a linear space computed shader.
  42875. if (linearSpace) {
  42876. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42877. effect.setColor3("vFogColor", this._tempFogColor);
  42878. }
  42879. else {
  42880. effect.setColor3("vFogColor", scene.fogColor);
  42881. }
  42882. }
  42883. };
  42884. /**
  42885. * Binds the bones information from the mesh to the effect.
  42886. * @param mesh The mesh we are binding the information to render
  42887. * @param effect The effect we are binding the data to
  42888. */
  42889. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42890. if (!effect || !mesh) {
  42891. return;
  42892. }
  42893. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42894. mesh.computeBonesUsingShaders = false;
  42895. }
  42896. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42897. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42898. if (matrices) {
  42899. effect.setMatrices("mBones", matrices);
  42900. }
  42901. }
  42902. };
  42903. /**
  42904. * Binds the morph targets information from the mesh to the effect.
  42905. * @param abstractMesh The mesh we are binding the information to render
  42906. * @param effect The effect we are binding the data to
  42907. */
  42908. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42909. var manager = abstractMesh.morphTargetManager;
  42910. if (!abstractMesh || !manager) {
  42911. return;
  42912. }
  42913. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42914. };
  42915. /**
  42916. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42917. * @param defines The generated defines used in the effect
  42918. * @param effect The effect we are binding the data to
  42919. * @param scene The scene we are willing to render with logarithmic scale for
  42920. */
  42921. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42922. if (defines["LOGARITHMICDEPTH"]) {
  42923. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42924. }
  42925. };
  42926. /**
  42927. * Binds the clip plane information from the scene to the effect.
  42928. * @param scene The scene the clip plane information are extracted from
  42929. * @param effect The effect we are binding the data to
  42930. */
  42931. MaterialHelper.BindClipPlane = function (effect, scene) {
  42932. if (scene.clipPlane) {
  42933. var clipPlane = scene.clipPlane;
  42934. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42935. }
  42936. if (scene.clipPlane2) {
  42937. var clipPlane = scene.clipPlane2;
  42938. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42939. }
  42940. if (scene.clipPlane3) {
  42941. var clipPlane = scene.clipPlane3;
  42942. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42943. }
  42944. if (scene.clipPlane4) {
  42945. var clipPlane = scene.clipPlane4;
  42946. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42947. }
  42948. };
  42949. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42950. return MaterialHelper;
  42951. }());
  42952. BABYLON.MaterialHelper = MaterialHelper;
  42953. })(BABYLON || (BABYLON = {}));
  42954. //# sourceMappingURL=babylon.materialHelper.js.map
  42955. var BABYLON;
  42956. (function (BABYLON) {
  42957. /**
  42958. * Base class of materials working in push mode in babylon JS
  42959. * @hidden
  42960. */
  42961. var PushMaterial = /** @class */ (function (_super) {
  42962. __extends(PushMaterial, _super);
  42963. function PushMaterial(name, scene) {
  42964. var _this = _super.call(this, name, scene) || this;
  42965. _this._normalMatrix = new BABYLON.Matrix();
  42966. _this.storeEffectOnSubMeshes = true;
  42967. return _this;
  42968. }
  42969. PushMaterial.prototype.getEffect = function () {
  42970. return this._activeEffect;
  42971. };
  42972. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42973. if (!mesh) {
  42974. return false;
  42975. }
  42976. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42977. return true;
  42978. }
  42979. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42980. };
  42981. /**
  42982. * Binds the given world matrix to the active effect
  42983. *
  42984. * @param world the matrix to bind
  42985. */
  42986. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42987. this._activeEffect.setMatrix("world", world);
  42988. };
  42989. /**
  42990. * Binds the given normal matrix to the active effect
  42991. *
  42992. * @param normalMatrix the matrix to bind
  42993. */
  42994. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42995. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42996. };
  42997. PushMaterial.prototype.bind = function (world, mesh) {
  42998. if (!mesh) {
  42999. return;
  43000. }
  43001. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43002. };
  43003. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43004. if (effect === void 0) { effect = null; }
  43005. _super.prototype._afterBind.call(this, mesh);
  43006. this.getScene()._cachedEffect = effect;
  43007. };
  43008. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43009. if (visibility === void 0) { visibility = 1; }
  43010. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43011. };
  43012. return PushMaterial;
  43013. }(BABYLON.Material));
  43014. BABYLON.PushMaterial = PushMaterial;
  43015. })(BABYLON || (BABYLON = {}));
  43016. //# sourceMappingURL=babylon.pushMaterial.js.map
  43017. var BABYLON;
  43018. (function (BABYLON) {
  43019. /** @hidden */
  43020. var StandardMaterialDefines = /** @class */ (function (_super) {
  43021. __extends(StandardMaterialDefines, _super);
  43022. function StandardMaterialDefines() {
  43023. var _this = _super.call(this) || this;
  43024. _this.MAINUV1 = false;
  43025. _this.MAINUV2 = false;
  43026. _this.DIFFUSE = false;
  43027. _this.DIFFUSEDIRECTUV = 0;
  43028. _this.AMBIENT = false;
  43029. _this.AMBIENTDIRECTUV = 0;
  43030. _this.OPACITY = false;
  43031. _this.OPACITYDIRECTUV = 0;
  43032. _this.OPACITYRGB = false;
  43033. _this.REFLECTION = false;
  43034. _this.EMISSIVE = false;
  43035. _this.EMISSIVEDIRECTUV = 0;
  43036. _this.SPECULAR = false;
  43037. _this.SPECULARDIRECTUV = 0;
  43038. _this.BUMP = false;
  43039. _this.BUMPDIRECTUV = 0;
  43040. _this.PARALLAX = false;
  43041. _this.PARALLAXOCCLUSION = false;
  43042. _this.SPECULAROVERALPHA = false;
  43043. _this.CLIPPLANE = false;
  43044. _this.CLIPPLANE2 = false;
  43045. _this.CLIPPLANE3 = false;
  43046. _this.CLIPPLANE4 = false;
  43047. _this.ALPHATEST = false;
  43048. _this.DEPTHPREPASS = false;
  43049. _this.ALPHAFROMDIFFUSE = false;
  43050. _this.POINTSIZE = false;
  43051. _this.FOG = false;
  43052. _this.SPECULARTERM = false;
  43053. _this.DIFFUSEFRESNEL = false;
  43054. _this.OPACITYFRESNEL = false;
  43055. _this.REFLECTIONFRESNEL = false;
  43056. _this.REFRACTIONFRESNEL = false;
  43057. _this.EMISSIVEFRESNEL = false;
  43058. _this.FRESNEL = false;
  43059. _this.NORMAL = false;
  43060. _this.UV1 = false;
  43061. _this.UV2 = false;
  43062. _this.VERTEXCOLOR = false;
  43063. _this.VERTEXALPHA = false;
  43064. _this.NUM_BONE_INFLUENCERS = 0;
  43065. _this.BonesPerMesh = 0;
  43066. _this.INSTANCES = false;
  43067. _this.GLOSSINESS = false;
  43068. _this.ROUGHNESS = false;
  43069. _this.EMISSIVEASILLUMINATION = false;
  43070. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43071. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43072. _this.LIGHTMAP = false;
  43073. _this.LIGHTMAPDIRECTUV = 0;
  43074. _this.OBJECTSPACE_NORMALMAP = false;
  43075. _this.USELIGHTMAPASSHADOWMAP = false;
  43076. _this.REFLECTIONMAP_3D = false;
  43077. _this.REFLECTIONMAP_SPHERICAL = false;
  43078. _this.REFLECTIONMAP_PLANAR = false;
  43079. _this.REFLECTIONMAP_CUBIC = false;
  43080. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43081. _this.REFLECTIONMAP_PROJECTION = false;
  43082. _this.REFLECTIONMAP_SKYBOX = false;
  43083. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43084. _this.REFLECTIONMAP_EXPLICIT = false;
  43085. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43086. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43087. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43088. _this.INVERTCUBICMAP = false;
  43089. _this.LOGARITHMICDEPTH = false;
  43090. _this.REFRACTION = false;
  43091. _this.REFRACTIONMAP_3D = false;
  43092. _this.REFLECTIONOVERALPHA = false;
  43093. _this.TWOSIDEDLIGHTING = false;
  43094. _this.SHADOWFLOAT = false;
  43095. _this.MORPHTARGETS = false;
  43096. _this.MORPHTARGETS_NORMAL = false;
  43097. _this.MORPHTARGETS_TANGENT = false;
  43098. _this.NUM_MORPH_INFLUENCERS = 0;
  43099. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43100. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43101. _this.IMAGEPROCESSING = false;
  43102. _this.VIGNETTE = false;
  43103. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43104. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43105. _this.TONEMAPPING = false;
  43106. _this.TONEMAPPING_ACES = false;
  43107. _this.CONTRAST = false;
  43108. _this.COLORCURVES = false;
  43109. _this.COLORGRADING = false;
  43110. _this.COLORGRADING3D = false;
  43111. _this.SAMPLER3DGREENDEPTH = false;
  43112. _this.SAMPLER3DBGRMAP = false;
  43113. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43114. /**
  43115. * If the reflection texture on this material is in linear color space
  43116. * @hidden
  43117. */
  43118. _this.IS_REFLECTION_LINEAR = false;
  43119. /**
  43120. * If the refraction texture on this material is in linear color space
  43121. * @hidden
  43122. */
  43123. _this.IS_REFRACTION_LINEAR = false;
  43124. _this.EXPOSURE = false;
  43125. _this.rebuild();
  43126. return _this;
  43127. }
  43128. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43129. var modes = [
  43130. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43131. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43132. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43133. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43134. ];
  43135. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43136. var mode = modes_1[_i];
  43137. this[mode] = (mode === modeToEnable);
  43138. }
  43139. };
  43140. return StandardMaterialDefines;
  43141. }(BABYLON.MaterialDefines));
  43142. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43143. /**
  43144. * This is the default material used in Babylon. It is the best trade off between quality
  43145. * and performances.
  43146. * @see http://doc.babylonjs.com/babylon101/materials
  43147. */
  43148. var StandardMaterial = /** @class */ (function (_super) {
  43149. __extends(StandardMaterial, _super);
  43150. /**
  43151. * Instantiates a new standard material.
  43152. * This is the default material used in Babylon. It is the best trade off between quality
  43153. * and performances.
  43154. * @see http://doc.babylonjs.com/babylon101/materials
  43155. * @param name Define the name of the material in the scene
  43156. * @param scene Define the scene the material belong to
  43157. */
  43158. function StandardMaterial(name, scene) {
  43159. var _this = _super.call(this, name, scene) || this;
  43160. /**
  43161. * The color of the material lit by the environmental background lighting.
  43162. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43163. */
  43164. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43165. /**
  43166. * The basic color of the material as viewed under a light.
  43167. */
  43168. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43169. /**
  43170. * Define how the color and intensity of the highlight given by the light in the material.
  43171. */
  43172. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43173. /**
  43174. * Define the color of the material as if self lit.
  43175. * This will be mixed in the final result even in the absence of light.
  43176. */
  43177. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43178. /**
  43179. * Defines how sharp are the highlights in the material.
  43180. * The bigger the value the sharper giving a more glossy feeling to the result.
  43181. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43182. */
  43183. _this.specularPower = 64;
  43184. _this._useAlphaFromDiffuseTexture = false;
  43185. _this._useEmissiveAsIllumination = false;
  43186. _this._linkEmissiveWithDiffuse = false;
  43187. _this._useSpecularOverAlpha = false;
  43188. _this._useReflectionOverAlpha = false;
  43189. _this._disableLighting = false;
  43190. _this._useObjectSpaceNormalMap = false;
  43191. _this._useParallax = false;
  43192. _this._useParallaxOcclusion = false;
  43193. /**
  43194. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  43195. */
  43196. _this.parallaxScaleBias = 0.05;
  43197. _this._roughness = 0;
  43198. /**
  43199. * In case of refraction, define the value of the indice of refraction.
  43200. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43201. */
  43202. _this.indexOfRefraction = 0.98;
  43203. /**
  43204. * Invert the refraction texture alongside the y axis.
  43205. * It can be usefull with procedural textures or probe for instance.
  43206. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43207. */
  43208. _this.invertRefractionY = true;
  43209. /**
  43210. * Defines the alpha limits in alpha test mode.
  43211. */
  43212. _this.alphaCutOff = 0.4;
  43213. _this._useLightmapAsShadowmap = false;
  43214. _this._useReflectionFresnelFromSpecular = false;
  43215. _this._useGlossinessFromSpecularMapAlpha = false;
  43216. _this._maxSimultaneousLights = 4;
  43217. _this._invertNormalMapX = false;
  43218. _this._invertNormalMapY = false;
  43219. _this._twoSidedLighting = false;
  43220. _this._renderTargets = new BABYLON.SmartArray(16);
  43221. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43222. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43223. // Setup the default processing configuration to the scene.
  43224. _this._attachImageProcessingConfiguration(null);
  43225. _this.getRenderTargetTextures = function () {
  43226. _this._renderTargets.reset();
  43227. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43228. _this._renderTargets.push(_this._reflectionTexture);
  43229. }
  43230. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43231. _this._renderTargets.push(_this._refractionTexture);
  43232. }
  43233. return _this._renderTargets;
  43234. };
  43235. return _this;
  43236. }
  43237. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43238. /**
  43239. * Gets the image processing configuration used either in this material.
  43240. */
  43241. get: function () {
  43242. return this._imageProcessingConfiguration;
  43243. },
  43244. /**
  43245. * Sets the Default image processing configuration used either in the this material.
  43246. *
  43247. * If sets to null, the scene one is in use.
  43248. */
  43249. set: function (value) {
  43250. this._attachImageProcessingConfiguration(value);
  43251. // Ensure the effect will be rebuilt.
  43252. this._markAllSubMeshesAsTexturesDirty();
  43253. },
  43254. enumerable: true,
  43255. configurable: true
  43256. });
  43257. /**
  43258. * Attaches a new image processing configuration to the Standard Material.
  43259. * @param configuration
  43260. */
  43261. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43262. var _this = this;
  43263. if (configuration === this._imageProcessingConfiguration) {
  43264. return;
  43265. }
  43266. // Detaches observer.
  43267. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43268. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43269. }
  43270. // Pick the scene configuration if needed.
  43271. if (!configuration) {
  43272. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43273. }
  43274. else {
  43275. this._imageProcessingConfiguration = configuration;
  43276. }
  43277. // Attaches observer.
  43278. if (this._imageProcessingConfiguration) {
  43279. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43280. _this._markAllSubMeshesAsImageProcessingDirty();
  43281. });
  43282. }
  43283. };
  43284. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43285. /**
  43286. * Gets wether the color curves effect is enabled.
  43287. */
  43288. get: function () {
  43289. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43290. },
  43291. /**
  43292. * Sets wether the color curves effect is enabled.
  43293. */
  43294. set: function (value) {
  43295. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43296. },
  43297. enumerable: true,
  43298. configurable: true
  43299. });
  43300. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43301. /**
  43302. * Gets wether the color grading effect is enabled.
  43303. */
  43304. get: function () {
  43305. return this.imageProcessingConfiguration.colorGradingEnabled;
  43306. },
  43307. /**
  43308. * Gets wether the color grading effect is enabled.
  43309. */
  43310. set: function (value) {
  43311. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43312. },
  43313. enumerable: true,
  43314. configurable: true
  43315. });
  43316. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43317. /**
  43318. * Gets wether tonemapping is enabled or not.
  43319. */
  43320. get: function () {
  43321. return this._imageProcessingConfiguration.toneMappingEnabled;
  43322. },
  43323. /**
  43324. * Sets wether tonemapping is enabled or not
  43325. */
  43326. set: function (value) {
  43327. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43328. },
  43329. enumerable: true,
  43330. configurable: true
  43331. });
  43332. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43333. /**
  43334. * The camera exposure used on this material.
  43335. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43336. * This corresponds to a photographic exposure.
  43337. */
  43338. get: function () {
  43339. return this._imageProcessingConfiguration.exposure;
  43340. },
  43341. /**
  43342. * The camera exposure used on this material.
  43343. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43344. * This corresponds to a photographic exposure.
  43345. */
  43346. set: function (value) {
  43347. this._imageProcessingConfiguration.exposure = value;
  43348. },
  43349. enumerable: true,
  43350. configurable: true
  43351. });
  43352. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43353. /**
  43354. * Gets The camera contrast used on this material.
  43355. */
  43356. get: function () {
  43357. return this._imageProcessingConfiguration.contrast;
  43358. },
  43359. /**
  43360. * Sets The camera contrast used on this material.
  43361. */
  43362. set: function (value) {
  43363. this._imageProcessingConfiguration.contrast = value;
  43364. },
  43365. enumerable: true,
  43366. configurable: true
  43367. });
  43368. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43369. /**
  43370. * Gets the Color Grading 2D Lookup Texture.
  43371. */
  43372. get: function () {
  43373. return this._imageProcessingConfiguration.colorGradingTexture;
  43374. },
  43375. /**
  43376. * Sets the Color Grading 2D Lookup Texture.
  43377. */
  43378. set: function (value) {
  43379. this._imageProcessingConfiguration.colorGradingTexture = value;
  43380. },
  43381. enumerable: true,
  43382. configurable: true
  43383. });
  43384. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43385. /**
  43386. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43387. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43388. * 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;
  43389. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43390. */
  43391. get: function () {
  43392. return this._imageProcessingConfiguration.colorCurves;
  43393. },
  43394. /**
  43395. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43396. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43397. * 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;
  43398. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43399. */
  43400. set: function (value) {
  43401. this._imageProcessingConfiguration.colorCurves = value;
  43402. },
  43403. enumerable: true,
  43404. configurable: true
  43405. });
  43406. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43407. /**
  43408. * Gets a boolean indicating that current material needs to register RTT
  43409. */
  43410. get: function () {
  43411. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43412. return true;
  43413. }
  43414. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43415. return true;
  43416. }
  43417. return false;
  43418. },
  43419. enumerable: true,
  43420. configurable: true
  43421. });
  43422. /**
  43423. * Gets the current class name of the material e.g. "StandardMaterial"
  43424. * Mainly use in serialization.
  43425. * @returns the class name
  43426. */
  43427. StandardMaterial.prototype.getClassName = function () {
  43428. return "StandardMaterial";
  43429. };
  43430. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43431. /**
  43432. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43433. * You can try switching to logarithmic depth.
  43434. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43435. */
  43436. get: function () {
  43437. return this._useLogarithmicDepth;
  43438. },
  43439. set: function (value) {
  43440. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43441. this._markAllSubMeshesAsMiscDirty();
  43442. },
  43443. enumerable: true,
  43444. configurable: true
  43445. });
  43446. /**
  43447. * Specifies if the material will require alpha blending
  43448. * @returns a boolean specifying if alpha blending is needed
  43449. */
  43450. StandardMaterial.prototype.needAlphaBlending = function () {
  43451. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43452. };
  43453. /**
  43454. * Specifies if this material should be rendered in alpha test mode
  43455. * @returns a boolean specifying if an alpha test is needed.
  43456. */
  43457. StandardMaterial.prototype.needAlphaTesting = function () {
  43458. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43459. };
  43460. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43461. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43462. };
  43463. /**
  43464. * Get the texture used for alpha test purpose.
  43465. * @returns the diffuse texture in case of the standard material.
  43466. */
  43467. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43468. return this._diffuseTexture;
  43469. };
  43470. /**
  43471. * Get if the submesh is ready to be used and all its information available.
  43472. * Child classes can use it to update shaders
  43473. * @param mesh defines the mesh to check
  43474. * @param subMesh defines which submesh to check
  43475. * @param useInstances specifies that instances should be used
  43476. * @returns a boolean indicating that the submesh is ready or not
  43477. */
  43478. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43479. if (useInstances === void 0) { useInstances = false; }
  43480. if (subMesh.effect && this.isFrozen) {
  43481. if (this._wasPreviouslyReady) {
  43482. return true;
  43483. }
  43484. }
  43485. if (!subMesh._materialDefines) {
  43486. subMesh._materialDefines = new StandardMaterialDefines();
  43487. }
  43488. var scene = this.getScene();
  43489. var defines = subMesh._materialDefines;
  43490. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43491. if (defines._renderId === scene.getRenderId()) {
  43492. return true;
  43493. }
  43494. }
  43495. var engine = scene.getEngine();
  43496. // Lights
  43497. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43498. // Textures
  43499. if (defines._areTexturesDirty) {
  43500. defines._needUVs = false;
  43501. defines.MAINUV1 = false;
  43502. defines.MAINUV2 = false;
  43503. if (scene.texturesEnabled) {
  43504. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43505. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43506. return false;
  43507. }
  43508. else {
  43509. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43510. }
  43511. }
  43512. else {
  43513. defines.DIFFUSE = false;
  43514. }
  43515. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43516. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43517. return false;
  43518. }
  43519. else {
  43520. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43521. }
  43522. }
  43523. else {
  43524. defines.AMBIENT = false;
  43525. }
  43526. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43527. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43528. return false;
  43529. }
  43530. else {
  43531. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43532. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43533. }
  43534. }
  43535. else {
  43536. defines.OPACITY = false;
  43537. }
  43538. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43539. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43540. return false;
  43541. }
  43542. else {
  43543. defines._needNormals = true;
  43544. defines.REFLECTION = true;
  43545. defines.ROUGHNESS = (this._roughness > 0);
  43546. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43547. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43548. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43549. switch (this._reflectionTexture.coordinatesMode) {
  43550. case BABYLON.Texture.EXPLICIT_MODE:
  43551. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43552. break;
  43553. case BABYLON.Texture.PLANAR_MODE:
  43554. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43555. break;
  43556. case BABYLON.Texture.PROJECTION_MODE:
  43557. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43558. break;
  43559. case BABYLON.Texture.SKYBOX_MODE:
  43560. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43561. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43562. break;
  43563. case BABYLON.Texture.SPHERICAL_MODE:
  43564. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43565. break;
  43566. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43567. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43568. break;
  43569. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43570. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43571. break;
  43572. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43573. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43574. break;
  43575. case BABYLON.Texture.CUBIC_MODE:
  43576. case BABYLON.Texture.INVCUBIC_MODE:
  43577. default:
  43578. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43579. break;
  43580. }
  43581. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43582. }
  43583. }
  43584. else {
  43585. defines.REFLECTION = false;
  43586. }
  43587. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43588. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43589. return false;
  43590. }
  43591. else {
  43592. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43593. }
  43594. }
  43595. else {
  43596. defines.EMISSIVE = false;
  43597. }
  43598. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43599. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43600. return false;
  43601. }
  43602. else {
  43603. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43604. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43605. }
  43606. }
  43607. else {
  43608. defines.LIGHTMAP = false;
  43609. }
  43610. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43611. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43612. return false;
  43613. }
  43614. else {
  43615. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43616. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43617. }
  43618. }
  43619. else {
  43620. defines.SPECULAR = false;
  43621. }
  43622. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43623. // Bump texure can not be not blocking.
  43624. if (!this._bumpTexture.isReady()) {
  43625. return false;
  43626. }
  43627. else {
  43628. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43629. defines.PARALLAX = this._useParallax;
  43630. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43631. }
  43632. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43633. }
  43634. else {
  43635. defines.BUMP = false;
  43636. }
  43637. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43638. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43639. return false;
  43640. }
  43641. else {
  43642. defines._needUVs = true;
  43643. defines.REFRACTION = true;
  43644. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43645. }
  43646. }
  43647. else {
  43648. defines.REFRACTION = false;
  43649. }
  43650. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43651. }
  43652. else {
  43653. defines.DIFFUSE = false;
  43654. defines.AMBIENT = false;
  43655. defines.OPACITY = false;
  43656. defines.REFLECTION = false;
  43657. defines.EMISSIVE = false;
  43658. defines.LIGHTMAP = false;
  43659. defines.BUMP = false;
  43660. defines.REFRACTION = false;
  43661. }
  43662. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43663. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43664. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43665. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43666. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43667. }
  43668. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43669. if (!this._imageProcessingConfiguration.isReady()) {
  43670. return false;
  43671. }
  43672. this._imageProcessingConfiguration.prepareDefines(defines);
  43673. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43674. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43675. }
  43676. if (defines._areFresnelDirty) {
  43677. if (StandardMaterial.FresnelEnabled) {
  43678. // Fresnel
  43679. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43680. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43681. this._reflectionFresnelParameters) {
  43682. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43683. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43684. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43685. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43686. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43687. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43688. defines._needNormals = true;
  43689. defines.FRESNEL = true;
  43690. }
  43691. }
  43692. else {
  43693. defines.FRESNEL = false;
  43694. }
  43695. }
  43696. // Misc.
  43697. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43698. // Attribs
  43699. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43700. // Values that need to be evaluated on every frame
  43701. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43702. // Get correct effect
  43703. if (defines.isDirty) {
  43704. defines.markAsProcessed();
  43705. scene.resetCachedMaterial();
  43706. // Fallbacks
  43707. var fallbacks = new BABYLON.EffectFallbacks();
  43708. if (defines.REFLECTION) {
  43709. fallbacks.addFallback(0, "REFLECTION");
  43710. }
  43711. if (defines.SPECULAR) {
  43712. fallbacks.addFallback(0, "SPECULAR");
  43713. }
  43714. if (defines.BUMP) {
  43715. fallbacks.addFallback(0, "BUMP");
  43716. }
  43717. if (defines.PARALLAX) {
  43718. fallbacks.addFallback(1, "PARALLAX");
  43719. }
  43720. if (defines.PARALLAXOCCLUSION) {
  43721. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43722. }
  43723. if (defines.SPECULAROVERALPHA) {
  43724. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43725. }
  43726. if (defines.FOG) {
  43727. fallbacks.addFallback(1, "FOG");
  43728. }
  43729. if (defines.POINTSIZE) {
  43730. fallbacks.addFallback(0, "POINTSIZE");
  43731. }
  43732. if (defines.LOGARITHMICDEPTH) {
  43733. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43734. }
  43735. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43736. if (defines.SPECULARTERM) {
  43737. fallbacks.addFallback(0, "SPECULARTERM");
  43738. }
  43739. if (defines.DIFFUSEFRESNEL) {
  43740. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43741. }
  43742. if (defines.OPACITYFRESNEL) {
  43743. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43744. }
  43745. if (defines.REFLECTIONFRESNEL) {
  43746. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43747. }
  43748. if (defines.EMISSIVEFRESNEL) {
  43749. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43750. }
  43751. if (defines.FRESNEL) {
  43752. fallbacks.addFallback(4, "FRESNEL");
  43753. }
  43754. //Attributes
  43755. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43756. if (defines.NORMAL) {
  43757. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43758. }
  43759. if (defines.UV1) {
  43760. attribs.push(BABYLON.VertexBuffer.UVKind);
  43761. }
  43762. if (defines.UV2) {
  43763. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43764. }
  43765. if (defines.VERTEXCOLOR) {
  43766. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43767. }
  43768. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43769. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43770. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43771. var shaderName = "default";
  43772. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43773. "vFogInfos", "vFogColor", "pointSize",
  43774. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43775. "mBones",
  43776. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43777. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43778. "vReflectionPosition", "vReflectionSize",
  43779. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43780. ];
  43781. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43782. var uniformBuffers = ["Material", "Scene"];
  43783. if (BABYLON.ImageProcessingConfiguration) {
  43784. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43785. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43786. }
  43787. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43788. uniformsNames: uniforms,
  43789. uniformBuffersNames: uniformBuffers,
  43790. samplers: samplers,
  43791. defines: defines,
  43792. maxSimultaneousLights: this._maxSimultaneousLights
  43793. });
  43794. if (this.customShaderNameResolve) {
  43795. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43796. }
  43797. var join = defines.toString();
  43798. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43799. attributes: attribs,
  43800. uniformsNames: uniforms,
  43801. uniformBuffersNames: uniformBuffers,
  43802. samplers: samplers,
  43803. defines: join,
  43804. fallbacks: fallbacks,
  43805. onCompiled: this.onCompiled,
  43806. onError: this.onError,
  43807. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43808. }, engine), defines);
  43809. this.buildUniformLayout();
  43810. }
  43811. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43812. return false;
  43813. }
  43814. defines._renderId = scene.getRenderId();
  43815. this._wasPreviouslyReady = true;
  43816. return true;
  43817. };
  43818. /**
  43819. * Builds the material UBO layouts.
  43820. * Used internally during the effect preparation.
  43821. */
  43822. StandardMaterial.prototype.buildUniformLayout = function () {
  43823. // Order is important !
  43824. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43825. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43826. this._uniformBuffer.addUniform("opacityParts", 4);
  43827. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43828. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43829. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43830. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43831. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43832. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43833. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43834. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43835. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43836. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43837. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43838. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43839. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43840. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43841. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43842. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43843. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43844. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43845. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43846. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43847. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43848. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43849. this._uniformBuffer.addUniform("specularMatrix", 16);
  43850. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43851. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43852. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43853. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43854. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43855. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43856. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43857. this._uniformBuffer.addUniform("pointSize", 1);
  43858. this._uniformBuffer.create();
  43859. };
  43860. /**
  43861. * Unbinds the material from the mesh
  43862. */
  43863. StandardMaterial.prototype.unbind = function () {
  43864. if (this._activeEffect) {
  43865. var needFlag = false;
  43866. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43867. this._activeEffect.setTexture("reflection2DSampler", null);
  43868. needFlag = true;
  43869. }
  43870. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43871. this._activeEffect.setTexture("refraction2DSampler", null);
  43872. needFlag = true;
  43873. }
  43874. if (needFlag) {
  43875. this._markAllSubMeshesAsTexturesDirty();
  43876. }
  43877. }
  43878. _super.prototype.unbind.call(this);
  43879. };
  43880. /**
  43881. * Binds the submesh to this material by preparing the effect and shader to draw
  43882. * @param world defines the world transformation matrix
  43883. * @param mesh defines the mesh containing the submesh
  43884. * @param subMesh defines the submesh to bind the material to
  43885. */
  43886. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43887. var scene = this.getScene();
  43888. var defines = subMesh._materialDefines;
  43889. if (!defines) {
  43890. return;
  43891. }
  43892. var effect = subMesh.effect;
  43893. if (!effect) {
  43894. return;
  43895. }
  43896. this._activeEffect = effect;
  43897. // Matrices
  43898. this.bindOnlyWorldMatrix(world);
  43899. // Normal Matrix
  43900. if (defines.OBJECTSPACE_NORMALMAP) {
  43901. world.toNormalMatrix(this._normalMatrix);
  43902. this.bindOnlyNormalMatrix(this._normalMatrix);
  43903. }
  43904. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43905. // Bones
  43906. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43907. if (mustRebind) {
  43908. this._uniformBuffer.bindToEffect(effect, "Material");
  43909. this.bindViewProjection(effect);
  43910. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43911. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43912. // Fresnel
  43913. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43914. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43915. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43916. }
  43917. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43918. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43919. }
  43920. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43921. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43922. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43923. }
  43924. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43925. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43926. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43927. }
  43928. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43929. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43930. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43931. }
  43932. }
  43933. // Textures
  43934. if (scene.texturesEnabled) {
  43935. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43936. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43937. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43938. if (this._diffuseTexture.hasAlpha) {
  43939. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43940. }
  43941. }
  43942. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43943. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43944. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43945. }
  43946. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43947. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43948. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43949. }
  43950. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43951. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43952. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43953. if (this._reflectionTexture.boundingBoxSize) {
  43954. var cubeTexture = this._reflectionTexture;
  43955. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43956. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43957. }
  43958. }
  43959. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43960. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43961. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43962. }
  43963. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43964. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43965. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43966. }
  43967. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43968. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43969. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43970. }
  43971. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43972. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43973. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43974. if (scene._mirroredCameraPosition) {
  43975. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43976. }
  43977. else {
  43978. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43979. }
  43980. }
  43981. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43982. var depth = 1.0;
  43983. if (!this._refractionTexture.isCube) {
  43984. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43985. if (this._refractionTexture.depth) {
  43986. depth = this._refractionTexture.depth;
  43987. }
  43988. }
  43989. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43990. }
  43991. }
  43992. // Point size
  43993. if (this.pointsCloud) {
  43994. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43995. }
  43996. if (defines.SPECULARTERM) {
  43997. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43998. }
  43999. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44000. // Diffuse
  44001. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44002. }
  44003. // Textures
  44004. if (scene.texturesEnabled) {
  44005. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44006. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44007. }
  44008. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44009. effect.setTexture("ambientSampler", this._ambientTexture);
  44010. }
  44011. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44012. effect.setTexture("opacitySampler", this._opacityTexture);
  44013. }
  44014. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44015. if (this._reflectionTexture.isCube) {
  44016. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44017. }
  44018. else {
  44019. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44020. }
  44021. }
  44022. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44023. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44024. }
  44025. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44026. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44027. }
  44028. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44029. effect.setTexture("specularSampler", this._specularTexture);
  44030. }
  44031. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44032. effect.setTexture("bumpSampler", this._bumpTexture);
  44033. }
  44034. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44035. var depth = 1.0;
  44036. if (this._refractionTexture.isCube) {
  44037. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44038. }
  44039. else {
  44040. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44041. }
  44042. }
  44043. }
  44044. // Clip plane
  44045. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44046. // Colors
  44047. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44048. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44049. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44050. }
  44051. if (mustRebind || !this.isFrozen) {
  44052. // Lights
  44053. if (scene.lightsEnabled && !this._disableLighting) {
  44054. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44055. }
  44056. // View
  44057. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44058. this.bindView(effect);
  44059. }
  44060. // Fog
  44061. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44062. // Morph targets
  44063. if (defines.NUM_MORPH_INFLUENCERS) {
  44064. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44065. }
  44066. // Log. depth
  44067. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44068. // image processing
  44069. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44070. this._imageProcessingConfiguration.bind(this._activeEffect);
  44071. }
  44072. }
  44073. this._uniformBuffer.update();
  44074. this._afterBind(mesh, this._activeEffect);
  44075. };
  44076. /**
  44077. * Get the list of animatables in the material.
  44078. * @returns the list of animatables object used in the material
  44079. */
  44080. StandardMaterial.prototype.getAnimatables = function () {
  44081. var results = [];
  44082. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44083. results.push(this._diffuseTexture);
  44084. }
  44085. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44086. results.push(this._ambientTexture);
  44087. }
  44088. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44089. results.push(this._opacityTexture);
  44090. }
  44091. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44092. results.push(this._reflectionTexture);
  44093. }
  44094. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44095. results.push(this._emissiveTexture);
  44096. }
  44097. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44098. results.push(this._specularTexture);
  44099. }
  44100. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44101. results.push(this._bumpTexture);
  44102. }
  44103. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44104. results.push(this._lightmapTexture);
  44105. }
  44106. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44107. results.push(this._refractionTexture);
  44108. }
  44109. return results;
  44110. };
  44111. /**
  44112. * Gets the active textures from the material
  44113. * @returns an array of textures
  44114. */
  44115. StandardMaterial.prototype.getActiveTextures = function () {
  44116. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44117. if (this._diffuseTexture) {
  44118. activeTextures.push(this._diffuseTexture);
  44119. }
  44120. if (this._ambientTexture) {
  44121. activeTextures.push(this._ambientTexture);
  44122. }
  44123. if (this._opacityTexture) {
  44124. activeTextures.push(this._opacityTexture);
  44125. }
  44126. if (this._reflectionTexture) {
  44127. activeTextures.push(this._reflectionTexture);
  44128. }
  44129. if (this._emissiveTexture) {
  44130. activeTextures.push(this._emissiveTexture);
  44131. }
  44132. if (this._specularTexture) {
  44133. activeTextures.push(this._specularTexture);
  44134. }
  44135. if (this._bumpTexture) {
  44136. activeTextures.push(this._bumpTexture);
  44137. }
  44138. if (this._lightmapTexture) {
  44139. activeTextures.push(this._lightmapTexture);
  44140. }
  44141. if (this._refractionTexture) {
  44142. activeTextures.push(this._refractionTexture);
  44143. }
  44144. return activeTextures;
  44145. };
  44146. /**
  44147. * Specifies if the material uses a texture
  44148. * @param texture defines the texture to check against the material
  44149. * @returns a boolean specifying if the material uses the texture
  44150. */
  44151. StandardMaterial.prototype.hasTexture = function (texture) {
  44152. if (_super.prototype.hasTexture.call(this, texture)) {
  44153. return true;
  44154. }
  44155. if (this._diffuseTexture === texture) {
  44156. return true;
  44157. }
  44158. if (this._ambientTexture === texture) {
  44159. return true;
  44160. }
  44161. if (this._opacityTexture === texture) {
  44162. return true;
  44163. }
  44164. if (this._reflectionTexture === texture) {
  44165. return true;
  44166. }
  44167. if (this._emissiveTexture === texture) {
  44168. return true;
  44169. }
  44170. if (this._specularTexture === texture) {
  44171. return true;
  44172. }
  44173. if (this._bumpTexture === texture) {
  44174. return true;
  44175. }
  44176. if (this._lightmapTexture === texture) {
  44177. return true;
  44178. }
  44179. if (this._refractionTexture === texture) {
  44180. return true;
  44181. }
  44182. return false;
  44183. };
  44184. /**
  44185. * Disposes the material
  44186. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44187. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44188. */
  44189. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44190. if (forceDisposeTextures) {
  44191. if (this._diffuseTexture) {
  44192. this._diffuseTexture.dispose();
  44193. }
  44194. if (this._ambientTexture) {
  44195. this._ambientTexture.dispose();
  44196. }
  44197. if (this._opacityTexture) {
  44198. this._opacityTexture.dispose();
  44199. }
  44200. if (this._reflectionTexture) {
  44201. this._reflectionTexture.dispose();
  44202. }
  44203. if (this._emissiveTexture) {
  44204. this._emissiveTexture.dispose();
  44205. }
  44206. if (this._specularTexture) {
  44207. this._specularTexture.dispose();
  44208. }
  44209. if (this._bumpTexture) {
  44210. this._bumpTexture.dispose();
  44211. }
  44212. if (this._lightmapTexture) {
  44213. this._lightmapTexture.dispose();
  44214. }
  44215. if (this._refractionTexture) {
  44216. this._refractionTexture.dispose();
  44217. }
  44218. }
  44219. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44220. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44221. }
  44222. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44223. };
  44224. /**
  44225. * Makes a duplicate of the material, and gives it a new name
  44226. * @param name defines the new name for the duplicated material
  44227. * @returns the cloned material
  44228. */
  44229. StandardMaterial.prototype.clone = function (name) {
  44230. var _this = this;
  44231. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44232. result.name = name;
  44233. result.id = name;
  44234. return result;
  44235. };
  44236. /**
  44237. * Serializes this material in a JSON representation
  44238. * @returns the serialized material object
  44239. */
  44240. StandardMaterial.prototype.serialize = function () {
  44241. return BABYLON.SerializationHelper.Serialize(this);
  44242. };
  44243. /**
  44244. * Creates a standard material from parsed material data
  44245. * @param source defines the JSON represnetation of the material
  44246. * @param scene defines the hosting scene
  44247. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44248. * @returns a new material
  44249. */
  44250. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44251. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44252. };
  44253. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44254. /**
  44255. * Are diffuse textures enabled in the application.
  44256. */
  44257. get: function () {
  44258. return StandardMaterial._DiffuseTextureEnabled;
  44259. },
  44260. set: function (value) {
  44261. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44262. return;
  44263. }
  44264. StandardMaterial._DiffuseTextureEnabled = value;
  44265. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44266. },
  44267. enumerable: true,
  44268. configurable: true
  44269. });
  44270. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44271. /**
  44272. * Are ambient textures enabled in the application.
  44273. */
  44274. get: function () {
  44275. return StandardMaterial._AmbientTextureEnabled;
  44276. },
  44277. set: function (value) {
  44278. if (StandardMaterial._AmbientTextureEnabled === value) {
  44279. return;
  44280. }
  44281. StandardMaterial._AmbientTextureEnabled = value;
  44282. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44283. },
  44284. enumerable: true,
  44285. configurable: true
  44286. });
  44287. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44288. /**
  44289. * Are opacity textures enabled in the application.
  44290. */
  44291. get: function () {
  44292. return StandardMaterial._OpacityTextureEnabled;
  44293. },
  44294. set: function (value) {
  44295. if (StandardMaterial._OpacityTextureEnabled === value) {
  44296. return;
  44297. }
  44298. StandardMaterial._OpacityTextureEnabled = value;
  44299. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44300. },
  44301. enumerable: true,
  44302. configurable: true
  44303. });
  44304. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44305. /**
  44306. * Are reflection textures enabled in the application.
  44307. */
  44308. get: function () {
  44309. return StandardMaterial._ReflectionTextureEnabled;
  44310. },
  44311. set: function (value) {
  44312. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44313. return;
  44314. }
  44315. StandardMaterial._ReflectionTextureEnabled = value;
  44316. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44317. },
  44318. enumerable: true,
  44319. configurable: true
  44320. });
  44321. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44322. /**
  44323. * Are emissive textures enabled in the application.
  44324. */
  44325. get: function () {
  44326. return StandardMaterial._EmissiveTextureEnabled;
  44327. },
  44328. set: function (value) {
  44329. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44330. return;
  44331. }
  44332. StandardMaterial._EmissiveTextureEnabled = value;
  44333. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44334. },
  44335. enumerable: true,
  44336. configurable: true
  44337. });
  44338. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44339. /**
  44340. * Are specular textures enabled in the application.
  44341. */
  44342. get: function () {
  44343. return StandardMaterial._SpecularTextureEnabled;
  44344. },
  44345. set: function (value) {
  44346. if (StandardMaterial._SpecularTextureEnabled === value) {
  44347. return;
  44348. }
  44349. StandardMaterial._SpecularTextureEnabled = value;
  44350. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44351. },
  44352. enumerable: true,
  44353. configurable: true
  44354. });
  44355. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44356. /**
  44357. * Are bump textures enabled in the application.
  44358. */
  44359. get: function () {
  44360. return StandardMaterial._BumpTextureEnabled;
  44361. },
  44362. set: function (value) {
  44363. if (StandardMaterial._BumpTextureEnabled === value) {
  44364. return;
  44365. }
  44366. StandardMaterial._BumpTextureEnabled = value;
  44367. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44368. },
  44369. enumerable: true,
  44370. configurable: true
  44371. });
  44372. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44373. /**
  44374. * Are lightmap textures enabled in the application.
  44375. */
  44376. get: function () {
  44377. return StandardMaterial._LightmapTextureEnabled;
  44378. },
  44379. set: function (value) {
  44380. if (StandardMaterial._LightmapTextureEnabled === value) {
  44381. return;
  44382. }
  44383. StandardMaterial._LightmapTextureEnabled = value;
  44384. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44385. },
  44386. enumerable: true,
  44387. configurable: true
  44388. });
  44389. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44390. /**
  44391. * Are refraction textures enabled in the application.
  44392. */
  44393. get: function () {
  44394. return StandardMaterial._RefractionTextureEnabled;
  44395. },
  44396. set: function (value) {
  44397. if (StandardMaterial._RefractionTextureEnabled === value) {
  44398. return;
  44399. }
  44400. StandardMaterial._RefractionTextureEnabled = value;
  44401. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44402. },
  44403. enumerable: true,
  44404. configurable: true
  44405. });
  44406. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44407. /**
  44408. * Are color grading textures enabled in the application.
  44409. */
  44410. get: function () {
  44411. return StandardMaterial._ColorGradingTextureEnabled;
  44412. },
  44413. set: function (value) {
  44414. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44415. return;
  44416. }
  44417. StandardMaterial._ColorGradingTextureEnabled = value;
  44418. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44419. },
  44420. enumerable: true,
  44421. configurable: true
  44422. });
  44423. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44424. /**
  44425. * Are fresnels enabled in the application.
  44426. */
  44427. get: function () {
  44428. return StandardMaterial._FresnelEnabled;
  44429. },
  44430. set: function (value) {
  44431. if (StandardMaterial._FresnelEnabled === value) {
  44432. return;
  44433. }
  44434. StandardMaterial._FresnelEnabled = value;
  44435. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44436. },
  44437. enumerable: true,
  44438. configurable: true
  44439. });
  44440. // Flags used to enable or disable a type of texture for all Standard Materials
  44441. StandardMaterial._DiffuseTextureEnabled = true;
  44442. StandardMaterial._AmbientTextureEnabled = true;
  44443. StandardMaterial._OpacityTextureEnabled = true;
  44444. StandardMaterial._ReflectionTextureEnabled = true;
  44445. StandardMaterial._EmissiveTextureEnabled = true;
  44446. StandardMaterial._SpecularTextureEnabled = true;
  44447. StandardMaterial._BumpTextureEnabled = true;
  44448. StandardMaterial._LightmapTextureEnabled = true;
  44449. StandardMaterial._RefractionTextureEnabled = true;
  44450. StandardMaterial._ColorGradingTextureEnabled = true;
  44451. StandardMaterial._FresnelEnabled = true;
  44452. __decorate([
  44453. BABYLON.serializeAsTexture("diffuseTexture")
  44454. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44455. __decorate([
  44456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44457. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44458. __decorate([
  44459. BABYLON.serializeAsTexture("ambientTexture")
  44460. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44461. __decorate([
  44462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44463. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44464. __decorate([
  44465. BABYLON.serializeAsTexture("opacityTexture")
  44466. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44467. __decorate([
  44468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44469. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44470. __decorate([
  44471. BABYLON.serializeAsTexture("reflectionTexture")
  44472. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44473. __decorate([
  44474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44475. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44476. __decorate([
  44477. BABYLON.serializeAsTexture("emissiveTexture")
  44478. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44479. __decorate([
  44480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44481. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44482. __decorate([
  44483. BABYLON.serializeAsTexture("specularTexture")
  44484. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44485. __decorate([
  44486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44487. ], StandardMaterial.prototype, "specularTexture", void 0);
  44488. __decorate([
  44489. BABYLON.serializeAsTexture("bumpTexture")
  44490. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44491. __decorate([
  44492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44493. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44494. __decorate([
  44495. BABYLON.serializeAsTexture("lightmapTexture")
  44496. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44497. __decorate([
  44498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44499. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44500. __decorate([
  44501. BABYLON.serializeAsTexture("refractionTexture")
  44502. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44503. __decorate([
  44504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44505. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44506. __decorate([
  44507. BABYLON.serializeAsColor3("ambient")
  44508. ], StandardMaterial.prototype, "ambientColor", void 0);
  44509. __decorate([
  44510. BABYLON.serializeAsColor3("diffuse")
  44511. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44512. __decorate([
  44513. BABYLON.serializeAsColor3("specular")
  44514. ], StandardMaterial.prototype, "specularColor", void 0);
  44515. __decorate([
  44516. BABYLON.serializeAsColor3("emissive")
  44517. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44518. __decorate([
  44519. BABYLON.serialize()
  44520. ], StandardMaterial.prototype, "specularPower", void 0);
  44521. __decorate([
  44522. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44523. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44524. __decorate([
  44525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44526. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44527. __decorate([
  44528. BABYLON.serialize("useEmissiveAsIllumination")
  44529. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44530. __decorate([
  44531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44532. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44533. __decorate([
  44534. BABYLON.serialize("linkEmissiveWithDiffuse")
  44535. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44536. __decorate([
  44537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44538. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44539. __decorate([
  44540. BABYLON.serialize("useSpecularOverAlpha")
  44541. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44542. __decorate([
  44543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44544. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44545. __decorate([
  44546. BABYLON.serialize("useReflectionOverAlpha")
  44547. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44548. __decorate([
  44549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44550. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44551. __decorate([
  44552. BABYLON.serialize("disableLighting")
  44553. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44554. __decorate([
  44555. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44556. ], StandardMaterial.prototype, "disableLighting", void 0);
  44557. __decorate([
  44558. BABYLON.serialize("useObjectSpaceNormalMap")
  44559. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44560. __decorate([
  44561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44562. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44563. __decorate([
  44564. BABYLON.serialize("useParallax")
  44565. ], StandardMaterial.prototype, "_useParallax", void 0);
  44566. __decorate([
  44567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44568. ], StandardMaterial.prototype, "useParallax", void 0);
  44569. __decorate([
  44570. BABYLON.serialize("useParallaxOcclusion")
  44571. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44572. __decorate([
  44573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44574. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44575. __decorate([
  44576. BABYLON.serialize()
  44577. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44578. __decorate([
  44579. BABYLON.serialize("roughness")
  44580. ], StandardMaterial.prototype, "_roughness", void 0);
  44581. __decorate([
  44582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44583. ], StandardMaterial.prototype, "roughness", void 0);
  44584. __decorate([
  44585. BABYLON.serialize()
  44586. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44587. __decorate([
  44588. BABYLON.serialize()
  44589. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44590. __decorate([
  44591. BABYLON.serialize()
  44592. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44593. __decorate([
  44594. BABYLON.serialize("useLightmapAsShadowmap")
  44595. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44596. __decorate([
  44597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44598. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44599. __decorate([
  44600. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44601. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44602. __decorate([
  44603. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44604. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44605. __decorate([
  44606. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44607. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44608. __decorate([
  44609. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44610. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44611. __decorate([
  44612. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44613. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44614. __decorate([
  44615. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44616. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44617. __decorate([
  44618. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44619. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44620. __decorate([
  44621. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44622. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44623. __decorate([
  44624. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44625. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44626. __decorate([
  44627. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44628. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44629. __decorate([
  44630. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44631. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44632. __decorate([
  44633. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44634. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44635. __decorate([
  44636. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44637. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44638. __decorate([
  44639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44640. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44641. __decorate([
  44642. BABYLON.serialize("maxSimultaneousLights")
  44643. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44644. __decorate([
  44645. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44646. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44647. __decorate([
  44648. BABYLON.serialize("invertNormalMapX")
  44649. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44650. __decorate([
  44651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44652. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44653. __decorate([
  44654. BABYLON.serialize("invertNormalMapY")
  44655. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44656. __decorate([
  44657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44658. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44659. __decorate([
  44660. BABYLON.serialize("twoSidedLighting")
  44661. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44662. __decorate([
  44663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44664. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44665. __decorate([
  44666. BABYLON.serialize()
  44667. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44668. return StandardMaterial;
  44669. }(BABYLON.PushMaterial));
  44670. BABYLON.StandardMaterial = StandardMaterial;
  44671. })(BABYLON || (BABYLON = {}));
  44672. //# sourceMappingURL=babylon.standardMaterial.js.map
  44673. var BABYLON;
  44674. (function (BABYLON) {
  44675. /**
  44676. * Class representing spherical polynomial coefficients to the 3rd degree
  44677. */
  44678. var SphericalPolynomial = /** @class */ (function () {
  44679. function SphericalPolynomial() {
  44680. /**
  44681. * The x coefficients of the spherical polynomial
  44682. */
  44683. this.x = BABYLON.Vector3.Zero();
  44684. /**
  44685. * The y coefficients of the spherical polynomial
  44686. */
  44687. this.y = BABYLON.Vector3.Zero();
  44688. /**
  44689. * The z coefficients of the spherical polynomial
  44690. */
  44691. this.z = BABYLON.Vector3.Zero();
  44692. /**
  44693. * The xx coefficients of the spherical polynomial
  44694. */
  44695. this.xx = BABYLON.Vector3.Zero();
  44696. /**
  44697. * The yy coefficients of the spherical polynomial
  44698. */
  44699. this.yy = BABYLON.Vector3.Zero();
  44700. /**
  44701. * The zz coefficients of the spherical polynomial
  44702. */
  44703. this.zz = BABYLON.Vector3.Zero();
  44704. /**
  44705. * The xy coefficients of the spherical polynomial
  44706. */
  44707. this.xy = BABYLON.Vector3.Zero();
  44708. /**
  44709. * The yz coefficients of the spherical polynomial
  44710. */
  44711. this.yz = BABYLON.Vector3.Zero();
  44712. /**
  44713. * The zx coefficients of the spherical polynomial
  44714. */
  44715. this.zx = BABYLON.Vector3.Zero();
  44716. }
  44717. /**
  44718. * Adds an ambient color to the spherical polynomial
  44719. * @param color the color to add
  44720. */
  44721. SphericalPolynomial.prototype.addAmbient = function (color) {
  44722. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44723. this.xx = this.xx.add(colorVector);
  44724. this.yy = this.yy.add(colorVector);
  44725. this.zz = this.zz.add(colorVector);
  44726. };
  44727. /**
  44728. * Scales the spherical polynomial by the given amount
  44729. * @param scale the amount to scale
  44730. */
  44731. SphericalPolynomial.prototype.scale = function (scale) {
  44732. this.x = this.x.scale(scale);
  44733. this.y = this.y.scale(scale);
  44734. this.z = this.z.scale(scale);
  44735. this.xx = this.xx.scale(scale);
  44736. this.yy = this.yy.scale(scale);
  44737. this.zz = this.zz.scale(scale);
  44738. this.yz = this.yz.scale(scale);
  44739. this.zx = this.zx.scale(scale);
  44740. this.xy = this.xy.scale(scale);
  44741. };
  44742. /**
  44743. * Gets the spherical polynomial from harmonics
  44744. * @param harmonics the spherical harmonics
  44745. * @returns the spherical polynomial
  44746. */
  44747. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44748. var result = new SphericalPolynomial();
  44749. result.x = harmonics.l11.scale(1.02333);
  44750. result.y = harmonics.l1_1.scale(1.02333);
  44751. result.z = harmonics.l10.scale(1.02333);
  44752. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44753. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44754. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44755. result.yz = harmonics.l2_1.scale(0.858086);
  44756. result.zx = harmonics.l21.scale(0.858086);
  44757. result.xy = harmonics.l2_2.scale(0.858086);
  44758. result.scale(1.0 / Math.PI);
  44759. return result;
  44760. };
  44761. /**
  44762. * Constructs a spherical polynomial from an array.
  44763. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44764. * @returns the spherical polynomial
  44765. */
  44766. SphericalPolynomial.FromArray = function (data) {
  44767. var sp = new SphericalPolynomial();
  44768. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44769. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44770. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44771. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44772. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44773. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44774. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44775. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44776. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44777. return sp;
  44778. };
  44779. return SphericalPolynomial;
  44780. }());
  44781. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44782. /**
  44783. * Class representing spherical harmonics coefficients to the 3rd degree
  44784. */
  44785. var SphericalHarmonics = /** @class */ (function () {
  44786. function SphericalHarmonics() {
  44787. /**
  44788. * The l0,0 coefficients of the spherical harmonics
  44789. */
  44790. this.l00 = BABYLON.Vector3.Zero();
  44791. /**
  44792. * The l1,-1 coefficients of the spherical harmonics
  44793. */
  44794. this.l1_1 = BABYLON.Vector3.Zero();
  44795. /**
  44796. * The l1,0 coefficients of the spherical harmonics
  44797. */
  44798. this.l10 = BABYLON.Vector3.Zero();
  44799. /**
  44800. * The l1,1 coefficients of the spherical harmonics
  44801. */
  44802. this.l11 = BABYLON.Vector3.Zero();
  44803. /**
  44804. * The l2,-2 coefficients of the spherical harmonics
  44805. */
  44806. this.l2_2 = BABYLON.Vector3.Zero();
  44807. /**
  44808. * The l2,-1 coefficients of the spherical harmonics
  44809. */
  44810. this.l2_1 = BABYLON.Vector3.Zero();
  44811. /**
  44812. * The l2,0 coefficients of the spherical harmonics
  44813. */
  44814. this.l20 = BABYLON.Vector3.Zero();
  44815. /**
  44816. * The l2,1 coefficients of the spherical harmonics
  44817. */
  44818. this.l21 = BABYLON.Vector3.Zero();
  44819. /**
  44820. * The l2,2 coefficients of the spherical harmonics
  44821. */
  44822. this.lL22 = BABYLON.Vector3.Zero();
  44823. }
  44824. /**
  44825. * Adds a light to the spherical harmonics
  44826. * @param direction the direction of the light
  44827. * @param color the color of the light
  44828. * @param deltaSolidAngle the delta solid angle of the light
  44829. */
  44830. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44831. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44832. var c = colorVector.scale(deltaSolidAngle);
  44833. this.l00 = this.l00.add(c.scale(0.282095));
  44834. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44835. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44836. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44837. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44838. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44839. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44840. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44841. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44842. };
  44843. /**
  44844. * Scales the spherical harmonics by the given amount
  44845. * @param scale the amount to scale
  44846. */
  44847. SphericalHarmonics.prototype.scale = function (scale) {
  44848. this.l00 = this.l00.scale(scale);
  44849. this.l1_1 = this.l1_1.scale(scale);
  44850. this.l10 = this.l10.scale(scale);
  44851. this.l11 = this.l11.scale(scale);
  44852. this.l2_2 = this.l2_2.scale(scale);
  44853. this.l2_1 = this.l2_1.scale(scale);
  44854. this.l20 = this.l20.scale(scale);
  44855. this.l21 = this.l21.scale(scale);
  44856. this.lL22 = this.lL22.scale(scale);
  44857. };
  44858. /**
  44859. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44860. *
  44861. * ```
  44862. * E_lm = A_l * L_lm
  44863. * ```
  44864. *
  44865. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44866. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44867. * the scaling factors are given in equation 9.
  44868. */
  44869. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44870. // Constant (Band 0)
  44871. this.l00 = this.l00.scale(3.141593);
  44872. // Linear (Band 1)
  44873. this.l1_1 = this.l1_1.scale(2.094395);
  44874. this.l10 = this.l10.scale(2.094395);
  44875. this.l11 = this.l11.scale(2.094395);
  44876. // Quadratic (Band 2)
  44877. this.l2_2 = this.l2_2.scale(0.785398);
  44878. this.l2_1 = this.l2_1.scale(0.785398);
  44879. this.l20 = this.l20.scale(0.785398);
  44880. this.l21 = this.l21.scale(0.785398);
  44881. this.lL22 = this.lL22.scale(0.785398);
  44882. };
  44883. /**
  44884. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44885. *
  44886. * ```
  44887. * L = (1/pi) * E * rho
  44888. * ```
  44889. *
  44890. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44891. */
  44892. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44893. this.scale(1.0 / Math.PI);
  44894. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44895. // (The pixel shader must apply albedo after texture fetches, etc).
  44896. };
  44897. /**
  44898. * Gets the spherical harmonics from polynomial
  44899. * @param polynomial the spherical polynomial
  44900. * @returns the spherical harmonics
  44901. */
  44902. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44903. var result = new SphericalHarmonics();
  44904. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44905. result.l1_1 = polynomial.y.scale(0.977204);
  44906. result.l10 = polynomial.z.scale(0.977204);
  44907. result.l11 = polynomial.x.scale(0.977204);
  44908. result.l2_2 = polynomial.xy.scale(1.16538);
  44909. result.l2_1 = polynomial.yz.scale(1.16538);
  44910. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44911. result.l21 = polynomial.zx.scale(1.16538);
  44912. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44913. result.scale(Math.PI);
  44914. return result;
  44915. };
  44916. /**
  44917. * Constructs a spherical harmonics from an array.
  44918. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44919. * @returns the spherical harmonics
  44920. */
  44921. SphericalHarmonics.FromArray = function (data) {
  44922. var sh = new SphericalHarmonics();
  44923. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44924. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44925. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44926. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44927. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44928. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44929. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44930. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44931. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44932. return sh;
  44933. };
  44934. return SphericalHarmonics;
  44935. }());
  44936. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44937. })(BABYLON || (BABYLON = {}));
  44938. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44939. var BABYLON;
  44940. (function (BABYLON) {
  44941. var FileFaceOrientation = /** @class */ (function () {
  44942. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44943. this.name = name;
  44944. this.worldAxisForNormal = worldAxisForNormal;
  44945. this.worldAxisForFileX = worldAxisForFileX;
  44946. this.worldAxisForFileY = worldAxisForFileY;
  44947. }
  44948. return FileFaceOrientation;
  44949. }());
  44950. /**
  44951. * Helper class dealing with the extraction of spherical polynomial dataArray
  44952. * from a cube map.
  44953. */
  44954. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44955. function CubeMapToSphericalPolynomialTools() {
  44956. }
  44957. /**
  44958. * Converts a texture to the according Spherical Polynomial data.
  44959. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44960. *
  44961. * @param texture The texture to extract the information from.
  44962. * @return The Spherical Polynomial data.
  44963. */
  44964. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44965. if (!texture.isCube) {
  44966. // Only supports cube Textures currently.
  44967. return null;
  44968. }
  44969. var size = texture.getSize().width;
  44970. var right = texture.readPixels(0);
  44971. var left = texture.readPixels(1);
  44972. var up;
  44973. var down;
  44974. if (texture.isRenderTarget) {
  44975. up = texture.readPixels(3);
  44976. down = texture.readPixels(2);
  44977. }
  44978. else {
  44979. up = texture.readPixels(2);
  44980. down = texture.readPixels(3);
  44981. }
  44982. var front = texture.readPixels(4);
  44983. var back = texture.readPixels(5);
  44984. var gammaSpace = texture.gammaSpace;
  44985. // Always read as RGBA.
  44986. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44987. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44988. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44989. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44990. }
  44991. var cubeInfo = {
  44992. size: size,
  44993. right: right,
  44994. left: left,
  44995. up: up,
  44996. down: down,
  44997. front: front,
  44998. back: back,
  44999. format: format,
  45000. type: type,
  45001. gammaSpace: gammaSpace,
  45002. };
  45003. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45004. };
  45005. /**
  45006. * Converts a cubemap to the according Spherical Polynomial data.
  45007. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45008. *
  45009. * @param cubeInfo The Cube map to extract the information from.
  45010. * @return The Spherical Polynomial data.
  45011. */
  45012. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45013. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45014. var totalSolidAngle = 0.0;
  45015. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45016. var du = 2.0 / cubeInfo.size;
  45017. var dv = du;
  45018. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45019. var minUV = du * 0.5 - 1.0;
  45020. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45021. var fileFace = this.FileFaces[faceIndex];
  45022. var dataArray = cubeInfo[fileFace.name];
  45023. var v = minUV;
  45024. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45025. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45026. // Because SP is still linear, so summation is fine in that basis.
  45027. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45028. for (var y = 0; y < cubeInfo.size; y++) {
  45029. var u = minUV;
  45030. for (var x = 0; x < cubeInfo.size; x++) {
  45031. // World direction (not normalised)
  45032. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45033. worldDirection.normalize();
  45034. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45035. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45036. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45037. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45038. // Handle Integer types.
  45039. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45040. r /= 255;
  45041. g /= 255;
  45042. b /= 255;
  45043. }
  45044. // Handle Gamma space textures.
  45045. if (cubeInfo.gammaSpace) {
  45046. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45047. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45048. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45049. }
  45050. var color = new BABYLON.Color3(r, g, b);
  45051. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45052. totalSolidAngle += deltaSolidAngle;
  45053. u += du;
  45054. }
  45055. v += dv;
  45056. }
  45057. }
  45058. // Solid angle for entire sphere is 4*pi
  45059. var sphereSolidAngle = 4.0 * Math.PI;
  45060. // Adjust the solid angle to allow for how many faces we processed.
  45061. var facesProcessed = 6.0;
  45062. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45063. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45064. // This is needed because the numerical integration over the cube uses a
  45065. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45066. // and also to compensate for accumulative error due to float precision in the summation.
  45067. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45068. sphericalHarmonics.scale(correctionFactor);
  45069. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45070. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45071. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45072. };
  45073. CubeMapToSphericalPolynomialTools.FileFaces = [
  45074. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45075. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45076. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45077. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45078. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45079. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45080. ];
  45081. return CubeMapToSphericalPolynomialTools;
  45082. }());
  45083. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45084. })(BABYLON || (BABYLON = {}));
  45085. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45086. var BABYLON;
  45087. (function (BABYLON) {
  45088. /**
  45089. * Manages the defines for the PBR Material.
  45090. * @hiddenChildren
  45091. */
  45092. var PBRMaterialDefines = /** @class */ (function (_super) {
  45093. __extends(PBRMaterialDefines, _super);
  45094. /**
  45095. * Initializes the PBR Material defines.
  45096. */
  45097. function PBRMaterialDefines() {
  45098. var _this = _super.call(this) || this;
  45099. _this.PBR = true;
  45100. _this.MAINUV1 = false;
  45101. _this.MAINUV2 = false;
  45102. _this.UV1 = false;
  45103. _this.UV2 = false;
  45104. _this.ALBEDO = false;
  45105. _this.ALBEDODIRECTUV = 0;
  45106. _this.VERTEXCOLOR = false;
  45107. _this.AMBIENT = false;
  45108. _this.AMBIENTDIRECTUV = 0;
  45109. _this.AMBIENTINGRAYSCALE = false;
  45110. _this.OPACITY = false;
  45111. _this.VERTEXALPHA = false;
  45112. _this.OPACITYDIRECTUV = 0;
  45113. _this.OPACITYRGB = false;
  45114. _this.ALPHATEST = false;
  45115. _this.DEPTHPREPASS = false;
  45116. _this.ALPHABLEND = false;
  45117. _this.ALPHAFROMALBEDO = false;
  45118. _this.ALPHATESTVALUE = "0.5";
  45119. _this.SPECULAROVERALPHA = false;
  45120. _this.RADIANCEOVERALPHA = false;
  45121. _this.ALPHAFRESNEL = false;
  45122. _this.LINEARALPHAFRESNEL = false;
  45123. _this.PREMULTIPLYALPHA = false;
  45124. _this.EMISSIVE = false;
  45125. _this.EMISSIVEDIRECTUV = 0;
  45126. _this.REFLECTIVITY = false;
  45127. _this.REFLECTIVITYDIRECTUV = 0;
  45128. _this.SPECULARTERM = false;
  45129. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45130. _this.MICROSURFACEAUTOMATIC = false;
  45131. _this.LODBASEDMICROSFURACE = false;
  45132. _this.MICROSURFACEMAP = false;
  45133. _this.MICROSURFACEMAPDIRECTUV = 0;
  45134. _this.METALLICWORKFLOW = false;
  45135. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45136. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45137. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45138. _this.AOSTOREINMETALMAPRED = false;
  45139. _this.ENVIRONMENTBRDF = false;
  45140. _this.NORMAL = false;
  45141. _this.TANGENT = false;
  45142. _this.BUMP = false;
  45143. _this.BUMPDIRECTUV = 0;
  45144. _this.OBJECTSPACE_NORMALMAP = false;
  45145. _this.PARALLAX = false;
  45146. _this.PARALLAXOCCLUSION = false;
  45147. _this.NORMALXYSCALE = true;
  45148. _this.LIGHTMAP = false;
  45149. _this.LIGHTMAPDIRECTUV = 0;
  45150. _this.USELIGHTMAPASSHADOWMAP = false;
  45151. _this.GAMMALIGHTMAP = false;
  45152. _this.REFLECTION = false;
  45153. _this.REFLECTIONMAP_3D = false;
  45154. _this.REFLECTIONMAP_SPHERICAL = false;
  45155. _this.REFLECTIONMAP_PLANAR = false;
  45156. _this.REFLECTIONMAP_CUBIC = false;
  45157. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45158. _this.REFLECTIONMAP_PROJECTION = false;
  45159. _this.REFLECTIONMAP_SKYBOX = false;
  45160. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45161. _this.REFLECTIONMAP_EXPLICIT = false;
  45162. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45163. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45164. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45165. _this.INVERTCUBICMAP = false;
  45166. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45167. _this.USESPHERICALINVERTEX = false;
  45168. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45169. _this.LODINREFLECTIONALPHA = false;
  45170. _this.GAMMAREFLECTION = false;
  45171. _this.RGBDREFLECTION = false;
  45172. _this.RADIANCEOCCLUSION = false;
  45173. _this.HORIZONOCCLUSION = false;
  45174. _this.REFRACTION = false;
  45175. _this.REFRACTIONMAP_3D = false;
  45176. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45177. _this.LODINREFRACTIONALPHA = false;
  45178. _this.GAMMAREFRACTION = false;
  45179. _this.RGBDREFRACTION = false;
  45180. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45181. _this.INSTANCES = false;
  45182. _this.NUM_BONE_INFLUENCERS = 0;
  45183. _this.BonesPerMesh = 0;
  45184. _this.NONUNIFORMSCALING = false;
  45185. _this.MORPHTARGETS = false;
  45186. _this.MORPHTARGETS_NORMAL = false;
  45187. _this.MORPHTARGETS_TANGENT = false;
  45188. _this.NUM_MORPH_INFLUENCERS = 0;
  45189. _this.IMAGEPROCESSING = false;
  45190. _this.VIGNETTE = false;
  45191. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45192. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45193. _this.TONEMAPPING = false;
  45194. _this.TONEMAPPING_ACES = false;
  45195. _this.CONTRAST = false;
  45196. _this.COLORCURVES = false;
  45197. _this.COLORGRADING = false;
  45198. _this.COLORGRADING3D = false;
  45199. _this.SAMPLER3DGREENDEPTH = false;
  45200. _this.SAMPLER3DBGRMAP = false;
  45201. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45202. _this.EXPOSURE = false;
  45203. _this.USEPHYSICALLIGHTFALLOFF = false;
  45204. _this.USEGLTFLIGHTFALLOFF = false;
  45205. _this.TWOSIDEDLIGHTING = false;
  45206. _this.SHADOWFLOAT = false;
  45207. _this.CLIPPLANE = false;
  45208. _this.CLIPPLANE2 = false;
  45209. _this.CLIPPLANE3 = false;
  45210. _this.CLIPPLANE4 = false;
  45211. _this.POINTSIZE = false;
  45212. _this.FOG = false;
  45213. _this.LOGARITHMICDEPTH = false;
  45214. _this.FORCENORMALFORWARD = false;
  45215. _this.SPECULARAA = false;
  45216. _this.UNLIT = false;
  45217. _this.rebuild();
  45218. return _this;
  45219. }
  45220. /**
  45221. * Resets the PBR Material defines.
  45222. */
  45223. PBRMaterialDefines.prototype.reset = function () {
  45224. _super.prototype.reset.call(this);
  45225. this.ALPHATESTVALUE = "0.5";
  45226. this.PBR = true;
  45227. };
  45228. return PBRMaterialDefines;
  45229. }(BABYLON.MaterialDefines));
  45230. /**
  45231. * The Physically based material base class of BJS.
  45232. *
  45233. * This offers the main features of a standard PBR material.
  45234. * For more information, please refer to the documentation :
  45235. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45236. */
  45237. var PBRBaseMaterial = /** @class */ (function (_super) {
  45238. __extends(PBRBaseMaterial, _super);
  45239. /**
  45240. * Instantiates a new PBRMaterial instance.
  45241. *
  45242. * @param name The material name
  45243. * @param scene The scene the material will be use in.
  45244. */
  45245. function PBRBaseMaterial(name, scene) {
  45246. var _this = _super.call(this, name, scene) || this;
  45247. /**
  45248. * Intensity of the direct lights e.g. the four lights available in your scene.
  45249. * This impacts both the direct diffuse and specular highlights.
  45250. */
  45251. _this._directIntensity = 1.0;
  45252. /**
  45253. * Intensity of the emissive part of the material.
  45254. * This helps controlling the emissive effect without modifying the emissive color.
  45255. */
  45256. _this._emissiveIntensity = 1.0;
  45257. /**
  45258. * Intensity of the environment e.g. how much the environment will light the object
  45259. * either through harmonics for rough material or through the refelction for shiny ones.
  45260. */
  45261. _this._environmentIntensity = 1.0;
  45262. /**
  45263. * This is a special control allowing the reduction of the specular highlights coming from the
  45264. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45265. */
  45266. _this._specularIntensity = 1.0;
  45267. /**
  45268. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45269. */
  45270. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45271. /**
  45272. * Debug Control allowing disabling the bump map on this material.
  45273. */
  45274. _this._disableBumpMap = false;
  45275. /**
  45276. * AKA Occlusion Texture Intensity in other nomenclature.
  45277. */
  45278. _this._ambientTextureStrength = 1.0;
  45279. /**
  45280. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45281. * 1 means it completely occludes it
  45282. * 0 mean it has no impact
  45283. */
  45284. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45285. /**
  45286. * The color of a material in ambient lighting.
  45287. */
  45288. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45289. /**
  45290. * AKA Diffuse Color in other nomenclature.
  45291. */
  45292. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45293. /**
  45294. * AKA Specular Color in other nomenclature.
  45295. */
  45296. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45297. /**
  45298. * The color applied when light is reflected from a material.
  45299. */
  45300. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45301. /**
  45302. * The color applied when light is emitted from a material.
  45303. */
  45304. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45305. /**
  45306. * AKA Glossiness in other nomenclature.
  45307. */
  45308. _this._microSurface = 0.9;
  45309. /**
  45310. * source material index of refraction (IOR)' / 'destination material IOR.
  45311. */
  45312. _this._indexOfRefraction = 0.66;
  45313. /**
  45314. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45315. */
  45316. _this._invertRefractionY = false;
  45317. /**
  45318. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45319. * Materials half opaque for instance using refraction could benefit from this control.
  45320. */
  45321. _this._linkRefractionWithTransparency = false;
  45322. /**
  45323. * Specifies that the material will use the light map as a show map.
  45324. */
  45325. _this._useLightmapAsShadowmap = false;
  45326. /**
  45327. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45328. * makes the reflect vector face the model (under horizon).
  45329. */
  45330. _this._useHorizonOcclusion = true;
  45331. /**
  45332. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45333. * too much the area relying on ambient texture to define their ambient occlusion.
  45334. */
  45335. _this._useRadianceOcclusion = true;
  45336. /**
  45337. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45338. */
  45339. _this._useAlphaFromAlbedoTexture = false;
  45340. /**
  45341. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45342. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45343. */
  45344. _this._useSpecularOverAlpha = true;
  45345. /**
  45346. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45347. */
  45348. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45349. /**
  45350. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45351. */
  45352. _this._useRoughnessFromMetallicTextureAlpha = true;
  45353. /**
  45354. * Specifies if the metallic texture contains the roughness information in its green channel.
  45355. */
  45356. _this._useRoughnessFromMetallicTextureGreen = false;
  45357. /**
  45358. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45359. */
  45360. _this._useMetallnessFromMetallicTextureBlue = false;
  45361. /**
  45362. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45363. */
  45364. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45365. /**
  45366. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45367. */
  45368. _this._useAmbientInGrayScale = false;
  45369. /**
  45370. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45371. * The material will try to infer what glossiness each pixel should be.
  45372. */
  45373. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45374. /**
  45375. * Defines the falloff type used in this material.
  45376. * It by default is Physical.
  45377. */
  45378. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45379. /**
  45380. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45381. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45382. */
  45383. _this._useRadianceOverAlpha = true;
  45384. /**
  45385. * Allows using an object space normal map (instead of tangent space).
  45386. */
  45387. _this._useObjectSpaceNormalMap = false;
  45388. /**
  45389. * Allows using the bump map in parallax mode.
  45390. */
  45391. _this._useParallax = false;
  45392. /**
  45393. * Allows using the bump map in parallax occlusion mode.
  45394. */
  45395. _this._useParallaxOcclusion = false;
  45396. /**
  45397. * Controls the scale bias of the parallax mode.
  45398. */
  45399. _this._parallaxScaleBias = 0.05;
  45400. /**
  45401. * If sets to true, disables all the lights affecting the material.
  45402. */
  45403. _this._disableLighting = false;
  45404. /**
  45405. * Number of Simultaneous lights allowed on the material.
  45406. */
  45407. _this._maxSimultaneousLights = 4;
  45408. /**
  45409. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45410. */
  45411. _this._invertNormalMapX = false;
  45412. /**
  45413. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45414. */
  45415. _this._invertNormalMapY = false;
  45416. /**
  45417. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45418. */
  45419. _this._twoSidedLighting = false;
  45420. /**
  45421. * Defines the alpha limits in alpha test mode.
  45422. */
  45423. _this._alphaCutOff = 0.4;
  45424. /**
  45425. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45426. */
  45427. _this._forceAlphaTest = false;
  45428. /**
  45429. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45430. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45431. */
  45432. _this._useAlphaFresnel = false;
  45433. /**
  45434. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45435. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45436. */
  45437. _this._useLinearAlphaFresnel = false;
  45438. /**
  45439. * The transparency mode of the material.
  45440. */
  45441. _this._transparencyMode = null;
  45442. /**
  45443. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45444. * from cos thetav and roughness:
  45445. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45446. */
  45447. _this._environmentBRDFTexture = null;
  45448. /**
  45449. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45450. */
  45451. _this._forceIrradianceInFragment = false;
  45452. /**
  45453. * Force normal to face away from face.
  45454. */
  45455. _this._forceNormalForward = false;
  45456. /**
  45457. * Enables specular anti aliasing in the PBR shader.
  45458. * It will both interacts on the Geometry for analytical and IBL lighting.
  45459. * It also prefilter the roughness map based on the bump values.
  45460. */
  45461. _this._enableSpecularAntiAliasing = false;
  45462. /**
  45463. * Stores the available render targets.
  45464. */
  45465. _this._renderTargets = new BABYLON.SmartArray(16);
  45466. /**
  45467. * Sets the global ambient color for the material used in lighting calculations.
  45468. */
  45469. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45470. /**
  45471. * If set to true, no lighting calculations will be applied.
  45472. */
  45473. _this._unlit = false;
  45474. // Setup the default processing configuration to the scene.
  45475. _this._attachImageProcessingConfiguration(null);
  45476. _this.getRenderTargetTextures = function () {
  45477. _this._renderTargets.reset();
  45478. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45479. _this._renderTargets.push(_this._reflectionTexture);
  45480. }
  45481. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45482. _this._renderTargets.push(_this._refractionTexture);
  45483. }
  45484. return _this._renderTargets;
  45485. };
  45486. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45487. return _this;
  45488. }
  45489. /**
  45490. * Attaches a new image processing configuration to the PBR Material.
  45491. * @param configuration
  45492. */
  45493. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45494. var _this = this;
  45495. if (configuration === this._imageProcessingConfiguration) {
  45496. return;
  45497. }
  45498. // Detaches observer.
  45499. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45500. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45501. }
  45502. // Pick the scene configuration if needed.
  45503. if (!configuration) {
  45504. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45505. }
  45506. else {
  45507. this._imageProcessingConfiguration = configuration;
  45508. }
  45509. // Attaches observer.
  45510. if (this._imageProcessingConfiguration) {
  45511. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45512. _this._markAllSubMeshesAsImageProcessingDirty();
  45513. });
  45514. }
  45515. };
  45516. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45517. /**
  45518. * Gets a boolean indicating that current material needs to register RTT
  45519. */
  45520. get: function () {
  45521. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45522. return true;
  45523. }
  45524. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45525. return true;
  45526. }
  45527. return false;
  45528. },
  45529. enumerable: true,
  45530. configurable: true
  45531. });
  45532. /**
  45533. * Gets the name of the material class.
  45534. */
  45535. PBRBaseMaterial.prototype.getClassName = function () {
  45536. return "PBRBaseMaterial";
  45537. };
  45538. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45539. /**
  45540. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45541. */
  45542. get: function () {
  45543. return this._useLogarithmicDepth;
  45544. },
  45545. /**
  45546. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45547. */
  45548. set: function (value) {
  45549. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45550. },
  45551. enumerable: true,
  45552. configurable: true
  45553. });
  45554. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45555. /**
  45556. * Gets the current transparency mode.
  45557. */
  45558. get: function () {
  45559. return this._transparencyMode;
  45560. },
  45561. /**
  45562. * Sets the transparency mode of the material.
  45563. *
  45564. * | Value | Type | Description |
  45565. * | ----- | ----------------------------------- | ----------- |
  45566. * | 0 | OPAQUE | |
  45567. * | 1 | ALPHATEST | |
  45568. * | 2 | ALPHABLEND | |
  45569. * | 3 | ALPHATESTANDBLEND | |
  45570. *
  45571. */
  45572. set: function (value) {
  45573. if (this._transparencyMode === value) {
  45574. return;
  45575. }
  45576. this._transparencyMode = value;
  45577. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45578. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45579. },
  45580. enumerable: true,
  45581. configurable: true
  45582. });
  45583. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45584. /**
  45585. * Returns true if alpha blending should be disabled.
  45586. */
  45587. get: function () {
  45588. return (this._linkRefractionWithTransparency ||
  45589. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45590. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45591. },
  45592. enumerable: true,
  45593. configurable: true
  45594. });
  45595. /**
  45596. * Specifies whether or not this material should be rendered in alpha blend mode.
  45597. */
  45598. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45599. if (this._disableAlphaBlending) {
  45600. return false;
  45601. }
  45602. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45603. };
  45604. /**
  45605. * Specifies if the mesh will require alpha blending.
  45606. * @param mesh - BJS mesh.
  45607. */
  45608. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45609. if (this._disableAlphaBlending) {
  45610. return false;
  45611. }
  45612. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45613. };
  45614. /**
  45615. * Specifies whether or not this material should be rendered in alpha test mode.
  45616. */
  45617. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45618. if (this._forceAlphaTest) {
  45619. return true;
  45620. }
  45621. if (this._linkRefractionWithTransparency) {
  45622. return false;
  45623. }
  45624. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45625. };
  45626. /**
  45627. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45628. */
  45629. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45630. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45631. };
  45632. /**
  45633. * Gets the texture used for the alpha test.
  45634. */
  45635. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45636. return this._albedoTexture;
  45637. };
  45638. /**
  45639. * Specifies that the submesh is ready to be used.
  45640. * @param mesh - BJS mesh.
  45641. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45642. * @param useInstances - Specifies that instances should be used.
  45643. * @returns - boolean indicating that the submesh is ready or not.
  45644. */
  45645. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45646. if (subMesh.effect && this.isFrozen) {
  45647. if (this._wasPreviouslyReady) {
  45648. return true;
  45649. }
  45650. }
  45651. if (!subMesh._materialDefines) {
  45652. subMesh._materialDefines = new PBRMaterialDefines();
  45653. }
  45654. var defines = subMesh._materialDefines;
  45655. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45656. if (defines._renderId === this.getScene().getRenderId()) {
  45657. return true;
  45658. }
  45659. }
  45660. var scene = this.getScene();
  45661. var engine = scene.getEngine();
  45662. if (defines._areTexturesDirty) {
  45663. if (scene.texturesEnabled) {
  45664. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45665. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45666. return false;
  45667. }
  45668. }
  45669. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45670. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45671. return false;
  45672. }
  45673. }
  45674. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45675. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45676. return false;
  45677. }
  45678. }
  45679. var reflectionTexture = this._getReflectionTexture();
  45680. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45681. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45682. return false;
  45683. }
  45684. }
  45685. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45686. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45687. return false;
  45688. }
  45689. }
  45690. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45691. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45692. return false;
  45693. }
  45694. }
  45695. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45696. if (this._metallicTexture) {
  45697. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45698. return false;
  45699. }
  45700. }
  45701. else if (this._reflectivityTexture) {
  45702. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45703. return false;
  45704. }
  45705. }
  45706. if (this._microSurfaceTexture) {
  45707. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45708. return false;
  45709. }
  45710. }
  45711. }
  45712. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45713. // Bump texture cannot be not blocking.
  45714. if (!this._bumpTexture.isReady()) {
  45715. return false;
  45716. }
  45717. }
  45718. var refractionTexture = this._getRefractionTexture();
  45719. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45720. if (!refractionTexture.isReadyOrNotBlocking()) {
  45721. return false;
  45722. }
  45723. }
  45724. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45725. // This is blocking.
  45726. if (!this._environmentBRDFTexture.isReady()) {
  45727. return false;
  45728. }
  45729. }
  45730. }
  45731. }
  45732. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45733. if (!this._imageProcessingConfiguration.isReady()) {
  45734. return false;
  45735. }
  45736. }
  45737. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45738. mesh.createNormals(true);
  45739. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45740. }
  45741. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45742. if (effect) {
  45743. scene.resetCachedMaterial();
  45744. subMesh.setEffect(effect, defines);
  45745. this.buildUniformLayout();
  45746. }
  45747. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45748. return false;
  45749. }
  45750. defines._renderId = scene.getRenderId();
  45751. this._wasPreviouslyReady = true;
  45752. return true;
  45753. };
  45754. /**
  45755. * Specifies if the material uses metallic roughness workflow.
  45756. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45757. */
  45758. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45759. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45760. return true;
  45761. }
  45762. return false;
  45763. };
  45764. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45765. if (onCompiled === void 0) { onCompiled = null; }
  45766. if (onError === void 0) { onError = null; }
  45767. if (useInstances === void 0) { useInstances = null; }
  45768. if (useClipPlane === void 0) { useClipPlane = null; }
  45769. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45770. if (!defines.isDirty) {
  45771. return null;
  45772. }
  45773. defines.markAsProcessed();
  45774. var scene = this.getScene();
  45775. var engine = scene.getEngine();
  45776. // Fallbacks
  45777. var fallbacks = new BABYLON.EffectFallbacks();
  45778. var fallbackRank = 0;
  45779. if (defines.USESPHERICALINVERTEX) {
  45780. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45781. }
  45782. if (defines.FOG) {
  45783. fallbacks.addFallback(fallbackRank, "FOG");
  45784. }
  45785. if (defines.SPECULARAA) {
  45786. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45787. }
  45788. if (defines.POINTSIZE) {
  45789. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45790. }
  45791. if (defines.LOGARITHMICDEPTH) {
  45792. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45793. }
  45794. if (defines.PARALLAX) {
  45795. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45796. }
  45797. if (defines.PARALLAXOCCLUSION) {
  45798. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45799. }
  45800. if (defines.ENVIRONMENTBRDF) {
  45801. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45802. }
  45803. if (defines.TANGENT) {
  45804. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45805. }
  45806. if (defines.BUMP) {
  45807. fallbacks.addFallback(fallbackRank++, "BUMP");
  45808. }
  45809. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45810. if (defines.SPECULARTERM) {
  45811. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45812. }
  45813. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45814. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45815. }
  45816. if (defines.LIGHTMAP) {
  45817. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45818. }
  45819. if (defines.NORMAL) {
  45820. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45821. }
  45822. if (defines.AMBIENT) {
  45823. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45824. }
  45825. if (defines.EMISSIVE) {
  45826. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45827. }
  45828. if (defines.VERTEXCOLOR) {
  45829. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45830. }
  45831. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45832. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45833. }
  45834. if (defines.MORPHTARGETS) {
  45835. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45836. }
  45837. //Attributes
  45838. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45839. if (defines.NORMAL) {
  45840. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45841. }
  45842. if (defines.TANGENT) {
  45843. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45844. }
  45845. if (defines.UV1) {
  45846. attribs.push(BABYLON.VertexBuffer.UVKind);
  45847. }
  45848. if (defines.UV2) {
  45849. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45850. }
  45851. if (defines.VERTEXCOLOR) {
  45852. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45853. }
  45854. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45855. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45856. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45857. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45858. "vFogInfos", "vFogColor", "pointSize",
  45859. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45860. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45861. "mBones",
  45862. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45863. "vLightingIntensity",
  45864. "logarithmicDepthConstant",
  45865. "vSphericalX", "vSphericalY", "vSphericalZ",
  45866. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45867. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45868. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45869. "vTangentSpaceParams"
  45870. ];
  45871. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45872. "bumpSampler", "lightmapSampler", "opacitySampler",
  45873. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45874. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45875. "microSurfaceSampler", "environmentBrdfSampler"];
  45876. var uniformBuffers = ["Material", "Scene"];
  45877. if (BABYLON.ImageProcessingConfiguration) {
  45878. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45879. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45880. }
  45881. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45882. uniformsNames: uniforms,
  45883. uniformBuffersNames: uniformBuffers,
  45884. samplers: samplers,
  45885. defines: defines,
  45886. maxSimultaneousLights: this._maxSimultaneousLights
  45887. });
  45888. var join = defines.toString();
  45889. return engine.createEffect("pbr", {
  45890. attributes: attribs,
  45891. uniformsNames: uniforms,
  45892. uniformBuffersNames: uniformBuffers,
  45893. samplers: samplers,
  45894. defines: join,
  45895. fallbacks: fallbacks,
  45896. onCompiled: onCompiled,
  45897. onError: onError,
  45898. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45899. }, engine);
  45900. };
  45901. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45902. if (useInstances === void 0) { useInstances = null; }
  45903. if (useClipPlane === void 0) { useClipPlane = null; }
  45904. var scene = this.getScene();
  45905. var engine = scene.getEngine();
  45906. // Lights
  45907. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45908. defines._needNormals = true;
  45909. // Textures
  45910. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45911. if (defines._areTexturesDirty) {
  45912. defines._needUVs = false;
  45913. if (scene.texturesEnabled) {
  45914. if (scene.getEngine().getCaps().textureLOD) {
  45915. defines.LODBASEDMICROSFURACE = true;
  45916. }
  45917. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45918. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45919. }
  45920. else {
  45921. defines.ALBEDO = false;
  45922. }
  45923. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45924. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45925. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45926. }
  45927. else {
  45928. defines.AMBIENT = false;
  45929. }
  45930. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45931. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45932. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45933. }
  45934. else {
  45935. defines.OPACITY = false;
  45936. }
  45937. var reflectionTexture = this._getReflectionTexture();
  45938. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45939. defines.REFLECTION = true;
  45940. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45941. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45942. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45943. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45944. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45945. defines.INVERTCUBICMAP = true;
  45946. }
  45947. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45948. switch (reflectionTexture.coordinatesMode) {
  45949. case BABYLON.Texture.EXPLICIT_MODE:
  45950. defines.REFLECTIONMAP_EXPLICIT = true;
  45951. break;
  45952. case BABYLON.Texture.PLANAR_MODE:
  45953. defines.REFLECTIONMAP_PLANAR = true;
  45954. break;
  45955. case BABYLON.Texture.PROJECTION_MODE:
  45956. defines.REFLECTIONMAP_PROJECTION = true;
  45957. break;
  45958. case BABYLON.Texture.SKYBOX_MODE:
  45959. defines.REFLECTIONMAP_SKYBOX = true;
  45960. break;
  45961. case BABYLON.Texture.SPHERICAL_MODE:
  45962. defines.REFLECTIONMAP_SPHERICAL = true;
  45963. break;
  45964. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45965. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45966. break;
  45967. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45968. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45969. break;
  45970. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45971. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45972. break;
  45973. case BABYLON.Texture.CUBIC_MODE:
  45974. case BABYLON.Texture.INVCUBIC_MODE:
  45975. default:
  45976. defines.REFLECTIONMAP_CUBIC = true;
  45977. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45978. break;
  45979. }
  45980. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45981. if (reflectionTexture.sphericalPolynomial) {
  45982. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45983. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45984. defines.USESPHERICALINVERTEX = false;
  45985. }
  45986. else {
  45987. defines.USESPHERICALINVERTEX = true;
  45988. }
  45989. }
  45990. }
  45991. else {
  45992. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45993. }
  45994. }
  45995. else {
  45996. defines.REFLECTION = false;
  45997. defines.REFLECTIONMAP_3D = false;
  45998. defines.REFLECTIONMAP_SPHERICAL = false;
  45999. defines.REFLECTIONMAP_PLANAR = false;
  46000. defines.REFLECTIONMAP_CUBIC = false;
  46001. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46002. defines.REFLECTIONMAP_PROJECTION = false;
  46003. defines.REFLECTIONMAP_SKYBOX = false;
  46004. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46005. defines.REFLECTIONMAP_EXPLICIT = false;
  46006. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46007. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46008. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46009. defines.INVERTCUBICMAP = false;
  46010. defines.USESPHERICALFROMREFLECTIONMAP = false;
  46011. defines.USESPHERICALINVERTEX = false;
  46012. defines.REFLECTIONMAP_OPPOSITEZ = false;
  46013. defines.LODINREFLECTIONALPHA = false;
  46014. defines.GAMMAREFLECTION = false;
  46015. defines.RGBDREFLECTION = false;
  46016. }
  46017. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46018. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  46019. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  46020. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  46021. }
  46022. else {
  46023. defines.LIGHTMAP = false;
  46024. }
  46025. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46026. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46027. }
  46028. else {
  46029. defines.EMISSIVE = false;
  46030. }
  46031. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46032. if (this._metallicTexture) {
  46033. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46034. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46035. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46036. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46037. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46038. }
  46039. else if (this._reflectivityTexture) {
  46040. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46041. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46042. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46043. }
  46044. else {
  46045. defines.REFLECTIVITY = false;
  46046. }
  46047. if (this._microSurfaceTexture) {
  46048. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46049. }
  46050. else {
  46051. defines.MICROSURFACEMAP = false;
  46052. }
  46053. }
  46054. else {
  46055. defines.REFLECTIVITY = false;
  46056. defines.MICROSURFACEMAP = false;
  46057. }
  46058. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46059. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46060. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46061. defines.PARALLAX = true;
  46062. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46063. }
  46064. else {
  46065. defines.PARALLAX = false;
  46066. }
  46067. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46068. }
  46069. else {
  46070. defines.BUMP = false;
  46071. }
  46072. var refractionTexture = this._getRefractionTexture();
  46073. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46074. defines.REFRACTION = true;
  46075. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46076. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46077. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46078. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46079. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46080. if (this._linkRefractionWithTransparency) {
  46081. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46082. }
  46083. }
  46084. else {
  46085. defines.REFRACTION = false;
  46086. }
  46087. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46088. defines.ENVIRONMENTBRDF = true;
  46089. }
  46090. else {
  46091. defines.ENVIRONMENTBRDF = false;
  46092. }
  46093. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46094. defines.ALPHAFROMALBEDO = true;
  46095. }
  46096. else {
  46097. defines.ALPHAFROMALBEDO = false;
  46098. }
  46099. }
  46100. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46101. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46102. defines.USEPHYSICALLIGHTFALLOFF = false;
  46103. defines.USEGLTFLIGHTFALLOFF = false;
  46104. }
  46105. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46106. defines.USEPHYSICALLIGHTFALLOFF = false;
  46107. defines.USEGLTFLIGHTFALLOFF = true;
  46108. }
  46109. else {
  46110. defines.USEPHYSICALLIGHTFALLOFF = true;
  46111. defines.USEGLTFLIGHTFALLOFF = false;
  46112. }
  46113. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46114. if (!this.backFaceCulling && this._twoSidedLighting) {
  46115. defines.TWOSIDEDLIGHTING = true;
  46116. }
  46117. else {
  46118. defines.TWOSIDEDLIGHTING = false;
  46119. }
  46120. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46121. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46122. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46123. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46124. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46125. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46126. }
  46127. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46128. this._imageProcessingConfiguration.prepareDefines(defines);
  46129. }
  46130. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46131. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46132. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46133. // Misc.
  46134. if (defines._areMiscDirty) {
  46135. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46136. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46137. }
  46138. // Values that need to be evaluated on every frame
  46139. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46140. // Attribs
  46141. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46142. };
  46143. /**
  46144. * Force shader compilation
  46145. */
  46146. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46147. var _this = this;
  46148. var localOptions = __assign({ clipPlane: false }, options);
  46149. var defines = new PBRMaterialDefines();
  46150. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46151. if (effect.isReady()) {
  46152. if (onCompiled) {
  46153. onCompiled(this);
  46154. }
  46155. }
  46156. else {
  46157. effect.onCompileObservable.add(function () {
  46158. if (onCompiled) {
  46159. onCompiled(_this);
  46160. }
  46161. });
  46162. }
  46163. };
  46164. /**
  46165. * Initializes the uniform buffer layout for the shader.
  46166. */
  46167. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46168. // Order is important !
  46169. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46170. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46171. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46172. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46173. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46174. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46175. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46176. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46177. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46178. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46179. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46180. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46181. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46182. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46183. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46184. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46185. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46186. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46187. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46188. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46189. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46190. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46191. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46192. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46193. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46194. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46195. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46196. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46197. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46198. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46199. this._uniformBuffer.addUniform("pointSize", 1);
  46200. this._uniformBuffer.create();
  46201. };
  46202. /**
  46203. * Unbinds the textures.
  46204. */
  46205. PBRBaseMaterial.prototype.unbind = function () {
  46206. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46207. this._uniformBuffer.setTexture("reflectionSampler", null);
  46208. }
  46209. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46210. this._uniformBuffer.setTexture("refractionSampler", null);
  46211. }
  46212. _super.prototype.unbind.call(this);
  46213. };
  46214. /**
  46215. * Binds the submesh data.
  46216. * @param world - The world matrix.
  46217. * @param mesh - The BJS mesh.
  46218. * @param subMesh - A submesh of the BJS mesh.
  46219. */
  46220. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46221. var scene = this.getScene();
  46222. var defines = subMesh._materialDefines;
  46223. if (!defines) {
  46224. return;
  46225. }
  46226. var effect = subMesh.effect;
  46227. if (!effect) {
  46228. return;
  46229. }
  46230. this._activeEffect = effect;
  46231. // Matrices
  46232. this.bindOnlyWorldMatrix(world);
  46233. // Normal Matrix
  46234. if (defines.OBJECTSPACE_NORMALMAP) {
  46235. world.toNormalMatrix(this._normalMatrix);
  46236. this.bindOnlyNormalMatrix(this._normalMatrix);
  46237. }
  46238. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46239. // Bones
  46240. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46241. var reflectionTexture = null;
  46242. if (mustRebind) {
  46243. this._uniformBuffer.bindToEffect(effect, "Material");
  46244. this.bindViewProjection(effect);
  46245. reflectionTexture = this._getReflectionTexture();
  46246. var refractionTexture = this._getRefractionTexture();
  46247. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46248. // Texture uniforms
  46249. if (scene.texturesEnabled) {
  46250. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46251. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46252. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46253. }
  46254. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46255. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46256. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46257. }
  46258. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46259. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46260. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46261. }
  46262. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46263. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46264. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46265. if (reflectionTexture.boundingBoxSize) {
  46266. var cubeTexture = reflectionTexture;
  46267. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46268. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46269. }
  46270. var polynomials = reflectionTexture.sphericalPolynomial;
  46271. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46272. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46273. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46274. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46275. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46276. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46277. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46278. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46279. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46280. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46281. }
  46282. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46283. }
  46284. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46285. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46286. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46287. }
  46288. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46289. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46290. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46291. }
  46292. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46293. if (this._metallicTexture) {
  46294. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46295. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46296. }
  46297. else if (this._reflectivityTexture) {
  46298. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46299. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46300. }
  46301. if (this._microSurfaceTexture) {
  46302. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46303. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46304. }
  46305. }
  46306. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46307. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46308. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46309. if (scene._mirroredCameraPosition) {
  46310. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46311. }
  46312. else {
  46313. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46314. }
  46315. }
  46316. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46317. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46318. var depth = 1.0;
  46319. if (!refractionTexture.isCube) {
  46320. if (refractionTexture.depth) {
  46321. depth = refractionTexture.depth;
  46322. }
  46323. }
  46324. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46325. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46326. }
  46327. }
  46328. // Point size
  46329. if (this.pointsCloud) {
  46330. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46331. }
  46332. // Colors
  46333. if (defines.METALLICWORKFLOW) {
  46334. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46335. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46336. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46337. }
  46338. else {
  46339. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46340. }
  46341. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46342. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46343. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46344. // Misc
  46345. this._lightingInfos.x = this._directIntensity;
  46346. this._lightingInfos.y = this._emissiveIntensity;
  46347. this._lightingInfos.z = this._environmentIntensity;
  46348. this._lightingInfos.w = this._specularIntensity;
  46349. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46350. }
  46351. // Textures
  46352. if (scene.texturesEnabled) {
  46353. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46354. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46355. }
  46356. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46357. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46358. }
  46359. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46360. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46361. }
  46362. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46363. if (defines.LODBASEDMICROSFURACE) {
  46364. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46365. }
  46366. else {
  46367. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46368. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46369. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46370. }
  46371. }
  46372. if (defines.ENVIRONMENTBRDF) {
  46373. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46374. }
  46375. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46376. if (defines.LODBASEDMICROSFURACE) {
  46377. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46378. }
  46379. else {
  46380. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46381. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46382. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46383. }
  46384. }
  46385. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46386. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46387. }
  46388. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46389. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46390. }
  46391. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46392. if (this._metallicTexture) {
  46393. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46394. }
  46395. else if (this._reflectivityTexture) {
  46396. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46397. }
  46398. if (this._microSurfaceTexture) {
  46399. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46400. }
  46401. }
  46402. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46403. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46404. }
  46405. }
  46406. // Clip plane
  46407. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46408. // Colors
  46409. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46410. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46411. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46412. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46413. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46414. }
  46415. if (mustRebind || !this.isFrozen) {
  46416. // Lights
  46417. if (scene.lightsEnabled && !this._disableLighting) {
  46418. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46419. }
  46420. // View
  46421. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46422. this.bindView(effect);
  46423. }
  46424. // Fog
  46425. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46426. // Morph targets
  46427. if (defines.NUM_MORPH_INFLUENCERS) {
  46428. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46429. }
  46430. // image processing
  46431. this._imageProcessingConfiguration.bind(this._activeEffect);
  46432. // Log. depth
  46433. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46434. }
  46435. this._uniformBuffer.update();
  46436. this._afterBind(mesh, this._activeEffect);
  46437. };
  46438. /**
  46439. * Returns the animatable textures.
  46440. * @returns - Array of animatable textures.
  46441. */
  46442. PBRBaseMaterial.prototype.getAnimatables = function () {
  46443. var results = [];
  46444. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46445. results.push(this._albedoTexture);
  46446. }
  46447. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46448. results.push(this._ambientTexture);
  46449. }
  46450. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46451. results.push(this._opacityTexture);
  46452. }
  46453. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46454. results.push(this._reflectionTexture);
  46455. }
  46456. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46457. results.push(this._emissiveTexture);
  46458. }
  46459. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46460. results.push(this._metallicTexture);
  46461. }
  46462. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46463. results.push(this._reflectivityTexture);
  46464. }
  46465. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46466. results.push(this._bumpTexture);
  46467. }
  46468. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46469. results.push(this._lightmapTexture);
  46470. }
  46471. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46472. results.push(this._refractionTexture);
  46473. }
  46474. return results;
  46475. };
  46476. /**
  46477. * Returns the texture used for reflections.
  46478. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46479. */
  46480. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46481. if (this._reflectionTexture) {
  46482. return this._reflectionTexture;
  46483. }
  46484. return this.getScene().environmentTexture;
  46485. };
  46486. /**
  46487. * Returns the texture used for refraction or null if none is used.
  46488. * @returns - Refection texture if present. If no refraction texture and refraction
  46489. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46490. */
  46491. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46492. if (this._refractionTexture) {
  46493. return this._refractionTexture;
  46494. }
  46495. if (this._linkRefractionWithTransparency) {
  46496. return this.getScene().environmentTexture;
  46497. }
  46498. return null;
  46499. };
  46500. /**
  46501. * Disposes the resources of the material.
  46502. * @param forceDisposeEffect - Forces the disposal of effects.
  46503. * @param forceDisposeTextures - Forces the disposal of all textures.
  46504. */
  46505. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46506. if (forceDisposeTextures) {
  46507. if (this._albedoTexture) {
  46508. this._albedoTexture.dispose();
  46509. }
  46510. if (this._ambientTexture) {
  46511. this._ambientTexture.dispose();
  46512. }
  46513. if (this._opacityTexture) {
  46514. this._opacityTexture.dispose();
  46515. }
  46516. if (this._reflectionTexture) {
  46517. this._reflectionTexture.dispose();
  46518. }
  46519. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46520. this._environmentBRDFTexture.dispose();
  46521. }
  46522. if (this._emissiveTexture) {
  46523. this._emissiveTexture.dispose();
  46524. }
  46525. if (this._metallicTexture) {
  46526. this._metallicTexture.dispose();
  46527. }
  46528. if (this._reflectivityTexture) {
  46529. this._reflectivityTexture.dispose();
  46530. }
  46531. if (this._bumpTexture) {
  46532. this._bumpTexture.dispose();
  46533. }
  46534. if (this._lightmapTexture) {
  46535. this._lightmapTexture.dispose();
  46536. }
  46537. if (this._refractionTexture) {
  46538. this._refractionTexture.dispose();
  46539. }
  46540. }
  46541. this._renderTargets.dispose();
  46542. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46543. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46544. }
  46545. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46546. };
  46547. /**
  46548. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46549. */
  46550. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46551. /**
  46552. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46553. * to enhance interoperability with other engines.
  46554. */
  46555. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46556. /**
  46557. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46558. * to enhance interoperability with other materials.
  46559. */
  46560. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46561. /**
  46562. * Stores the reflectivity values based on metallic roughness workflow.
  46563. */
  46564. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46565. __decorate([
  46566. BABYLON.serializeAsImageProcessingConfiguration()
  46567. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46568. __decorate([
  46569. BABYLON.serialize()
  46570. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46571. __decorate([
  46572. BABYLON.serialize()
  46573. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46574. return PBRBaseMaterial;
  46575. }(BABYLON.PushMaterial));
  46576. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46577. })(BABYLON || (BABYLON = {}));
  46578. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46579. var BABYLON;
  46580. (function (BABYLON) {
  46581. /**
  46582. * The Physically based simple base material of BJS.
  46583. *
  46584. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46585. * It is used as the base class for both the specGloss and metalRough conventions.
  46586. */
  46587. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46588. __extends(PBRBaseSimpleMaterial, _super);
  46589. /**
  46590. * Instantiates a new PBRMaterial instance.
  46591. *
  46592. * @param name The material name
  46593. * @param scene The scene the material will be use in.
  46594. */
  46595. function PBRBaseSimpleMaterial(name, scene) {
  46596. var _this = _super.call(this, name, scene) || this;
  46597. /**
  46598. * Number of Simultaneous lights allowed on the material.
  46599. */
  46600. _this.maxSimultaneousLights = 4;
  46601. /**
  46602. * If sets to true, disables all the lights affecting the material.
  46603. */
  46604. _this.disableLighting = false;
  46605. /**
  46606. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46607. */
  46608. _this.invertNormalMapX = false;
  46609. /**
  46610. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46611. */
  46612. _this.invertNormalMapY = false;
  46613. /**
  46614. * Emissivie color used to self-illuminate the model.
  46615. */
  46616. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46617. /**
  46618. * Occlusion Channel Strenght.
  46619. */
  46620. _this.occlusionStrength = 1.0;
  46621. /**
  46622. * If true, the light map contains occlusion information instead of lighting info.
  46623. */
  46624. _this.useLightmapAsShadowmap = false;
  46625. _this._useAlphaFromAlbedoTexture = true;
  46626. _this._useAmbientInGrayScale = true;
  46627. return _this;
  46628. }
  46629. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46630. /**
  46631. * Gets the current double sided mode.
  46632. */
  46633. get: function () {
  46634. return this._twoSidedLighting;
  46635. },
  46636. /**
  46637. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46638. */
  46639. set: function (value) {
  46640. if (this._twoSidedLighting === value) {
  46641. return;
  46642. }
  46643. this._twoSidedLighting = value;
  46644. this.backFaceCulling = !value;
  46645. this._markAllSubMeshesAsTexturesDirty();
  46646. },
  46647. enumerable: true,
  46648. configurable: true
  46649. });
  46650. /**
  46651. * Return the active textures of the material.
  46652. */
  46653. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46654. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46655. if (this.environmentTexture) {
  46656. activeTextures.push(this.environmentTexture);
  46657. }
  46658. if (this.normalTexture) {
  46659. activeTextures.push(this.normalTexture);
  46660. }
  46661. if (this.emissiveTexture) {
  46662. activeTextures.push(this.emissiveTexture);
  46663. }
  46664. if (this.occlusionTexture) {
  46665. activeTextures.push(this.occlusionTexture);
  46666. }
  46667. if (this.lightmapTexture) {
  46668. activeTextures.push(this.lightmapTexture);
  46669. }
  46670. return activeTextures;
  46671. };
  46672. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46673. if (_super.prototype.hasTexture.call(this, texture)) {
  46674. return true;
  46675. }
  46676. if (this.lightmapTexture === texture) {
  46677. return true;
  46678. }
  46679. return false;
  46680. };
  46681. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46682. return "PBRBaseSimpleMaterial";
  46683. };
  46684. __decorate([
  46685. BABYLON.serialize(),
  46686. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46687. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46688. __decorate([
  46689. BABYLON.serialize(),
  46690. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46691. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46692. __decorate([
  46693. BABYLON.serializeAsTexture(),
  46694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46695. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46696. __decorate([
  46697. BABYLON.serialize(),
  46698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46699. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46700. __decorate([
  46701. BABYLON.serialize(),
  46702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46703. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46704. __decorate([
  46705. BABYLON.serializeAsTexture(),
  46706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46707. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46708. __decorate([
  46709. BABYLON.serializeAsColor3("emissive"),
  46710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46711. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46712. __decorate([
  46713. BABYLON.serializeAsTexture(),
  46714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46715. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46716. __decorate([
  46717. BABYLON.serialize(),
  46718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46719. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46720. __decorate([
  46721. BABYLON.serializeAsTexture(),
  46722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46723. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46724. __decorate([
  46725. BABYLON.serialize(),
  46726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46727. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46728. __decorate([
  46729. BABYLON.serialize()
  46730. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46731. __decorate([
  46732. BABYLON.serializeAsTexture(),
  46733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46734. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46735. __decorate([
  46736. BABYLON.serialize(),
  46737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46738. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46739. return PBRBaseSimpleMaterial;
  46740. }(BABYLON.PBRBaseMaterial));
  46741. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46742. })(BABYLON || (BABYLON = {}));
  46743. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46744. var BABYLON;
  46745. (function (BABYLON) {
  46746. /**
  46747. * The Physically based material of BJS.
  46748. *
  46749. * This offers the main features of a standard PBR material.
  46750. * For more information, please refer to the documentation :
  46751. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46752. */
  46753. var PBRMaterial = /** @class */ (function (_super) {
  46754. __extends(PBRMaterial, _super);
  46755. /**
  46756. * Instantiates a new PBRMaterial instance.
  46757. *
  46758. * @param name The material name
  46759. * @param scene The scene the material will be use in.
  46760. */
  46761. function PBRMaterial(name, scene) {
  46762. var _this = _super.call(this, name, scene) || this;
  46763. /**
  46764. * Intensity of the direct lights e.g. the four lights available in your scene.
  46765. * This impacts both the direct diffuse and specular highlights.
  46766. */
  46767. _this.directIntensity = 1.0;
  46768. /**
  46769. * Intensity of the emissive part of the material.
  46770. * This helps controlling the emissive effect without modifying the emissive color.
  46771. */
  46772. _this.emissiveIntensity = 1.0;
  46773. /**
  46774. * Intensity of the environment e.g. how much the environment will light the object
  46775. * either through harmonics for rough material or through the refelction for shiny ones.
  46776. */
  46777. _this.environmentIntensity = 1.0;
  46778. /**
  46779. * This is a special control allowing the reduction of the specular highlights coming from the
  46780. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46781. */
  46782. _this.specularIntensity = 1.0;
  46783. /**
  46784. * Debug Control allowing disabling the bump map on this material.
  46785. */
  46786. _this.disableBumpMap = false;
  46787. /**
  46788. * AKA Occlusion Texture Intensity in other nomenclature.
  46789. */
  46790. _this.ambientTextureStrength = 1.0;
  46791. /**
  46792. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46793. * 1 means it completely occludes it
  46794. * 0 mean it has no impact
  46795. */
  46796. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46797. /**
  46798. * The color of a material in ambient lighting.
  46799. */
  46800. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46801. /**
  46802. * AKA Diffuse Color in other nomenclature.
  46803. */
  46804. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46805. /**
  46806. * AKA Specular Color in other nomenclature.
  46807. */
  46808. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46809. /**
  46810. * The color reflected from the material.
  46811. */
  46812. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46813. /**
  46814. * The color emitted from the material.
  46815. */
  46816. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46817. /**
  46818. * AKA Glossiness in other nomenclature.
  46819. */
  46820. _this.microSurface = 1.0;
  46821. /**
  46822. * source material index of refraction (IOR)' / 'destination material IOR.
  46823. */
  46824. _this.indexOfRefraction = 0.66;
  46825. /**
  46826. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46827. */
  46828. _this.invertRefractionY = false;
  46829. /**
  46830. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46831. * Materials half opaque for instance using refraction could benefit from this control.
  46832. */
  46833. _this.linkRefractionWithTransparency = false;
  46834. /**
  46835. * If true, the light map contains occlusion information instead of lighting info.
  46836. */
  46837. _this.useLightmapAsShadowmap = false;
  46838. /**
  46839. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46840. */
  46841. _this.useAlphaFromAlbedoTexture = false;
  46842. /**
  46843. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46844. */
  46845. _this.forceAlphaTest = false;
  46846. /**
  46847. * Defines the alpha limits in alpha test mode.
  46848. */
  46849. _this.alphaCutOff = 0.4;
  46850. /**
  46851. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46852. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46853. */
  46854. _this.useSpecularOverAlpha = true;
  46855. /**
  46856. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46857. */
  46858. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46859. /**
  46860. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46861. */
  46862. _this.useRoughnessFromMetallicTextureAlpha = true;
  46863. /**
  46864. * Specifies if the metallic texture contains the roughness information in its green channel.
  46865. */
  46866. _this.useRoughnessFromMetallicTextureGreen = false;
  46867. /**
  46868. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46869. */
  46870. _this.useMetallnessFromMetallicTextureBlue = false;
  46871. /**
  46872. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46873. */
  46874. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46875. /**
  46876. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46877. */
  46878. _this.useAmbientInGrayScale = false;
  46879. /**
  46880. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46881. * The material will try to infer what glossiness each pixel should be.
  46882. */
  46883. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46884. /**
  46885. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46886. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46887. */
  46888. _this.useRadianceOverAlpha = true;
  46889. /**
  46890. * Allows using an object space normal map (instead of tangent space).
  46891. */
  46892. _this.useObjectSpaceNormalMap = false;
  46893. /**
  46894. * Allows using the bump map in parallax mode.
  46895. */
  46896. _this.useParallax = false;
  46897. /**
  46898. * Allows using the bump map in parallax occlusion mode.
  46899. */
  46900. _this.useParallaxOcclusion = false;
  46901. /**
  46902. * Controls the scale bias of the parallax mode.
  46903. */
  46904. _this.parallaxScaleBias = 0.05;
  46905. /**
  46906. * If sets to true, disables all the lights affecting the material.
  46907. */
  46908. _this.disableLighting = false;
  46909. /**
  46910. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46911. */
  46912. _this.forceIrradianceInFragment = false;
  46913. /**
  46914. * Number of Simultaneous lights allowed on the material.
  46915. */
  46916. _this.maxSimultaneousLights = 4;
  46917. /**
  46918. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46919. */
  46920. _this.invertNormalMapX = false;
  46921. /**
  46922. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46923. */
  46924. _this.invertNormalMapY = false;
  46925. /**
  46926. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46927. */
  46928. _this.twoSidedLighting = false;
  46929. /**
  46930. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46931. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46932. */
  46933. _this.useAlphaFresnel = false;
  46934. /**
  46935. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46936. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46937. */
  46938. _this.useLinearAlphaFresnel = false;
  46939. /**
  46940. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46941. * And/Or occlude the blended part.
  46942. */
  46943. _this.environmentBRDFTexture = null;
  46944. /**
  46945. * Force normal to face away from face.
  46946. */
  46947. _this.forceNormalForward = false;
  46948. /**
  46949. * Enables specular anti aliasing in the PBR shader.
  46950. * It will both interacts on the Geometry for analytical and IBL lighting.
  46951. * It also prefilter the roughness map based on the bump values.
  46952. */
  46953. _this.enableSpecularAntiAliasing = false;
  46954. /**
  46955. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46956. * makes the reflect vector face the model (under horizon).
  46957. */
  46958. _this.useHorizonOcclusion = true;
  46959. /**
  46960. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46961. * too much the area relying on ambient texture to define their ambient occlusion.
  46962. */
  46963. _this.useRadianceOcclusion = true;
  46964. /**
  46965. * If set to true, no lighting calculations will be applied.
  46966. */
  46967. _this.unlit = false;
  46968. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46969. return _this;
  46970. }
  46971. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46972. /**
  46973. * BJS is using an harcoded light falloff based on a manually sets up range.
  46974. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46975. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46976. */
  46977. get: function () {
  46978. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46979. },
  46980. /**
  46981. * BJS is using an harcoded light falloff based on a manually sets up range.
  46982. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46983. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46984. */
  46985. set: function (value) {
  46986. if (value !== this.usePhysicalLightFalloff) {
  46987. // Ensure the effect will be rebuilt.
  46988. this._markAllSubMeshesAsTexturesDirty();
  46989. if (value) {
  46990. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46991. }
  46992. else {
  46993. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46994. }
  46995. }
  46996. },
  46997. enumerable: true,
  46998. configurable: true
  46999. });
  47000. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  47001. /**
  47002. * In order to support the falloff compatibility with gltf, a special mode has been added
  47003. * to reproduce the gltf light falloff.
  47004. */
  47005. get: function () {
  47006. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47007. },
  47008. /**
  47009. * In order to support the falloff compatibility with gltf, a special mode has been added
  47010. * to reproduce the gltf light falloff.
  47011. */
  47012. set: function (value) {
  47013. if (value !== this.useGLTFLightFalloff) {
  47014. // Ensure the effect will be rebuilt.
  47015. this._markAllSubMeshesAsTexturesDirty();
  47016. if (value) {
  47017. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47018. }
  47019. else {
  47020. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47021. }
  47022. }
  47023. },
  47024. enumerable: true,
  47025. configurable: true
  47026. });
  47027. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47028. /**
  47029. * Gets the image processing configuration used either in this material.
  47030. */
  47031. get: function () {
  47032. return this._imageProcessingConfiguration;
  47033. },
  47034. /**
  47035. * Sets the Default image processing configuration used either in the this material.
  47036. *
  47037. * If sets to null, the scene one is in use.
  47038. */
  47039. set: function (value) {
  47040. this._attachImageProcessingConfiguration(value);
  47041. // Ensure the effect will be rebuilt.
  47042. this._markAllSubMeshesAsTexturesDirty();
  47043. },
  47044. enumerable: true,
  47045. configurable: true
  47046. });
  47047. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47048. /**
  47049. * Gets wether the color curves effect is enabled.
  47050. */
  47051. get: function () {
  47052. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47053. },
  47054. /**
  47055. * Sets wether the color curves effect is enabled.
  47056. */
  47057. set: function (value) {
  47058. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47059. },
  47060. enumerable: true,
  47061. configurable: true
  47062. });
  47063. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47064. /**
  47065. * Gets wether the color grading effect is enabled.
  47066. */
  47067. get: function () {
  47068. return this.imageProcessingConfiguration.colorGradingEnabled;
  47069. },
  47070. /**
  47071. * Gets wether the color grading effect is enabled.
  47072. */
  47073. set: function (value) {
  47074. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47075. },
  47076. enumerable: true,
  47077. configurable: true
  47078. });
  47079. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47080. /**
  47081. * Gets wether tonemapping is enabled or not.
  47082. */
  47083. get: function () {
  47084. return this._imageProcessingConfiguration.toneMappingEnabled;
  47085. },
  47086. /**
  47087. * Sets wether tonemapping is enabled or not
  47088. */
  47089. set: function (value) {
  47090. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47091. },
  47092. enumerable: true,
  47093. configurable: true
  47094. });
  47095. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47096. /**
  47097. * The camera exposure used on this material.
  47098. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47099. * This corresponds to a photographic exposure.
  47100. */
  47101. get: function () {
  47102. return this._imageProcessingConfiguration.exposure;
  47103. },
  47104. /**
  47105. * The camera exposure used on this material.
  47106. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47107. * This corresponds to a photographic exposure.
  47108. */
  47109. set: function (value) {
  47110. this._imageProcessingConfiguration.exposure = value;
  47111. },
  47112. enumerable: true,
  47113. configurable: true
  47114. });
  47115. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47116. /**
  47117. * Gets The camera contrast used on this material.
  47118. */
  47119. get: function () {
  47120. return this._imageProcessingConfiguration.contrast;
  47121. },
  47122. /**
  47123. * Sets The camera contrast used on this material.
  47124. */
  47125. set: function (value) {
  47126. this._imageProcessingConfiguration.contrast = value;
  47127. },
  47128. enumerable: true,
  47129. configurable: true
  47130. });
  47131. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47132. /**
  47133. * Gets the Color Grading 2D Lookup Texture.
  47134. */
  47135. get: function () {
  47136. return this._imageProcessingConfiguration.colorGradingTexture;
  47137. },
  47138. /**
  47139. * Sets the Color Grading 2D Lookup Texture.
  47140. */
  47141. set: function (value) {
  47142. this._imageProcessingConfiguration.colorGradingTexture = value;
  47143. },
  47144. enumerable: true,
  47145. configurable: true
  47146. });
  47147. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47148. /**
  47149. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47150. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47151. * 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;
  47152. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47153. */
  47154. get: function () {
  47155. return this._imageProcessingConfiguration.colorCurves;
  47156. },
  47157. /**
  47158. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47159. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47160. * 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;
  47161. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47162. */
  47163. set: function (value) {
  47164. this._imageProcessingConfiguration.colorCurves = value;
  47165. },
  47166. enumerable: true,
  47167. configurable: true
  47168. });
  47169. /**
  47170. * Returns the name of this material class.
  47171. */
  47172. PBRMaterial.prototype.getClassName = function () {
  47173. return "PBRMaterial";
  47174. };
  47175. /**
  47176. * Returns an array of the actively used textures.
  47177. * @returns - Array of BaseTextures
  47178. */
  47179. PBRMaterial.prototype.getActiveTextures = function () {
  47180. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47181. if (this._albedoTexture) {
  47182. activeTextures.push(this._albedoTexture);
  47183. }
  47184. if (this._ambientTexture) {
  47185. activeTextures.push(this._ambientTexture);
  47186. }
  47187. if (this._opacityTexture) {
  47188. activeTextures.push(this._opacityTexture);
  47189. }
  47190. if (this._reflectionTexture) {
  47191. activeTextures.push(this._reflectionTexture);
  47192. }
  47193. if (this._emissiveTexture) {
  47194. activeTextures.push(this._emissiveTexture);
  47195. }
  47196. if (this._reflectivityTexture) {
  47197. activeTextures.push(this._reflectivityTexture);
  47198. }
  47199. if (this._metallicTexture) {
  47200. activeTextures.push(this._metallicTexture);
  47201. }
  47202. if (this._microSurfaceTexture) {
  47203. activeTextures.push(this._microSurfaceTexture);
  47204. }
  47205. if (this._bumpTexture) {
  47206. activeTextures.push(this._bumpTexture);
  47207. }
  47208. if (this._lightmapTexture) {
  47209. activeTextures.push(this._lightmapTexture);
  47210. }
  47211. if (this._refractionTexture) {
  47212. activeTextures.push(this._refractionTexture);
  47213. }
  47214. return activeTextures;
  47215. };
  47216. /**
  47217. * Checks to see if a texture is used in the material.
  47218. * @param texture - Base texture to use.
  47219. * @returns - Boolean specifying if a texture is used in the material.
  47220. */
  47221. PBRMaterial.prototype.hasTexture = function (texture) {
  47222. if (_super.prototype.hasTexture.call(this, texture)) {
  47223. return true;
  47224. }
  47225. if (this._albedoTexture === texture) {
  47226. return true;
  47227. }
  47228. if (this._ambientTexture === texture) {
  47229. return true;
  47230. }
  47231. if (this._opacityTexture === texture) {
  47232. return true;
  47233. }
  47234. if (this._reflectionTexture === texture) {
  47235. return true;
  47236. }
  47237. if (this._reflectivityTexture === texture) {
  47238. return true;
  47239. }
  47240. if (this._metallicTexture === texture) {
  47241. return true;
  47242. }
  47243. if (this._microSurfaceTexture === texture) {
  47244. return true;
  47245. }
  47246. if (this._bumpTexture === texture) {
  47247. return true;
  47248. }
  47249. if (this._lightmapTexture === texture) {
  47250. return true;
  47251. }
  47252. if (this._refractionTexture === texture) {
  47253. return true;
  47254. }
  47255. return false;
  47256. };
  47257. /**
  47258. * Makes a duplicate of the current material.
  47259. * @param name - name to use for the new material.
  47260. */
  47261. PBRMaterial.prototype.clone = function (name) {
  47262. var _this = this;
  47263. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47264. clone.id = name;
  47265. clone.name = name;
  47266. return clone;
  47267. };
  47268. /**
  47269. * Serializes this PBR Material.
  47270. * @returns - An object with the serialized material.
  47271. */
  47272. PBRMaterial.prototype.serialize = function () {
  47273. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47274. serializationObject.customType = "BABYLON.PBRMaterial";
  47275. return serializationObject;
  47276. };
  47277. // Statics
  47278. /**
  47279. * Parses a PBR Material from a serialized object.
  47280. * @param source - Serialized object.
  47281. * @param scene - BJS scene instance.
  47282. * @param rootUrl - url for the scene object
  47283. * @returns - PBRMaterial
  47284. */
  47285. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47286. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47287. };
  47288. /**
  47289. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47290. */
  47291. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47292. /**
  47293. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47294. */
  47295. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47296. /**
  47297. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47298. */
  47299. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47300. /**
  47301. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47302. * They are also discarded below the alpha cutoff threshold to improve performances.
  47303. */
  47304. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47305. /**
  47306. * Defines the default value of how much AO map is occluding the analytical lights
  47307. * (point spot...).
  47308. */
  47309. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47310. __decorate([
  47311. BABYLON.serialize(),
  47312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47313. ], PBRMaterial.prototype, "directIntensity", void 0);
  47314. __decorate([
  47315. BABYLON.serialize(),
  47316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47317. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47318. __decorate([
  47319. BABYLON.serialize(),
  47320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47321. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47322. __decorate([
  47323. BABYLON.serialize(),
  47324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47325. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47326. __decorate([
  47327. BABYLON.serialize(),
  47328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47329. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47330. __decorate([
  47331. BABYLON.serializeAsTexture(),
  47332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47333. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47334. __decorate([
  47335. BABYLON.serializeAsTexture(),
  47336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47337. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47338. __decorate([
  47339. BABYLON.serialize(),
  47340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47341. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47342. __decorate([
  47343. BABYLON.serialize(),
  47344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47345. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47346. __decorate([
  47347. BABYLON.serializeAsTexture(),
  47348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47349. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47350. __decorate([
  47351. BABYLON.serializeAsTexture(),
  47352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47353. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47354. __decorate([
  47355. BABYLON.serializeAsTexture(),
  47356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47357. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47358. __decorate([
  47359. BABYLON.serializeAsTexture(),
  47360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47361. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47362. __decorate([
  47363. BABYLON.serializeAsTexture(),
  47364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47365. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47366. __decorate([
  47367. BABYLON.serialize(),
  47368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47369. ], PBRMaterial.prototype, "metallic", void 0);
  47370. __decorate([
  47371. BABYLON.serialize(),
  47372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47373. ], PBRMaterial.prototype, "roughness", void 0);
  47374. __decorate([
  47375. BABYLON.serializeAsTexture(),
  47376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47377. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47378. __decorate([
  47379. BABYLON.serializeAsTexture(),
  47380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47381. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47382. __decorate([
  47383. BABYLON.serializeAsTexture(),
  47384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47385. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47386. __decorate([
  47387. BABYLON.serializeAsTexture(),
  47388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47389. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47390. __decorate([
  47391. BABYLON.serializeAsColor3("ambient"),
  47392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47393. ], PBRMaterial.prototype, "ambientColor", void 0);
  47394. __decorate([
  47395. BABYLON.serializeAsColor3("albedo"),
  47396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47397. ], PBRMaterial.prototype, "albedoColor", void 0);
  47398. __decorate([
  47399. BABYLON.serializeAsColor3("reflectivity"),
  47400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47401. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47402. __decorate([
  47403. BABYLON.serializeAsColor3("reflection"),
  47404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47405. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47406. __decorate([
  47407. BABYLON.serializeAsColor3("emissive"),
  47408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47409. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47410. __decorate([
  47411. BABYLON.serialize(),
  47412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47413. ], PBRMaterial.prototype, "microSurface", void 0);
  47414. __decorate([
  47415. BABYLON.serialize(),
  47416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47417. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47418. __decorate([
  47419. BABYLON.serialize(),
  47420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47421. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47422. __decorate([
  47423. BABYLON.serialize(),
  47424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47425. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47426. __decorate([
  47427. BABYLON.serialize(),
  47428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47429. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47430. __decorate([
  47431. BABYLON.serialize(),
  47432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47433. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47434. __decorate([
  47435. BABYLON.serialize(),
  47436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47437. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47438. __decorate([
  47439. BABYLON.serialize(),
  47440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47441. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47442. __decorate([
  47443. BABYLON.serialize(),
  47444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47445. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47446. __decorate([
  47447. BABYLON.serialize(),
  47448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47449. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47450. __decorate([
  47451. BABYLON.serialize(),
  47452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47453. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47454. __decorate([
  47455. BABYLON.serialize(),
  47456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47457. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47458. __decorate([
  47459. BABYLON.serialize(),
  47460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47461. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47462. __decorate([
  47463. BABYLON.serialize(),
  47464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47465. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47466. __decorate([
  47467. BABYLON.serialize(),
  47468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47469. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47470. __decorate([
  47471. BABYLON.serialize(),
  47472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47473. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47474. __decorate([
  47475. BABYLON.serialize()
  47476. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47477. __decorate([
  47478. BABYLON.serialize()
  47479. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47480. __decorate([
  47481. BABYLON.serialize(),
  47482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47483. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47484. __decorate([
  47485. BABYLON.serialize(),
  47486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47487. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47488. __decorate([
  47489. BABYLON.serialize(),
  47490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47491. ], PBRMaterial.prototype, "useParallax", void 0);
  47492. __decorate([
  47493. BABYLON.serialize(),
  47494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47495. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47496. __decorate([
  47497. BABYLON.serialize(),
  47498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47499. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47500. __decorate([
  47501. BABYLON.serialize(),
  47502. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47503. ], PBRMaterial.prototype, "disableLighting", void 0);
  47504. __decorate([
  47505. BABYLON.serialize(),
  47506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47507. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47508. __decorate([
  47509. BABYLON.serialize(),
  47510. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47511. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47512. __decorate([
  47513. BABYLON.serialize(),
  47514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47515. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47516. __decorate([
  47517. BABYLON.serialize(),
  47518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47519. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47520. __decorate([
  47521. BABYLON.serialize(),
  47522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47523. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47524. __decorate([
  47525. BABYLON.serialize(),
  47526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47527. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47528. __decorate([
  47529. BABYLON.serialize(),
  47530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47531. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47532. __decorate([
  47533. BABYLON.serializeAsTexture(),
  47534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47535. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47536. __decorate([
  47537. BABYLON.serialize(),
  47538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47539. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47540. __decorate([
  47541. BABYLON.serialize(),
  47542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47543. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47544. __decorate([
  47545. BABYLON.serialize(),
  47546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47547. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47548. __decorate([
  47549. BABYLON.serialize(),
  47550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47551. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47552. __decorate([
  47553. BABYLON.serialize(),
  47554. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47555. ], PBRMaterial.prototype, "unlit", void 0);
  47556. return PBRMaterial;
  47557. }(BABYLON.PBRBaseMaterial));
  47558. BABYLON.PBRMaterial = PBRMaterial;
  47559. })(BABYLON || (BABYLON = {}));
  47560. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47561. var BABYLON;
  47562. (function (BABYLON) {
  47563. /**
  47564. * The PBR material of BJS following the metal roughness convention.
  47565. *
  47566. * This fits to the PBR convention in the GLTF definition:
  47567. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47568. */
  47569. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47570. __extends(PBRMetallicRoughnessMaterial, _super);
  47571. /**
  47572. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47573. *
  47574. * @param name The material name
  47575. * @param scene The scene the material will be use in.
  47576. */
  47577. function PBRMetallicRoughnessMaterial(name, scene) {
  47578. var _this = _super.call(this, name, scene) || this;
  47579. _this._useRoughnessFromMetallicTextureAlpha = false;
  47580. _this._useRoughnessFromMetallicTextureGreen = true;
  47581. _this._useMetallnessFromMetallicTextureBlue = true;
  47582. _this.metallic = 1.0;
  47583. _this.roughness = 1.0;
  47584. return _this;
  47585. }
  47586. /**
  47587. * Return the currrent class name of the material.
  47588. */
  47589. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47590. return "PBRMetallicRoughnessMaterial";
  47591. };
  47592. /**
  47593. * Return the active textures of the material.
  47594. */
  47595. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47596. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47597. if (this.baseTexture) {
  47598. activeTextures.push(this.baseTexture);
  47599. }
  47600. if (this.metallicRoughnessTexture) {
  47601. activeTextures.push(this.metallicRoughnessTexture);
  47602. }
  47603. return activeTextures;
  47604. };
  47605. /**
  47606. * Checks to see if a texture is used in the material.
  47607. * @param texture - Base texture to use.
  47608. * @returns - Boolean specifying if a texture is used in the material.
  47609. */
  47610. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47611. if (_super.prototype.hasTexture.call(this, texture)) {
  47612. return true;
  47613. }
  47614. if (this.baseTexture === texture) {
  47615. return true;
  47616. }
  47617. if (this.metallicRoughnessTexture === texture) {
  47618. return true;
  47619. }
  47620. return false;
  47621. };
  47622. /**
  47623. * Makes a duplicate of the current material.
  47624. * @param name - name to use for the new material.
  47625. */
  47626. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47627. var _this = this;
  47628. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47629. clone.id = name;
  47630. clone.name = name;
  47631. return clone;
  47632. };
  47633. /**
  47634. * Serialize the material to a parsable JSON object.
  47635. */
  47636. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47637. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47638. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47639. return serializationObject;
  47640. };
  47641. /**
  47642. * Parses a JSON object correponding to the serialize function.
  47643. */
  47644. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47645. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47646. };
  47647. __decorate([
  47648. BABYLON.serializeAsColor3(),
  47649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47650. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47651. __decorate([
  47652. BABYLON.serializeAsTexture(),
  47653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47654. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47655. __decorate([
  47656. BABYLON.serialize(),
  47657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47658. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47659. __decorate([
  47660. BABYLON.serialize(),
  47661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47662. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47663. __decorate([
  47664. BABYLON.serializeAsTexture(),
  47665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47666. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47667. return PBRMetallicRoughnessMaterial;
  47668. }(BABYLON.PBRBaseSimpleMaterial));
  47669. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47670. })(BABYLON || (BABYLON = {}));
  47671. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47672. var BABYLON;
  47673. (function (BABYLON) {
  47674. /**
  47675. * The PBR material of BJS following the specular glossiness convention.
  47676. *
  47677. * This fits to the PBR convention in the GLTF definition:
  47678. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47679. */
  47680. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47681. __extends(PBRSpecularGlossinessMaterial, _super);
  47682. /**
  47683. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47684. *
  47685. * @param name The material name
  47686. * @param scene The scene the material will be use in.
  47687. */
  47688. function PBRSpecularGlossinessMaterial(name, scene) {
  47689. var _this = _super.call(this, name, scene) || this;
  47690. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47691. return _this;
  47692. }
  47693. /**
  47694. * Return the currrent class name of the material.
  47695. */
  47696. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47697. return "PBRSpecularGlossinessMaterial";
  47698. };
  47699. /**
  47700. * Return the active textures of the material.
  47701. */
  47702. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47703. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47704. if (this.diffuseTexture) {
  47705. activeTextures.push(this.diffuseTexture);
  47706. }
  47707. if (this.specularGlossinessTexture) {
  47708. activeTextures.push(this.specularGlossinessTexture);
  47709. }
  47710. return activeTextures;
  47711. };
  47712. /**
  47713. * Checks to see if a texture is used in the material.
  47714. * @param texture - Base texture to use.
  47715. * @returns - Boolean specifying if a texture is used in the material.
  47716. */
  47717. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47718. if (_super.prototype.hasTexture.call(this, texture)) {
  47719. return true;
  47720. }
  47721. if (this.diffuseTexture === texture) {
  47722. return true;
  47723. }
  47724. if (this.specularGlossinessTexture === texture) {
  47725. return true;
  47726. }
  47727. return false;
  47728. };
  47729. /**
  47730. * Makes a duplicate of the current material.
  47731. * @param name - name to use for the new material.
  47732. */
  47733. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47734. var _this = this;
  47735. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47736. clone.id = name;
  47737. clone.name = name;
  47738. return clone;
  47739. };
  47740. /**
  47741. * Serialize the material to a parsable JSON object.
  47742. */
  47743. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47744. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47745. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47746. return serializationObject;
  47747. };
  47748. /**
  47749. * Parses a JSON object correponding to the serialize function.
  47750. */
  47751. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47752. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47753. };
  47754. __decorate([
  47755. BABYLON.serializeAsColor3("diffuse"),
  47756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47757. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47758. __decorate([
  47759. BABYLON.serializeAsTexture(),
  47760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47761. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47762. __decorate([
  47763. BABYLON.serializeAsColor3("specular"),
  47764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47765. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47766. __decorate([
  47767. BABYLON.serialize(),
  47768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47769. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47770. __decorate([
  47771. BABYLON.serializeAsTexture(),
  47772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47773. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47774. return PBRSpecularGlossinessMaterial;
  47775. }(BABYLON.PBRBaseSimpleMaterial));
  47776. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47777. })(BABYLON || (BABYLON = {}));
  47778. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47779. var BABYLON;
  47780. (function (BABYLON) {
  47781. /**
  47782. * @ignore
  47783. * This is a list of all the different input types that are available in the application.
  47784. * Fo instance: ArcRotateCameraGamepadInput...
  47785. */
  47786. BABYLON.CameraInputTypes = {};
  47787. /**
  47788. * This represents the input manager used within a camera.
  47789. * It helps dealing with all the different kind of input attached to a camera.
  47790. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47791. */
  47792. var CameraInputsManager = /** @class */ (function () {
  47793. /**
  47794. * Instantiate a new Camera Input Manager.
  47795. * @param camera Defines the camera the input manager blongs to
  47796. */
  47797. function CameraInputsManager(camera) {
  47798. this.attached = {};
  47799. this.camera = camera;
  47800. this.checkInputs = function () { };
  47801. }
  47802. /**
  47803. * Add an input method to a camera
  47804. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47805. * @param input camera input method
  47806. */
  47807. CameraInputsManager.prototype.add = function (input) {
  47808. var type = input.getSimpleName();
  47809. if (this.attached[type]) {
  47810. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47811. return;
  47812. }
  47813. this.attached[type] = input;
  47814. input.camera = this.camera;
  47815. //for checkInputs, we are dynamically creating a function
  47816. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47817. if (input.checkInputs) {
  47818. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47819. }
  47820. if (this.attachedElement) {
  47821. input.attachControl(this.attachedElement);
  47822. }
  47823. };
  47824. /**
  47825. * Remove a specific input method from a camera
  47826. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47827. * @param inputToRemove camera input method
  47828. */
  47829. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47830. for (var cam in this.attached) {
  47831. var input = this.attached[cam];
  47832. if (input === inputToRemove) {
  47833. input.detachControl(this.attachedElement);
  47834. input.camera = null;
  47835. delete this.attached[cam];
  47836. this.rebuildInputCheck();
  47837. }
  47838. }
  47839. };
  47840. /**
  47841. * Remove a specific input type from a camera
  47842. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47843. * @param inputType the type of the input to remove
  47844. */
  47845. CameraInputsManager.prototype.removeByType = function (inputType) {
  47846. for (var cam in this.attached) {
  47847. var input = this.attached[cam];
  47848. if (input.getClassName() === inputType) {
  47849. input.detachControl(this.attachedElement);
  47850. input.camera = null;
  47851. delete this.attached[cam];
  47852. this.rebuildInputCheck();
  47853. }
  47854. }
  47855. };
  47856. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47857. var current = this.checkInputs;
  47858. return function () {
  47859. current();
  47860. fn();
  47861. };
  47862. };
  47863. /**
  47864. * Attach the input controls to the currently attached dom element to listen the events from.
  47865. * @param input Defines the input to attach
  47866. */
  47867. CameraInputsManager.prototype.attachInput = function (input) {
  47868. if (this.attachedElement) {
  47869. input.attachControl(this.attachedElement, this.noPreventDefault);
  47870. }
  47871. };
  47872. /**
  47873. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47874. * @param element Defines the dom element to collect the events from
  47875. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47876. */
  47877. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47878. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47879. if (this.attachedElement) {
  47880. return;
  47881. }
  47882. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47883. this.attachedElement = element;
  47884. this.noPreventDefault = noPreventDefault;
  47885. for (var cam in this.attached) {
  47886. this.attached[cam].attachControl(element, noPreventDefault);
  47887. }
  47888. };
  47889. /**
  47890. * Detach the current manager inputs controls from a specific dom element.
  47891. * @param element Defines the dom element to collect the events from
  47892. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47893. */
  47894. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47895. if (disconnect === void 0) { disconnect = false; }
  47896. if (this.attachedElement !== element) {
  47897. return;
  47898. }
  47899. for (var cam in this.attached) {
  47900. this.attached[cam].detachControl(element);
  47901. if (disconnect) {
  47902. this.attached[cam].camera = null;
  47903. }
  47904. }
  47905. this.attachedElement = null;
  47906. };
  47907. /**
  47908. * Rebuild the dynamic inputCheck function from the current list of
  47909. * defined inputs in the manager.
  47910. */
  47911. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47912. this.checkInputs = function () { };
  47913. for (var cam in this.attached) {
  47914. var input = this.attached[cam];
  47915. if (input.checkInputs) {
  47916. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47917. }
  47918. }
  47919. };
  47920. /**
  47921. * Remove all attached input methods from a camera
  47922. */
  47923. CameraInputsManager.prototype.clear = function () {
  47924. if (this.attachedElement) {
  47925. this.detachElement(this.attachedElement, true);
  47926. }
  47927. this.attached = {};
  47928. this.attachedElement = null;
  47929. this.checkInputs = function () { };
  47930. };
  47931. /**
  47932. * Serialize the current input manager attached to a camera.
  47933. * This ensures than once parsed,
  47934. * the input associated to the camera will be identical to the current ones
  47935. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47936. */
  47937. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47938. var inputs = {};
  47939. for (var cam in this.attached) {
  47940. var input = this.attached[cam];
  47941. var res = BABYLON.SerializationHelper.Serialize(input);
  47942. inputs[input.getClassName()] = res;
  47943. }
  47944. serializedCamera.inputsmgr = inputs;
  47945. };
  47946. /**
  47947. * Parses an input manager serialized JSON to restore the previous list of inputs
  47948. * and states associated to a camera.
  47949. * @param parsedCamera Defines the JSON to parse
  47950. */
  47951. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47952. var parsedInputs = parsedCamera.inputsmgr;
  47953. if (parsedInputs) {
  47954. this.clear();
  47955. for (var n in parsedInputs) {
  47956. var construct = BABYLON.CameraInputTypes[n];
  47957. if (construct) {
  47958. var parsedinput = parsedInputs[n];
  47959. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47960. this.add(input);
  47961. }
  47962. }
  47963. }
  47964. else {
  47965. //2016-03-08 this part is for managing backward compatibility
  47966. for (var n in this.attached) {
  47967. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47968. if (construct) {
  47969. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47970. this.remove(this.attached[n]);
  47971. this.add(input);
  47972. }
  47973. }
  47974. }
  47975. };
  47976. return CameraInputsManager;
  47977. }());
  47978. BABYLON.CameraInputsManager = CameraInputsManager;
  47979. })(BABYLON || (BABYLON = {}));
  47980. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47981. var BABYLON;
  47982. (function (BABYLON) {
  47983. /**
  47984. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47985. * This is the base of the follow, arc rotate cameras and Free camera
  47986. * @see http://doc.babylonjs.com/features/cameras
  47987. */
  47988. var TargetCamera = /** @class */ (function (_super) {
  47989. __extends(TargetCamera, _super);
  47990. /**
  47991. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47992. * This is the base of the follow, arc rotate cameras and Free camera
  47993. * @see http://doc.babylonjs.com/features/cameras
  47994. * @param name Defines the name of the camera in the scene
  47995. * @param position Defines the start position of the camera in the scene
  47996. * @param scene Defines the scene the camera belongs to
  47997. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47998. */
  47999. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48000. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48001. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48002. /**
  48003. * Define the current direction the camera is moving to
  48004. */
  48005. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48006. /**
  48007. * Define the current rotation the camera is rotating to
  48008. */
  48009. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  48010. /**
  48011. * Define the current rotation of the camera
  48012. */
  48013. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  48014. /**
  48015. * Define the current speed of the camera
  48016. */
  48017. _this.speed = 2.0;
  48018. /**
  48019. * Add cconstraint to the camera to prevent it to move freely in all directions and
  48020. * around all axis.
  48021. */
  48022. _this.noRotationConstraint = false;
  48023. /**
  48024. * Define the current target of the camera as an object or a position.
  48025. */
  48026. _this.lockedTarget = null;
  48027. /** @hidden */
  48028. _this._currentTarget = BABYLON.Vector3.Zero();
  48029. /** @hidden */
  48030. _this._viewMatrix = BABYLON.Matrix.Zero();
  48031. /** @hidden */
  48032. _this._camMatrix = BABYLON.Matrix.Zero();
  48033. /** @hidden */
  48034. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48035. /** @hidden */
  48036. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48037. /** @hidden */
  48038. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48039. /** @hidden */
  48040. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48041. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48042. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48043. _this._defaultUp = BABYLON.Vector3.Up();
  48044. _this._cachedRotationZ = 0;
  48045. _this._cachedQuaternionRotationZ = 0;
  48046. return _this;
  48047. }
  48048. /**
  48049. * Gets the position in front of the camera at a given distance.
  48050. * @param distance The distance from the camera we want the position to be
  48051. * @returns the position
  48052. */
  48053. TargetCamera.prototype.getFrontPosition = function (distance) {
  48054. this.getWorldMatrix();
  48055. var direction = this.getTarget().subtract(this.position);
  48056. direction.normalize();
  48057. direction.scaleInPlace(distance);
  48058. return this.globalPosition.add(direction);
  48059. };
  48060. /** @hidden */
  48061. TargetCamera.prototype._getLockedTargetPosition = function () {
  48062. if (!this.lockedTarget) {
  48063. return null;
  48064. }
  48065. if (this.lockedTarget.absolutePosition) {
  48066. this.lockedTarget.computeWorldMatrix();
  48067. }
  48068. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48069. };
  48070. /**
  48071. * Store current camera state of the camera (fov, position, rotation, etc..)
  48072. * @returns the camera
  48073. */
  48074. TargetCamera.prototype.storeState = function () {
  48075. this._storedPosition = this.position.clone();
  48076. this._storedRotation = this.rotation.clone();
  48077. if (this.rotationQuaternion) {
  48078. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48079. }
  48080. return _super.prototype.storeState.call(this);
  48081. };
  48082. /**
  48083. * Restored camera state. You must call storeState() first
  48084. * @returns whether it was successful or not
  48085. * @hidden
  48086. */
  48087. TargetCamera.prototype._restoreStateValues = function () {
  48088. if (!_super.prototype._restoreStateValues.call(this)) {
  48089. return false;
  48090. }
  48091. this.position = this._storedPosition.clone();
  48092. this.rotation = this._storedRotation.clone();
  48093. if (this.rotationQuaternion) {
  48094. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48095. }
  48096. this.cameraDirection.copyFromFloats(0, 0, 0);
  48097. this.cameraRotation.copyFromFloats(0, 0);
  48098. return true;
  48099. };
  48100. /** @hidden */
  48101. TargetCamera.prototype._initCache = function () {
  48102. _super.prototype._initCache.call(this);
  48103. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48104. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48105. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48106. };
  48107. /** @hidden */
  48108. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48109. if (!ignoreParentClass) {
  48110. _super.prototype._updateCache.call(this);
  48111. }
  48112. var lockedTargetPosition = this._getLockedTargetPosition();
  48113. if (!lockedTargetPosition) {
  48114. this._cache.lockedTarget = null;
  48115. }
  48116. else {
  48117. if (!this._cache.lockedTarget) {
  48118. this._cache.lockedTarget = lockedTargetPosition.clone();
  48119. }
  48120. else {
  48121. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48122. }
  48123. }
  48124. this._cache.rotation.copyFrom(this.rotation);
  48125. if (this.rotationQuaternion) {
  48126. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48127. }
  48128. };
  48129. // Synchronized
  48130. /** @hidden */
  48131. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48132. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48133. return false;
  48134. }
  48135. var lockedTargetPosition = this._getLockedTargetPosition();
  48136. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48137. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48138. };
  48139. // Methods
  48140. /** @hidden */
  48141. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48142. var engine = this.getEngine();
  48143. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48144. };
  48145. // Target
  48146. /** @hidden */
  48147. TargetCamera.prototype.setTarget = function (target) {
  48148. this.upVector.normalize();
  48149. if (this.position.z === target.z) {
  48150. this.position.z += BABYLON.Epsilon;
  48151. }
  48152. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48153. this._camMatrix.invert();
  48154. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48155. var vDir = target.subtract(this.position);
  48156. if (vDir.x >= 0.0) {
  48157. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48158. }
  48159. else {
  48160. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48161. }
  48162. this.rotation.z = 0;
  48163. if (isNaN(this.rotation.x)) {
  48164. this.rotation.x = 0;
  48165. }
  48166. if (isNaN(this.rotation.y)) {
  48167. this.rotation.y = 0;
  48168. }
  48169. if (isNaN(this.rotation.z)) {
  48170. this.rotation.z = 0;
  48171. }
  48172. if (this.rotationQuaternion) {
  48173. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48174. }
  48175. };
  48176. /**
  48177. * Return the current target position of the camera. This value is expressed in local space.
  48178. * @returns the target position
  48179. */
  48180. TargetCamera.prototype.getTarget = function () {
  48181. return this._currentTarget;
  48182. };
  48183. /** @hidden */
  48184. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48185. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48186. };
  48187. /** @hidden */
  48188. TargetCamera.prototype._updatePosition = function () {
  48189. if (this.parent) {
  48190. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48191. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48192. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48193. return;
  48194. }
  48195. this.position.addInPlace(this.cameraDirection);
  48196. };
  48197. /** @hidden */
  48198. TargetCamera.prototype._checkInputs = function () {
  48199. var needToMove = this._decideIfNeedsToMove();
  48200. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48201. // Move
  48202. if (needToMove) {
  48203. this._updatePosition();
  48204. }
  48205. // Rotate
  48206. if (needToRotate) {
  48207. this.rotation.x += this.cameraRotation.x;
  48208. this.rotation.y += this.cameraRotation.y;
  48209. //rotate, if quaternion is set and rotation was used
  48210. if (this.rotationQuaternion) {
  48211. var len = this.rotation.lengthSquared();
  48212. if (len) {
  48213. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48214. }
  48215. }
  48216. if (!this.noRotationConstraint) {
  48217. var limit = (Math.PI / 2) * 0.95;
  48218. if (this.rotation.x > limit) {
  48219. this.rotation.x = limit;
  48220. }
  48221. if (this.rotation.x < -limit) {
  48222. this.rotation.x = -limit;
  48223. }
  48224. }
  48225. }
  48226. // Inertia
  48227. if (needToMove) {
  48228. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48229. this.cameraDirection.x = 0;
  48230. }
  48231. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48232. this.cameraDirection.y = 0;
  48233. }
  48234. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48235. this.cameraDirection.z = 0;
  48236. }
  48237. this.cameraDirection.scaleInPlace(this.inertia);
  48238. }
  48239. if (needToRotate) {
  48240. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48241. this.cameraRotation.x = 0;
  48242. }
  48243. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48244. this.cameraRotation.y = 0;
  48245. }
  48246. this.cameraRotation.scaleInPlace(this.inertia);
  48247. }
  48248. _super.prototype._checkInputs.call(this);
  48249. };
  48250. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48251. if (this.rotationQuaternion) {
  48252. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48253. }
  48254. else {
  48255. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48256. }
  48257. };
  48258. /**
  48259. * 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)
  48260. * @returns the current camera
  48261. */
  48262. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48263. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48264. return this;
  48265. };
  48266. /** @hidden */
  48267. TargetCamera.prototype._getViewMatrix = function () {
  48268. if (this.lockedTarget) {
  48269. this.setTarget(this._getLockedTargetPosition());
  48270. }
  48271. // Compute
  48272. this._updateCameraRotationMatrix();
  48273. // Apply the changed rotation to the upVector
  48274. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48275. this._rotateUpVectorWithCameraRotationMatrix();
  48276. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48277. }
  48278. else if (this._cachedRotationZ != this.rotation.z) {
  48279. this._rotateUpVectorWithCameraRotationMatrix();
  48280. this._cachedRotationZ = this.rotation.z;
  48281. }
  48282. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48283. // Computing target and final matrix
  48284. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48285. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48286. return this._viewMatrix;
  48287. };
  48288. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48289. if (this.parent) {
  48290. var parentWorldMatrix = this.parent.getWorldMatrix();
  48291. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48292. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48293. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48294. this._markSyncedWithParent();
  48295. }
  48296. else {
  48297. this._globalPosition.copyFrom(position);
  48298. this._globalCurrentTarget.copyFrom(target);
  48299. this._globalCurrentUpVector.copyFrom(up);
  48300. }
  48301. if (this.getScene().useRightHandedSystem) {
  48302. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48303. }
  48304. else {
  48305. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48306. }
  48307. };
  48308. /**
  48309. * @hidden
  48310. */
  48311. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48312. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48313. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48314. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48315. if (!this.rotationQuaternion) {
  48316. this.rotationQuaternion = new BABYLON.Quaternion();
  48317. }
  48318. rigCamera._cameraRigParams = {};
  48319. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48320. }
  48321. return rigCamera;
  48322. }
  48323. return null;
  48324. };
  48325. /**
  48326. * @hidden
  48327. */
  48328. TargetCamera.prototype._updateRigCameras = function () {
  48329. var camLeft = this._rigCameras[0];
  48330. var camRight = this._rigCameras[1];
  48331. switch (this.cameraRigMode) {
  48332. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48333. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48334. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48335. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48336. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48337. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48338. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48339. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48340. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48341. camLeft.setTarget(this.getTarget());
  48342. camRight.setTarget(this.getTarget());
  48343. break;
  48344. case BABYLON.Camera.RIG_MODE_VR:
  48345. if (camLeft.rotationQuaternion) {
  48346. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48347. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48348. }
  48349. else {
  48350. camLeft.rotation.copyFrom(this.rotation);
  48351. camRight.rotation.copyFrom(this.rotation);
  48352. }
  48353. camLeft.position.copyFrom(this.position);
  48354. camRight.position.copyFrom(this.position);
  48355. break;
  48356. }
  48357. _super.prototype._updateRigCameras.call(this);
  48358. };
  48359. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48360. if (!this._rigCamTransformMatrix) {
  48361. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48362. }
  48363. var target = this.getTarget();
  48364. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48365. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48366. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48367. };
  48368. /**
  48369. * Gets the current object class name.
  48370. * @return the class name
  48371. */
  48372. TargetCamera.prototype.getClassName = function () {
  48373. return "TargetCamera";
  48374. };
  48375. __decorate([
  48376. BABYLON.serializeAsVector3()
  48377. ], TargetCamera.prototype, "rotation", void 0);
  48378. __decorate([
  48379. BABYLON.serialize()
  48380. ], TargetCamera.prototype, "speed", void 0);
  48381. __decorate([
  48382. BABYLON.serializeAsMeshReference("lockedTargetId")
  48383. ], TargetCamera.prototype, "lockedTarget", void 0);
  48384. return TargetCamera;
  48385. }(BABYLON.Camera));
  48386. BABYLON.TargetCamera = TargetCamera;
  48387. })(BABYLON || (BABYLON = {}));
  48388. //# sourceMappingURL=babylon.targetCamera.js.map
  48389. var BABYLON;
  48390. (function (BABYLON) {
  48391. /**
  48392. * Manage the mouse inputs to control the movement of a free camera.
  48393. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48394. */
  48395. var FreeCameraMouseInput = /** @class */ (function () {
  48396. /**
  48397. * Manage the mouse inputs to control the movement of a free camera.
  48398. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48399. * @param touchEnabled Defines if touch is enabled or not
  48400. */
  48401. function FreeCameraMouseInput(
  48402. /**
  48403. * Define if touch is enabled in the mouse input
  48404. */
  48405. touchEnabled) {
  48406. if (touchEnabled === void 0) { touchEnabled = true; }
  48407. this.touchEnabled = touchEnabled;
  48408. /**
  48409. * Defines the buttons associated with the input to handle camera move.
  48410. */
  48411. this.buttons = [0, 1, 2];
  48412. /**
  48413. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48414. */
  48415. this.angularSensibility = 2000.0;
  48416. this.previousPosition = null;
  48417. }
  48418. /**
  48419. * Attach the input controls to a specific dom element to get the input from.
  48420. * @param element Defines the element the controls should be listened from
  48421. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48422. */
  48423. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48424. var _this = this;
  48425. var engine = this.camera.getEngine();
  48426. if (!this._pointerInput) {
  48427. this._pointerInput = function (p, s) {
  48428. var evt = p.event;
  48429. if (engine.isInVRExclusivePointerMode) {
  48430. return;
  48431. }
  48432. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48433. return;
  48434. }
  48435. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48436. return;
  48437. }
  48438. var srcElement = (evt.srcElement || evt.target);
  48439. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48440. try {
  48441. srcElement.setPointerCapture(evt.pointerId);
  48442. }
  48443. catch (e) {
  48444. //Nothing to do with the error. Execution will continue.
  48445. }
  48446. _this.previousPosition = {
  48447. x: evt.clientX,
  48448. y: evt.clientY
  48449. };
  48450. if (!noPreventDefault) {
  48451. evt.preventDefault();
  48452. element.focus();
  48453. }
  48454. }
  48455. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48456. try {
  48457. srcElement.releasePointerCapture(evt.pointerId);
  48458. }
  48459. catch (e) {
  48460. //Nothing to do with the error.
  48461. }
  48462. _this.previousPosition = null;
  48463. if (!noPreventDefault) {
  48464. evt.preventDefault();
  48465. }
  48466. }
  48467. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48468. if (!_this.previousPosition || engine.isPointerLock) {
  48469. return;
  48470. }
  48471. var offsetX = evt.clientX - _this.previousPosition.x;
  48472. if (_this.camera.getScene().useRightHandedSystem) {
  48473. offsetX *= -1;
  48474. }
  48475. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48476. offsetX *= -1;
  48477. }
  48478. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48479. var offsetY = evt.clientY - _this.previousPosition.y;
  48480. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48481. _this.previousPosition = {
  48482. x: evt.clientX,
  48483. y: evt.clientY
  48484. };
  48485. if (!noPreventDefault) {
  48486. evt.preventDefault();
  48487. }
  48488. }
  48489. };
  48490. }
  48491. this._onMouseMove = function (evt) {
  48492. if (!engine.isPointerLock) {
  48493. return;
  48494. }
  48495. if (engine.isInVRExclusivePointerMode) {
  48496. return;
  48497. }
  48498. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48499. if (_this.camera.getScene().useRightHandedSystem) {
  48500. offsetX *= -1;
  48501. }
  48502. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48503. offsetX *= -1;
  48504. }
  48505. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48506. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48507. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48508. _this.previousPosition = null;
  48509. if (!noPreventDefault) {
  48510. evt.preventDefault();
  48511. }
  48512. };
  48513. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48514. element.addEventListener("mousemove", this._onMouseMove, false);
  48515. };
  48516. /**
  48517. * Detach the current controls from the specified dom element.
  48518. * @param element Defines the element to stop listening the inputs from
  48519. */
  48520. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48521. if (this._observer && element) {
  48522. this.camera.getScene().onPointerObservable.remove(this._observer);
  48523. if (this._onMouseMove) {
  48524. element.removeEventListener("mousemove", this._onMouseMove);
  48525. }
  48526. this._observer = null;
  48527. this._onMouseMove = null;
  48528. this.previousPosition = null;
  48529. }
  48530. };
  48531. /**
  48532. * Gets the class name of the current intput.
  48533. * @returns the class name
  48534. */
  48535. FreeCameraMouseInput.prototype.getClassName = function () {
  48536. return "FreeCameraMouseInput";
  48537. };
  48538. /**
  48539. * Get the friendly name associated with the input class.
  48540. * @returns the input friendly name
  48541. */
  48542. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48543. return "mouse";
  48544. };
  48545. __decorate([
  48546. BABYLON.serialize()
  48547. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48548. __decorate([
  48549. BABYLON.serialize()
  48550. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48551. return FreeCameraMouseInput;
  48552. }());
  48553. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48554. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48555. })(BABYLON || (BABYLON = {}));
  48556. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48557. var BABYLON;
  48558. (function (BABYLON) {
  48559. /**
  48560. * Manage the keyboard inputs to control the movement of a free camera.
  48561. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48562. */
  48563. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48564. function FreeCameraKeyboardMoveInput() {
  48565. /**
  48566. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48567. */
  48568. this.keysUp = [38];
  48569. /**
  48570. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48571. */
  48572. this.keysDown = [40];
  48573. /**
  48574. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48575. */
  48576. this.keysLeft = [37];
  48577. /**
  48578. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48579. */
  48580. this.keysRight = [39];
  48581. this._keys = new Array();
  48582. }
  48583. /**
  48584. * Attach the input controls to a specific dom element to get the input from.
  48585. * @param element Defines the element the controls should be listened from
  48586. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48587. */
  48588. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48589. var _this = this;
  48590. if (this._onCanvasBlurObserver) {
  48591. return;
  48592. }
  48593. this._scene = this.camera.getScene();
  48594. this._engine = this._scene.getEngine();
  48595. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48596. _this._keys = [];
  48597. });
  48598. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48599. var evt = info.event;
  48600. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48601. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48602. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48603. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48604. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48605. var index = _this._keys.indexOf(evt.keyCode);
  48606. if (index === -1) {
  48607. _this._keys.push(evt.keyCode);
  48608. }
  48609. if (!noPreventDefault) {
  48610. evt.preventDefault();
  48611. }
  48612. }
  48613. }
  48614. else {
  48615. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48616. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48617. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48618. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48619. var index = _this._keys.indexOf(evt.keyCode);
  48620. if (index >= 0) {
  48621. _this._keys.splice(index, 1);
  48622. }
  48623. if (!noPreventDefault) {
  48624. evt.preventDefault();
  48625. }
  48626. }
  48627. }
  48628. });
  48629. };
  48630. /**
  48631. * Detach the current controls from the specified dom element.
  48632. * @param element Defines the element to stop listening the inputs from
  48633. */
  48634. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48635. if (this._scene) {
  48636. if (this._onKeyboardObserver) {
  48637. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48638. }
  48639. if (this._onCanvasBlurObserver) {
  48640. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48641. }
  48642. this._onKeyboardObserver = null;
  48643. this._onCanvasBlurObserver = null;
  48644. }
  48645. this._keys = [];
  48646. };
  48647. /**
  48648. * Update the current camera state depending on the inputs that have been used this frame.
  48649. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48650. */
  48651. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48652. if (this._onKeyboardObserver) {
  48653. var camera = this.camera;
  48654. // Keyboard
  48655. for (var index = 0; index < this._keys.length; index++) {
  48656. var keyCode = this._keys[index];
  48657. var speed = camera._computeLocalCameraSpeed();
  48658. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48659. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48660. }
  48661. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48662. camera._localDirection.copyFromFloats(0, 0, speed);
  48663. }
  48664. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48665. camera._localDirection.copyFromFloats(speed, 0, 0);
  48666. }
  48667. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48668. camera._localDirection.copyFromFloats(0, 0, -speed);
  48669. }
  48670. if (camera.getScene().useRightHandedSystem) {
  48671. camera._localDirection.z *= -1;
  48672. }
  48673. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48674. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48675. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48676. }
  48677. }
  48678. };
  48679. /**
  48680. * Gets the class name of the current intput.
  48681. * @returns the class name
  48682. */
  48683. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48684. return "FreeCameraKeyboardMoveInput";
  48685. };
  48686. /** @hidden */
  48687. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48688. this._keys = [];
  48689. };
  48690. /**
  48691. * Get the friendly name associated with the input class.
  48692. * @returns the input friendly name
  48693. */
  48694. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48695. return "keyboard";
  48696. };
  48697. __decorate([
  48698. BABYLON.serialize()
  48699. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48700. __decorate([
  48701. BABYLON.serialize()
  48702. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48703. __decorate([
  48704. BABYLON.serialize()
  48705. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48706. __decorate([
  48707. BABYLON.serialize()
  48708. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48709. return FreeCameraKeyboardMoveInput;
  48710. }());
  48711. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48712. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48713. })(BABYLON || (BABYLON = {}));
  48714. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48715. var BABYLON;
  48716. (function (BABYLON) {
  48717. /**
  48718. * Default Inputs manager for the FreeCamera.
  48719. * It groups all the default supported inputs for ease of use.
  48720. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48721. */
  48722. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48723. __extends(FreeCameraInputsManager, _super);
  48724. /**
  48725. * Instantiates a new FreeCameraInputsManager.
  48726. * @param camera Defines the camera the inputs belong to
  48727. */
  48728. function FreeCameraInputsManager(camera) {
  48729. return _super.call(this, camera) || this;
  48730. }
  48731. /**
  48732. * Add keyboard input support to the input manager.
  48733. * @returns the current input manager
  48734. */
  48735. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48736. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48737. return this;
  48738. };
  48739. /**
  48740. * Add mouse input support to the input manager.
  48741. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  48742. * @returns the current input manager
  48743. */
  48744. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48745. if (touchEnabled === void 0) { touchEnabled = true; }
  48746. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48747. return this;
  48748. };
  48749. /**
  48750. * Add orientation input support to the input manager.
  48751. * @returns the current input manager
  48752. */
  48753. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48754. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48755. return this;
  48756. };
  48757. /**
  48758. * Add touch input support to the input manager.
  48759. * @returns the current input manager
  48760. */
  48761. FreeCameraInputsManager.prototype.addTouch = function () {
  48762. this.add(new BABYLON.FreeCameraTouchInput());
  48763. return this;
  48764. };
  48765. /**
  48766. * Add virtual joystick input support to the input manager.
  48767. * @returns the current input manager
  48768. */
  48769. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48770. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48771. return this;
  48772. };
  48773. return FreeCameraInputsManager;
  48774. }(BABYLON.CameraInputsManager));
  48775. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48776. })(BABYLON || (BABYLON = {}));
  48777. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48778. var BABYLON;
  48779. (function (BABYLON) {
  48780. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48781. // Forcing to use the Universal camera
  48782. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48783. });
  48784. /**
  48785. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48786. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48787. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48788. */
  48789. var FreeCamera = /** @class */ (function (_super) {
  48790. __extends(FreeCamera, _super);
  48791. /**
  48792. * Instantiates a Free Camera.
  48793. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48794. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48795. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48796. * @param name Define the name of the camera in the scene
  48797. * @param position Define the start position of the camera in the scene
  48798. * @param scene Define the scene the camera belongs to
  48799. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48800. */
  48801. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48802. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48803. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48804. /**
  48805. * Define the collision ellipsoid of the camera.
  48806. * This is helpful to simulate a camera body like the player body around the camera
  48807. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48808. */
  48809. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48810. /**
  48811. * Define an offset for the position of the ellipsoid around the camera.
  48812. * This can be helpful to determine the center of the body near the gravity center of the body
  48813. * instead of its head.
  48814. */
  48815. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48816. /**
  48817. * Enable or disable collisions of the camera with the rest of the scene objects.
  48818. */
  48819. _this.checkCollisions = false;
  48820. /**
  48821. * Enable or disable gravity on the camera.
  48822. */
  48823. _this.applyGravity = false;
  48824. _this._needMoveForGravity = false;
  48825. _this._oldPosition = BABYLON.Vector3.Zero();
  48826. _this._diffPosition = BABYLON.Vector3.Zero();
  48827. _this._newPosition = BABYLON.Vector3.Zero();
  48828. // Collisions
  48829. _this._collisionMask = -1;
  48830. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48831. if (collidedMesh === void 0) { collidedMesh = null; }
  48832. //TODO move this to the collision coordinator!
  48833. if (_this.getScene().workerCollisions) {
  48834. newPosition.multiplyInPlace(_this._collider._radius);
  48835. }
  48836. var updatePosition = function (newPos) {
  48837. _this._newPosition.copyFrom(newPos);
  48838. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48839. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48840. _this.position.addInPlace(_this._diffPosition);
  48841. if (_this.onCollide && collidedMesh) {
  48842. _this.onCollide(collidedMesh);
  48843. }
  48844. }
  48845. };
  48846. updatePosition(newPosition);
  48847. };
  48848. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48849. _this.inputs.addKeyboard().addMouse();
  48850. return _this;
  48851. }
  48852. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48853. /**
  48854. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48855. * Higher values reduce sensitivity.
  48856. */
  48857. get: function () {
  48858. var mouse = this.inputs.attached["mouse"];
  48859. if (mouse) {
  48860. return mouse.angularSensibility;
  48861. }
  48862. return 0;
  48863. },
  48864. /**
  48865. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48866. * Higher values reduce sensitivity.
  48867. */
  48868. set: function (value) {
  48869. var mouse = this.inputs.attached["mouse"];
  48870. if (mouse) {
  48871. mouse.angularSensibility = value;
  48872. }
  48873. },
  48874. enumerable: true,
  48875. configurable: true
  48876. });
  48877. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48878. /**
  48879. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48880. */
  48881. get: function () {
  48882. var keyboard = this.inputs.attached["keyboard"];
  48883. if (keyboard) {
  48884. return keyboard.keysUp;
  48885. }
  48886. return [];
  48887. },
  48888. set: function (value) {
  48889. var keyboard = this.inputs.attached["keyboard"];
  48890. if (keyboard) {
  48891. keyboard.keysUp = value;
  48892. }
  48893. },
  48894. enumerable: true,
  48895. configurable: true
  48896. });
  48897. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48898. /**
  48899. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48900. */
  48901. get: function () {
  48902. var keyboard = this.inputs.attached["keyboard"];
  48903. if (keyboard) {
  48904. return keyboard.keysDown;
  48905. }
  48906. return [];
  48907. },
  48908. set: function (value) {
  48909. var keyboard = this.inputs.attached["keyboard"];
  48910. if (keyboard) {
  48911. keyboard.keysDown = value;
  48912. }
  48913. },
  48914. enumerable: true,
  48915. configurable: true
  48916. });
  48917. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48918. /**
  48919. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48920. */
  48921. get: function () {
  48922. var keyboard = this.inputs.attached["keyboard"];
  48923. if (keyboard) {
  48924. return keyboard.keysLeft;
  48925. }
  48926. return [];
  48927. },
  48928. set: function (value) {
  48929. var keyboard = this.inputs.attached["keyboard"];
  48930. if (keyboard) {
  48931. keyboard.keysLeft = value;
  48932. }
  48933. },
  48934. enumerable: true,
  48935. configurable: true
  48936. });
  48937. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48938. /**
  48939. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48940. */
  48941. get: function () {
  48942. var keyboard = this.inputs.attached["keyboard"];
  48943. if (keyboard) {
  48944. return keyboard.keysRight;
  48945. }
  48946. return [];
  48947. },
  48948. set: function (value) {
  48949. var keyboard = this.inputs.attached["keyboard"];
  48950. if (keyboard) {
  48951. keyboard.keysRight = value;
  48952. }
  48953. },
  48954. enumerable: true,
  48955. configurable: true
  48956. });
  48957. /**
  48958. * Attached controls to the current camera.
  48959. * @param element Defines the element the controls should be listened from
  48960. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48961. */
  48962. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48963. this.inputs.attachElement(element, noPreventDefault);
  48964. };
  48965. /**
  48966. * Detach the current controls from the camera.
  48967. * The camera will stop reacting to inputs.
  48968. * @param element Defines the element to stop listening the inputs from
  48969. */
  48970. FreeCamera.prototype.detachControl = function (element) {
  48971. this.inputs.detachElement(element);
  48972. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48973. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48974. };
  48975. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48976. /**
  48977. * Define a collision mask to limit the list of object the camera can collide with
  48978. */
  48979. get: function () {
  48980. return this._collisionMask;
  48981. },
  48982. set: function (mask) {
  48983. this._collisionMask = !isNaN(mask) ? mask : -1;
  48984. },
  48985. enumerable: true,
  48986. configurable: true
  48987. });
  48988. /** @hidden */
  48989. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48990. var globalPosition;
  48991. if (this.parent) {
  48992. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48993. }
  48994. else {
  48995. globalPosition = this.position;
  48996. }
  48997. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48998. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48999. if (!this._collider) {
  49000. this._collider = new BABYLON.Collider();
  49001. }
  49002. this._collider._radius = this.ellipsoid;
  49003. this._collider.collisionMask = this._collisionMask;
  49004. //no need for clone, as long as gravity is not on.
  49005. var actualDisplacement = displacement;
  49006. //add gravity to the direction to prevent the dual-collision checking
  49007. if (this.applyGravity) {
  49008. //this prevents mending with cameraDirection, a global variable of the free camera class.
  49009. actualDisplacement = displacement.add(this.getScene().gravity);
  49010. }
  49011. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49012. };
  49013. /** @hidden */
  49014. FreeCamera.prototype._checkInputs = function () {
  49015. if (!this._localDirection) {
  49016. this._localDirection = BABYLON.Vector3.Zero();
  49017. this._transformedDirection = BABYLON.Vector3.Zero();
  49018. }
  49019. this.inputs.checkInputs();
  49020. _super.prototype._checkInputs.call(this);
  49021. };
  49022. /** @hidden */
  49023. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49024. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49025. };
  49026. /** @hidden */
  49027. FreeCamera.prototype._updatePosition = function () {
  49028. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49029. this._collideWithWorld(this.cameraDirection);
  49030. }
  49031. else {
  49032. _super.prototype._updatePosition.call(this);
  49033. }
  49034. };
  49035. /**
  49036. * Destroy the camera and release the current resources hold by it.
  49037. */
  49038. FreeCamera.prototype.dispose = function () {
  49039. this.inputs.clear();
  49040. _super.prototype.dispose.call(this);
  49041. };
  49042. /**
  49043. * Gets the current object class name.
  49044. * @return the class name
  49045. */
  49046. FreeCamera.prototype.getClassName = function () {
  49047. return "FreeCamera";
  49048. };
  49049. __decorate([
  49050. BABYLON.serializeAsVector3()
  49051. ], FreeCamera.prototype, "ellipsoid", void 0);
  49052. __decorate([
  49053. BABYLON.serializeAsVector3()
  49054. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49055. __decorate([
  49056. BABYLON.serialize()
  49057. ], FreeCamera.prototype, "checkCollisions", void 0);
  49058. __decorate([
  49059. BABYLON.serialize()
  49060. ], FreeCamera.prototype, "applyGravity", void 0);
  49061. return FreeCamera;
  49062. }(BABYLON.TargetCamera));
  49063. BABYLON.FreeCamera = FreeCamera;
  49064. })(BABYLON || (BABYLON = {}));
  49065. //# sourceMappingURL=babylon.freeCamera.js.map
  49066. var BABYLON;
  49067. (function (BABYLON) {
  49068. /**
  49069. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  49070. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49071. */
  49072. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  49073. function ArcRotateCameraKeyboardMoveInput() {
  49074. /**
  49075. * Defines the list of key codes associated with the up action (increase alpha)
  49076. */
  49077. this.keysUp = [38];
  49078. /**
  49079. * Defines the list of key codes associated with the down action (decrease alpha)
  49080. */
  49081. this.keysDown = [40];
  49082. /**
  49083. * Defines the list of key codes associated with the left action (increase beta)
  49084. */
  49085. this.keysLeft = [37];
  49086. /**
  49087. * Defines the list of key codes associated with the right action (decrease beta)
  49088. */
  49089. this.keysRight = [39];
  49090. /**
  49091. * Defines the list of key codes associated with the reset action.
  49092. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  49093. */
  49094. this.keysReset = [220];
  49095. /**
  49096. * Defines the panning sensibility of the inputs.
  49097. * (How fast is the camera paning)
  49098. */
  49099. this.panningSensibility = 50.0;
  49100. /**
  49101. * Defines the zooming sensibility of the inputs.
  49102. * (How fast is the camera zooming)
  49103. */
  49104. this.zoomingSensibility = 25.0;
  49105. /**
  49106. * Defines wether maintaining the alt key down switch the movement mode from
  49107. * orientation to zoom.
  49108. */
  49109. this.useAltToZoom = true;
  49110. /**
  49111. * Rotation speed of the camera
  49112. */
  49113. this.angularSpeed = 0.01;
  49114. this._keys = new Array();
  49115. }
  49116. /**
  49117. * Attach the input controls to a specific dom element to get the input from.
  49118. * @param element Defines the element the controls should be listened from
  49119. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49120. */
  49121. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  49122. var _this = this;
  49123. if (this._onCanvasBlurObserver) {
  49124. return;
  49125. }
  49126. this._scene = this.camera.getScene();
  49127. this._engine = this._scene.getEngine();
  49128. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49129. _this._keys = [];
  49130. });
  49131. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49132. var evt = info.event;
  49133. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49134. _this._ctrlPressed = evt.ctrlKey;
  49135. _this._altPressed = evt.altKey;
  49136. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49137. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49138. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49139. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49140. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49141. var index = _this._keys.indexOf(evt.keyCode);
  49142. if (index === -1) {
  49143. _this._keys.push(evt.keyCode);
  49144. }
  49145. if (evt.preventDefault) {
  49146. if (!noPreventDefault) {
  49147. evt.preventDefault();
  49148. }
  49149. }
  49150. }
  49151. }
  49152. else {
  49153. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49154. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49155. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49156. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49157. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49158. var index = _this._keys.indexOf(evt.keyCode);
  49159. if (index >= 0) {
  49160. _this._keys.splice(index, 1);
  49161. }
  49162. if (evt.preventDefault) {
  49163. if (!noPreventDefault) {
  49164. evt.preventDefault();
  49165. }
  49166. }
  49167. }
  49168. }
  49169. });
  49170. };
  49171. /**
  49172. * Detach the current controls from the specified dom element.
  49173. * @param element Defines the element to stop listening the inputs from
  49174. */
  49175. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  49176. if (this._scene) {
  49177. if (this._onKeyboardObserver) {
  49178. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49179. }
  49180. if (this._onCanvasBlurObserver) {
  49181. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49182. }
  49183. this._onKeyboardObserver = null;
  49184. this._onCanvasBlurObserver = null;
  49185. }
  49186. this._keys = [];
  49187. };
  49188. /**
  49189. * Update the current camera state depending on the inputs that have been used this frame.
  49190. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49191. */
  49192. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49193. if (this._onKeyboardObserver) {
  49194. var camera = this.camera;
  49195. for (var index = 0; index < this._keys.length; index++) {
  49196. var keyCode = this._keys[index];
  49197. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49198. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49199. camera.inertialPanningX -= 1 / this.panningSensibility;
  49200. }
  49201. else {
  49202. camera.inertialAlphaOffset -= this.angularSpeed;
  49203. }
  49204. }
  49205. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49206. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49207. camera.inertialPanningY += 1 / this.panningSensibility;
  49208. }
  49209. else if (this._altPressed && this.useAltToZoom) {
  49210. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  49211. }
  49212. else {
  49213. camera.inertialBetaOffset -= this.angularSpeed;
  49214. }
  49215. }
  49216. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49217. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49218. camera.inertialPanningX += 1 / this.panningSensibility;
  49219. }
  49220. else {
  49221. camera.inertialAlphaOffset += this.angularSpeed;
  49222. }
  49223. }
  49224. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49225. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49226. camera.inertialPanningY -= 1 / this.panningSensibility;
  49227. }
  49228. else if (this._altPressed && this.useAltToZoom) {
  49229. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  49230. }
  49231. else {
  49232. camera.inertialBetaOffset += this.angularSpeed;
  49233. }
  49234. }
  49235. else if (this.keysReset.indexOf(keyCode) !== -1) {
  49236. if (camera.useInputToRestoreState) {
  49237. camera.restoreState();
  49238. }
  49239. }
  49240. }
  49241. }
  49242. };
  49243. /**
  49244. * Gets the class name of the current intput.
  49245. * @returns the class name
  49246. */
  49247. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  49248. return "ArcRotateCameraKeyboardMoveInput";
  49249. };
  49250. /**
  49251. * Get the friendly name associated with the input class.
  49252. * @returns the input friendly name
  49253. */
  49254. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49255. return "keyboard";
  49256. };
  49257. __decorate([
  49258. BABYLON.serialize()
  49259. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49260. __decorate([
  49261. BABYLON.serialize()
  49262. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49263. __decorate([
  49264. BABYLON.serialize()
  49265. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49266. __decorate([
  49267. BABYLON.serialize()
  49268. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49269. __decorate([
  49270. BABYLON.serialize()
  49271. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  49272. __decorate([
  49273. BABYLON.serialize()
  49274. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  49275. __decorate([
  49276. BABYLON.serialize()
  49277. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  49278. __decorate([
  49279. BABYLON.serialize()
  49280. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  49281. __decorate([
  49282. BABYLON.serialize()
  49283. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  49284. return ArcRotateCameraKeyboardMoveInput;
  49285. }());
  49286. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  49287. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  49288. })(BABYLON || (BABYLON = {}));
  49289. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  49290. var BABYLON;
  49291. (function (BABYLON) {
  49292. /**
  49293. * Manage the mouse wheel inputs to control an arc rotate camera.
  49294. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49295. */
  49296. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  49297. function ArcRotateCameraMouseWheelInput() {
  49298. /**
  49299. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49300. */
  49301. this.wheelPrecision = 3.0;
  49302. /**
  49303. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  49304. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  49305. */
  49306. this.wheelDeltaPercentage = 0;
  49307. }
  49308. /**
  49309. * Attach the input controls to a specific dom element to get the input from.
  49310. * @param element Defines the element the controls should be listened from
  49311. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49312. */
  49313. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  49314. var _this = this;
  49315. this._wheel = function (p, s) {
  49316. //sanity check - this should be a PointerWheel event.
  49317. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  49318. return;
  49319. }
  49320. var event = p.event;
  49321. var delta = 0;
  49322. if (event.wheelDelta) {
  49323. if (_this.wheelDeltaPercentage) {
  49324. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  49325. if (event.wheelDelta > 0) {
  49326. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  49327. }
  49328. else {
  49329. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  49330. }
  49331. }
  49332. else {
  49333. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  49334. }
  49335. }
  49336. else if (event.detail) {
  49337. delta = -event.detail / _this.wheelPrecision;
  49338. }
  49339. if (delta) {
  49340. _this.camera.inertialRadiusOffset += delta;
  49341. }
  49342. if (event.preventDefault) {
  49343. if (!noPreventDefault) {
  49344. event.preventDefault();
  49345. }
  49346. }
  49347. };
  49348. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  49349. };
  49350. /**
  49351. * Detach the current controls from the specified dom element.
  49352. * @param element Defines the element to stop listening the inputs from
  49353. */
  49354. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  49355. if (this._observer && element) {
  49356. this.camera.getScene().onPointerObservable.remove(this._observer);
  49357. this._observer = null;
  49358. this._wheel = null;
  49359. }
  49360. };
  49361. /**
  49362. * Gets the class name of the current intput.
  49363. * @returns the class name
  49364. */
  49365. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  49366. return "ArcRotateCameraMouseWheelInput";
  49367. };
  49368. /**
  49369. * Get the friendly name associated with the input class.
  49370. * @returns the input friendly name
  49371. */
  49372. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  49373. return "mousewheel";
  49374. };
  49375. __decorate([
  49376. BABYLON.serialize()
  49377. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  49378. __decorate([
  49379. BABYLON.serialize()
  49380. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  49381. return ArcRotateCameraMouseWheelInput;
  49382. }());
  49383. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  49384. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  49385. })(BABYLON || (BABYLON = {}));
  49386. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  49387. var BABYLON;
  49388. (function (BABYLON) {
  49389. /**
  49390. * Manage the pointers inputs to control an arc rotate camera.
  49391. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49392. */
  49393. var ArcRotateCameraPointersInput = /** @class */ (function () {
  49394. function ArcRotateCameraPointersInput() {
  49395. /**
  49396. * Defines the buttons associated with the input to handle camera move.
  49397. */
  49398. this.buttons = [0, 1, 2];
  49399. /**
  49400. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49401. */
  49402. this.angularSensibilityX = 1000.0;
  49403. /**
  49404. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49405. */
  49406. this.angularSensibilityY = 1000.0;
  49407. /**
  49408. * Defines the pointer pinch precision or how fast is the camera zooming.
  49409. */
  49410. this.pinchPrecision = 12.0;
  49411. /**
  49412. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  49413. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49414. */
  49415. this.pinchDeltaPercentage = 0;
  49416. /**
  49417. * Defines the pointer panning sensibility or how fast is the camera moving.
  49418. */
  49419. this.panningSensibility = 1000.0;
  49420. /**
  49421. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  49422. */
  49423. this.multiTouchPanning = true;
  49424. /**
  49425. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  49426. */
  49427. this.multiTouchPanAndZoom = true;
  49428. /**
  49429. * Revers pinch action direction.
  49430. */
  49431. this.pinchInwards = true;
  49432. this._isPanClick = false;
  49433. }
  49434. /**
  49435. * Attach the input controls to a specific dom element to get the input from.
  49436. * @param element Defines the element the controls should be listened from
  49437. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49438. */
  49439. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  49440. var _this = this;
  49441. var engine = this.camera.getEngine();
  49442. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  49443. var pointA = null;
  49444. var pointB = null;
  49445. var previousPinchSquaredDistance = 0;
  49446. var initialDistance = 0;
  49447. var twoFingerActivityCount = 0;
  49448. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  49449. this._pointerInput = function (p, s) {
  49450. var evt = p.event;
  49451. var isTouch = p.event.pointerType === "touch";
  49452. if (engine.isInVRExclusivePointerMode) {
  49453. return;
  49454. }
  49455. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49456. return;
  49457. }
  49458. var srcElement = (evt.srcElement || evt.target);
  49459. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49460. try {
  49461. srcElement.setPointerCapture(evt.pointerId);
  49462. }
  49463. catch (e) {
  49464. //Nothing to do with the error. Execution will continue.
  49465. }
  49466. // Manage panning with pan button click
  49467. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  49468. // manage pointers
  49469. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  49470. if (pointA === null) {
  49471. pointA = cacheSoloPointer;
  49472. }
  49473. else if (pointB === null) {
  49474. pointB = cacheSoloPointer;
  49475. }
  49476. if (!noPreventDefault) {
  49477. evt.preventDefault();
  49478. element.focus();
  49479. }
  49480. }
  49481. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  49482. if (_this.camera.useInputToRestoreState) {
  49483. _this.camera.restoreState();
  49484. }
  49485. }
  49486. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49487. try {
  49488. srcElement.releasePointerCapture(evt.pointerId);
  49489. }
  49490. catch (e) {
  49491. //Nothing to do with the error.
  49492. }
  49493. cacheSoloPointer = null;
  49494. previousPinchSquaredDistance = 0;
  49495. previousMultiTouchPanPosition.isPaning = false;
  49496. previousMultiTouchPanPosition.isPinching = false;
  49497. twoFingerActivityCount = 0;
  49498. initialDistance = 0;
  49499. if (!isTouch) {
  49500. pointB = null; // Mouse and pen are mono pointer
  49501. }
  49502. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  49503. //but emptying completly pointers collection is required to fix a bug on iPhone :
  49504. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  49505. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  49506. if (engine._badOS) {
  49507. pointA = pointB = null;
  49508. }
  49509. else {
  49510. //only remove the impacted pointer in case of multitouch allowing on most
  49511. //platforms switching from rotate to zoom and pan seamlessly.
  49512. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  49513. pointA = pointB;
  49514. pointB = null;
  49515. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49516. }
  49517. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  49518. pointB = null;
  49519. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49520. }
  49521. else {
  49522. pointA = pointB = null;
  49523. }
  49524. }
  49525. if (!noPreventDefault) {
  49526. evt.preventDefault();
  49527. }
  49528. }
  49529. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49530. if (!noPreventDefault) {
  49531. evt.preventDefault();
  49532. }
  49533. // One button down
  49534. if (pointA && pointB === null && cacheSoloPointer) {
  49535. if (_this.panningSensibility !== 0 &&
  49536. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  49537. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  49538. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  49539. }
  49540. else {
  49541. var offsetX = evt.clientX - cacheSoloPointer.x;
  49542. var offsetY = evt.clientY - cacheSoloPointer.y;
  49543. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49544. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49545. }
  49546. cacheSoloPointer.x = evt.clientX;
  49547. cacheSoloPointer.y = evt.clientY;
  49548. }
  49549. // Two buttons down: pinch/pan
  49550. else if (pointA && pointB) {
  49551. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  49552. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  49553. ed.x = evt.clientX;
  49554. ed.y = evt.clientY;
  49555. var direction = _this.pinchInwards ? 1 : -1;
  49556. var distX = pointA.x - pointB.x;
  49557. var distY = pointA.y - pointB.y;
  49558. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  49559. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  49560. if (previousPinchSquaredDistance === 0) {
  49561. initialDistance = pinchDistance;
  49562. previousPinchSquaredDistance = pinchSquaredDistance;
  49563. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  49564. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  49565. return;
  49566. }
  49567. if (_this.multiTouchPanAndZoom) {
  49568. if (_this.pinchDeltaPercentage) {
  49569. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49570. }
  49571. else {
  49572. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49573. (_this.pinchPrecision *
  49574. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49575. direction);
  49576. }
  49577. if (_this.panningSensibility !== 0) {
  49578. var pointersCenterX = (pointA.x + pointB.x) / 2;
  49579. var pointersCenterY = (pointA.y + pointB.y) / 2;
  49580. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  49581. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  49582. previousMultiTouchPanPosition.x = pointersCenterX;
  49583. previousMultiTouchPanPosition.y = pointersCenterY;
  49584. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  49585. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  49586. }
  49587. }
  49588. else {
  49589. twoFingerActivityCount++;
  49590. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  49591. if (_this.pinchDeltaPercentage) {
  49592. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49593. }
  49594. else {
  49595. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49596. (_this.pinchPrecision *
  49597. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49598. direction);
  49599. }
  49600. previousMultiTouchPanPosition.isPaning = false;
  49601. previousMultiTouchPanPosition.isPinching = true;
  49602. }
  49603. else {
  49604. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49605. if (!previousMultiTouchPanPosition.isPaning) {
  49606. previousMultiTouchPanPosition.isPaning = true;
  49607. previousMultiTouchPanPosition.isPinching = false;
  49608. previousMultiTouchPanPosition.x = ed.x;
  49609. previousMultiTouchPanPosition.y = ed.y;
  49610. return;
  49611. }
  49612. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49613. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49614. }
  49615. }
  49616. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49617. previousMultiTouchPanPosition.x = ed.x;
  49618. previousMultiTouchPanPosition.y = ed.y;
  49619. }
  49620. }
  49621. previousPinchSquaredDistance = pinchSquaredDistance;
  49622. }
  49623. }
  49624. };
  49625. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49626. this._onContextMenu = function (evt) {
  49627. evt.preventDefault();
  49628. };
  49629. if (!this.camera._useCtrlForPanning) {
  49630. element.addEventListener("contextmenu", this._onContextMenu, false);
  49631. }
  49632. this._onLostFocus = function () {
  49633. //this._keys = [];
  49634. pointA = pointB = null;
  49635. previousPinchSquaredDistance = 0;
  49636. previousMultiTouchPanPosition.isPaning = false;
  49637. previousMultiTouchPanPosition.isPinching = false;
  49638. twoFingerActivityCount = 0;
  49639. cacheSoloPointer = null;
  49640. initialDistance = 0;
  49641. };
  49642. this._onMouseMove = function (evt) {
  49643. if (!engine.isPointerLock) {
  49644. return;
  49645. }
  49646. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49647. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49648. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49649. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49650. if (!noPreventDefault) {
  49651. evt.preventDefault();
  49652. }
  49653. };
  49654. this._onGestureStart = function (e) {
  49655. if (window.MSGesture === undefined) {
  49656. return;
  49657. }
  49658. if (!_this._MSGestureHandler) {
  49659. _this._MSGestureHandler = new MSGesture();
  49660. _this._MSGestureHandler.target = element;
  49661. }
  49662. _this._MSGestureHandler.addPointer(e.pointerId);
  49663. };
  49664. this._onGesture = function (e) {
  49665. _this.camera.radius *= e.scale;
  49666. if (e.preventDefault) {
  49667. if (!noPreventDefault) {
  49668. e.stopPropagation();
  49669. e.preventDefault();
  49670. }
  49671. }
  49672. };
  49673. element.addEventListener("mousemove", this._onMouseMove, false);
  49674. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49675. element.addEventListener("MSGestureChange", this._onGesture, false);
  49676. BABYLON.Tools.RegisterTopRootEvents([
  49677. { name: "blur", handler: this._onLostFocus }
  49678. ]);
  49679. };
  49680. /**
  49681. * Detach the current controls from the specified dom element.
  49682. * @param element Defines the element to stop listening the inputs from
  49683. */
  49684. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49685. if (this._onLostFocus) {
  49686. BABYLON.Tools.UnregisterTopRootEvents([
  49687. { name: "blur", handler: this._onLostFocus }
  49688. ]);
  49689. }
  49690. if (element && this._observer) {
  49691. this.camera.getScene().onPointerObservable.remove(this._observer);
  49692. this._observer = null;
  49693. if (this._onContextMenu) {
  49694. element.removeEventListener("contextmenu", this._onContextMenu);
  49695. }
  49696. if (this._onMouseMove) {
  49697. element.removeEventListener("mousemove", this._onMouseMove);
  49698. }
  49699. if (this._onGestureStart) {
  49700. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49701. }
  49702. if (this._onGesture) {
  49703. element.removeEventListener("MSGestureChange", this._onGesture);
  49704. }
  49705. this._isPanClick = false;
  49706. this.pinchInwards = true;
  49707. this._onMouseMove = null;
  49708. this._onGestureStart = null;
  49709. this._onGesture = null;
  49710. this._MSGestureHandler = null;
  49711. this._onLostFocus = null;
  49712. this._onContextMenu = null;
  49713. }
  49714. };
  49715. /**
  49716. * Gets the class name of the current intput.
  49717. * @returns the class name
  49718. */
  49719. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49720. return "ArcRotateCameraPointersInput";
  49721. };
  49722. /**
  49723. * Get the friendly name associated with the input class.
  49724. * @returns the input friendly name
  49725. */
  49726. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49727. return "pointers";
  49728. };
  49729. __decorate([
  49730. BABYLON.serialize()
  49731. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49732. __decorate([
  49733. BABYLON.serialize()
  49734. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49735. __decorate([
  49736. BABYLON.serialize()
  49737. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49738. __decorate([
  49739. BABYLON.serialize()
  49740. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49741. __decorate([
  49742. BABYLON.serialize()
  49743. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49744. __decorate([
  49745. BABYLON.serialize()
  49746. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49747. __decorate([
  49748. BABYLON.serialize()
  49749. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49750. __decorate([
  49751. BABYLON.serialize()
  49752. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49753. return ArcRotateCameraPointersInput;
  49754. }());
  49755. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49756. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49757. })(BABYLON || (BABYLON = {}));
  49758. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49759. var BABYLON;
  49760. (function (BABYLON) {
  49761. /**
  49762. * Default Inputs manager for the ArcRotateCamera.
  49763. * It groups all the default supported inputs for ease of use.
  49764. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49765. */
  49766. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49767. __extends(ArcRotateCameraInputsManager, _super);
  49768. /**
  49769. * Instantiates a new ArcRotateCameraInputsManager.
  49770. * @param camera Defines the camera the inputs belong to
  49771. */
  49772. function ArcRotateCameraInputsManager(camera) {
  49773. return _super.call(this, camera) || this;
  49774. }
  49775. /**
  49776. * Add mouse wheel input support to the input manager.
  49777. * @returns the current input manager
  49778. */
  49779. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49780. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49781. return this;
  49782. };
  49783. /**
  49784. * Add pointers input support to the input manager.
  49785. * @returns the current input manager
  49786. */
  49787. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49788. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49789. return this;
  49790. };
  49791. /**
  49792. * Add keyboard input support to the input manager.
  49793. * @returns the current input manager
  49794. */
  49795. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49796. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49797. return this;
  49798. };
  49799. /**
  49800. * Add orientation input support to the input manager.
  49801. * @returns the current input manager
  49802. */
  49803. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49804. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49805. return this;
  49806. };
  49807. return ArcRotateCameraInputsManager;
  49808. }(BABYLON.CameraInputsManager));
  49809. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49810. })(BABYLON || (BABYLON = {}));
  49811. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49812. var BABYLON;
  49813. (function (BABYLON) {
  49814. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49815. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49816. });
  49817. /**
  49818. * This represents an orbital type of camera.
  49819. *
  49820. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  49821. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  49822. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49823. */
  49824. var ArcRotateCamera = /** @class */ (function (_super) {
  49825. __extends(ArcRotateCamera, _super);
  49826. /**
  49827. * Instantiates a new ArcRotateCamera in a given scene
  49828. * @param name Defines the name of the camera
  49829. * @param alpha Defines the camera rotation along the logitudinal axis
  49830. * @param beta Defines the camera rotation along the latitudinal axis
  49831. * @param radius Defines the camera distance from its target
  49832. * @param target Defines the camera target
  49833. * @param scene Defines the scene the camera belongs to
  49834. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49835. */
  49836. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49837. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49838. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49839. /**
  49840. * Current inertia value on the longitudinal axis.
  49841. * The bigger this number the longer it will take for the camera to stop.
  49842. */
  49843. _this.inertialAlphaOffset = 0;
  49844. /**
  49845. * Current inertia value on the latitudinal axis.
  49846. * The bigger this number the longer it will take for the camera to stop.
  49847. */
  49848. _this.inertialBetaOffset = 0;
  49849. /**
  49850. * Current inertia value on the radius axis.
  49851. * The bigger this number the longer it will take for the camera to stop.
  49852. */
  49853. _this.inertialRadiusOffset = 0;
  49854. /**
  49855. * Minimum allowed angle on the longitudinal axis.
  49856. * This can help limiting how the Camera is able to move in the scene.
  49857. */
  49858. _this.lowerAlphaLimit = null;
  49859. /**
  49860. * Maximum allowed angle on the longitudinal axis.
  49861. * This can help limiting how the Camera is able to move in the scene.
  49862. */
  49863. _this.upperAlphaLimit = null;
  49864. /**
  49865. * Minimum allowed angle on the latitudinal axis.
  49866. * This can help limiting how the Camera is able to move in the scene.
  49867. */
  49868. _this.lowerBetaLimit = 0.01;
  49869. /**
  49870. * Maximum allowed angle on the latitudinal axis.
  49871. * This can help limiting how the Camera is able to move in the scene.
  49872. */
  49873. _this.upperBetaLimit = Math.PI;
  49874. /**
  49875. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49876. * This can help limiting how the Camera is able to move in the scene.
  49877. */
  49878. _this.lowerRadiusLimit = null;
  49879. /**
  49880. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49881. * This can help limiting how the Camera is able to move in the scene.
  49882. */
  49883. _this.upperRadiusLimit = null;
  49884. /**
  49885. * Defines the current inertia value used during panning of the camera along the X axis.
  49886. */
  49887. _this.inertialPanningX = 0;
  49888. /**
  49889. * Defines the current inertia value used during panning of the camera along the Y axis.
  49890. */
  49891. _this.inertialPanningY = 0;
  49892. /**
  49893. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49894. * Basically if your fingers moves away from more than this distance you will be considered
  49895. * in pinch mode.
  49896. */
  49897. _this.pinchToPanMaxDistance = 20;
  49898. /**
  49899. * Defines the maximum distance the camera can pan.
  49900. * This could help keeping the cammera always in your scene.
  49901. */
  49902. _this.panningDistanceLimit = null;
  49903. /**
  49904. * Defines the target of the camera before paning.
  49905. */
  49906. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49907. /**
  49908. * Defines the value of the inertia used during panning.
  49909. * 0 would mean stop inertia and one would mean no decelleration at all.
  49910. */
  49911. _this.panningInertia = 0.9;
  49912. //-- end properties for backward compatibility for inputs
  49913. /**
  49914. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49915. */
  49916. _this.zoomOnFactor = 1;
  49917. /**
  49918. * Defines a screen offset for the camera position.
  49919. */
  49920. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49921. /**
  49922. * Allows the camera to be completely reversed.
  49923. * If false the camera can not arrive upside down.
  49924. */
  49925. _this.allowUpsideDown = true;
  49926. /**
  49927. * Define if double tap/click is used to restore the previously saved state of the camera.
  49928. */
  49929. _this.useInputToRestoreState = true;
  49930. /** @hidden */
  49931. _this._viewMatrix = new BABYLON.Matrix();
  49932. /**
  49933. * Defines the allowed panning axis.
  49934. */
  49935. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49936. /**
  49937. * Observable triggered when the mesh target has been changed on the camera.
  49938. */
  49939. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49940. /**
  49941. * Defines whether the camera should check collision with the objects oh the scene.
  49942. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49943. */
  49944. _this.checkCollisions = false;
  49945. /**
  49946. * Defines the collision radius of the camera.
  49947. * This simulates a sphere around the camera.
  49948. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49949. */
  49950. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49951. _this._previousPosition = BABYLON.Vector3.Zero();
  49952. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49953. _this._newPosition = BABYLON.Vector3.Zero();
  49954. _this._computationVector = BABYLON.Vector3.Zero();
  49955. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49956. if (collidedMesh === void 0) { collidedMesh = null; }
  49957. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49958. newPosition.multiplyInPlace(_this._collider._radius);
  49959. }
  49960. if (!collidedMesh) {
  49961. _this._previousPosition.copyFrom(_this.position);
  49962. }
  49963. else {
  49964. _this.setPosition(newPosition);
  49965. if (_this.onCollide) {
  49966. _this.onCollide(collidedMesh);
  49967. }
  49968. }
  49969. // Recompute because of constraints
  49970. var cosa = Math.cos(_this.alpha);
  49971. var sina = Math.sin(_this.alpha);
  49972. var cosb = Math.cos(_this.beta);
  49973. var sinb = Math.sin(_this.beta);
  49974. if (sinb === 0) {
  49975. sinb = 0.0001;
  49976. }
  49977. var target = _this._getTargetPosition();
  49978. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49979. target.addToRef(_this._computationVector, _this._newPosition);
  49980. _this.position.copyFrom(_this._newPosition);
  49981. var up = _this.upVector;
  49982. if (_this.allowUpsideDown && _this.beta < 0) {
  49983. up = up.clone();
  49984. up = up.negate();
  49985. }
  49986. _this._computeViewMatrix(_this.position, target, up);
  49987. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49988. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49989. _this._collisionTriggered = false;
  49990. };
  49991. _this._target = BABYLON.Vector3.Zero();
  49992. if (target) {
  49993. _this.setTarget(target);
  49994. }
  49995. _this.alpha = alpha;
  49996. _this.beta = beta;
  49997. _this.radius = radius;
  49998. _this.getViewMatrix();
  49999. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  50000. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  50001. return _this;
  50002. }
  50003. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  50004. /**
  50005. * Defines the target point of the camera.
  50006. * The camera looks towards it form the radius distance.
  50007. */
  50008. get: function () {
  50009. return this._target;
  50010. },
  50011. set: function (value) {
  50012. this.setTarget(value);
  50013. },
  50014. enumerable: true,
  50015. configurable: true
  50016. });
  50017. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  50018. //-- begin properties for backward compatibility for inputs
  50019. /**
  50020. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  50021. */
  50022. get: function () {
  50023. var pointers = this.inputs.attached["pointers"];
  50024. if (pointers) {
  50025. return pointers.angularSensibilityX;
  50026. }
  50027. return 0;
  50028. },
  50029. set: function (value) {
  50030. var pointers = this.inputs.attached["pointers"];
  50031. if (pointers) {
  50032. pointers.angularSensibilityX = value;
  50033. }
  50034. },
  50035. enumerable: true,
  50036. configurable: true
  50037. });
  50038. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  50039. /**
  50040. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50041. */
  50042. get: function () {
  50043. var pointers = this.inputs.attached["pointers"];
  50044. if (pointers) {
  50045. return pointers.angularSensibilityY;
  50046. }
  50047. return 0;
  50048. },
  50049. set: function (value) {
  50050. var pointers = this.inputs.attached["pointers"];
  50051. if (pointers) {
  50052. pointers.angularSensibilityY = value;
  50053. }
  50054. },
  50055. enumerable: true,
  50056. configurable: true
  50057. });
  50058. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  50059. /**
  50060. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  50061. */
  50062. get: function () {
  50063. var pointers = this.inputs.attached["pointers"];
  50064. if (pointers) {
  50065. return pointers.pinchPrecision;
  50066. }
  50067. return 0;
  50068. },
  50069. set: function (value) {
  50070. var pointers = this.inputs.attached["pointers"];
  50071. if (pointers) {
  50072. pointers.pinchPrecision = value;
  50073. }
  50074. },
  50075. enumerable: true,
  50076. configurable: true
  50077. });
  50078. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  50079. /**
  50080. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  50081. * It will be used instead of pinchDeltaPrecision if different from 0.
  50082. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50083. */
  50084. get: function () {
  50085. var pointers = this.inputs.attached["pointers"];
  50086. if (pointers) {
  50087. return pointers.pinchDeltaPercentage;
  50088. }
  50089. return 0;
  50090. },
  50091. set: function (value) {
  50092. var pointers = this.inputs.attached["pointers"];
  50093. if (pointers) {
  50094. pointers.pinchDeltaPercentage = value;
  50095. }
  50096. },
  50097. enumerable: true,
  50098. configurable: true
  50099. });
  50100. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  50101. /**
  50102. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  50103. */
  50104. get: function () {
  50105. var pointers = this.inputs.attached["pointers"];
  50106. if (pointers) {
  50107. return pointers.panningSensibility;
  50108. }
  50109. return 0;
  50110. },
  50111. set: function (value) {
  50112. var pointers = this.inputs.attached["pointers"];
  50113. if (pointers) {
  50114. pointers.panningSensibility = value;
  50115. }
  50116. },
  50117. enumerable: true,
  50118. configurable: true
  50119. });
  50120. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  50121. /**
  50122. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  50123. */
  50124. get: function () {
  50125. var keyboard = this.inputs.attached["keyboard"];
  50126. if (keyboard) {
  50127. return keyboard.keysUp;
  50128. }
  50129. return [];
  50130. },
  50131. set: function (value) {
  50132. var keyboard = this.inputs.attached["keyboard"];
  50133. if (keyboard) {
  50134. keyboard.keysUp = value;
  50135. }
  50136. },
  50137. enumerable: true,
  50138. configurable: true
  50139. });
  50140. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  50141. /**
  50142. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  50143. */
  50144. get: function () {
  50145. var keyboard = this.inputs.attached["keyboard"];
  50146. if (keyboard) {
  50147. return keyboard.keysDown;
  50148. }
  50149. return [];
  50150. },
  50151. set: function (value) {
  50152. var keyboard = this.inputs.attached["keyboard"];
  50153. if (keyboard) {
  50154. keyboard.keysDown = value;
  50155. }
  50156. },
  50157. enumerable: true,
  50158. configurable: true
  50159. });
  50160. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  50161. /**
  50162. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  50163. */
  50164. get: function () {
  50165. var keyboard = this.inputs.attached["keyboard"];
  50166. if (keyboard) {
  50167. return keyboard.keysLeft;
  50168. }
  50169. return [];
  50170. },
  50171. set: function (value) {
  50172. var keyboard = this.inputs.attached["keyboard"];
  50173. if (keyboard) {
  50174. keyboard.keysLeft = value;
  50175. }
  50176. },
  50177. enumerable: true,
  50178. configurable: true
  50179. });
  50180. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  50181. /**
  50182. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  50183. */
  50184. get: function () {
  50185. var keyboard = this.inputs.attached["keyboard"];
  50186. if (keyboard) {
  50187. return keyboard.keysRight;
  50188. }
  50189. return [];
  50190. },
  50191. set: function (value) {
  50192. var keyboard = this.inputs.attached["keyboard"];
  50193. if (keyboard) {
  50194. keyboard.keysRight = value;
  50195. }
  50196. },
  50197. enumerable: true,
  50198. configurable: true
  50199. });
  50200. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  50201. /**
  50202. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50203. */
  50204. get: function () {
  50205. var mousewheel = this.inputs.attached["mousewheel"];
  50206. if (mousewheel) {
  50207. return mousewheel.wheelPrecision;
  50208. }
  50209. return 0;
  50210. },
  50211. set: function (value) {
  50212. var mousewheel = this.inputs.attached["mousewheel"];
  50213. if (mousewheel) {
  50214. mousewheel.wheelPrecision = value;
  50215. }
  50216. },
  50217. enumerable: true,
  50218. configurable: true
  50219. });
  50220. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  50221. /**
  50222. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  50223. * It will be used instead of pinchDeltaPrecision if different from 0.
  50224. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50225. */
  50226. get: function () {
  50227. var mousewheel = this.inputs.attached["mousewheel"];
  50228. if (mousewheel) {
  50229. return mousewheel.wheelDeltaPercentage;
  50230. }
  50231. return 0;
  50232. },
  50233. set: function (value) {
  50234. var mousewheel = this.inputs.attached["mousewheel"];
  50235. if (mousewheel) {
  50236. mousewheel.wheelDeltaPercentage = value;
  50237. }
  50238. },
  50239. enumerable: true,
  50240. configurable: true
  50241. });
  50242. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  50243. /**
  50244. * Gets the bouncing behavior of the camera if it has been enabled.
  50245. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50246. */
  50247. get: function () {
  50248. return this._bouncingBehavior;
  50249. },
  50250. enumerable: true,
  50251. configurable: true
  50252. });
  50253. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  50254. /**
  50255. * Defines if the bouncing behavior of the camera is enabled on the camera.
  50256. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50257. */
  50258. get: function () {
  50259. return this._bouncingBehavior != null;
  50260. },
  50261. set: function (value) {
  50262. if (value === this.useBouncingBehavior) {
  50263. return;
  50264. }
  50265. if (value) {
  50266. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  50267. this.addBehavior(this._bouncingBehavior);
  50268. }
  50269. else if (this._bouncingBehavior) {
  50270. this.removeBehavior(this._bouncingBehavior);
  50271. this._bouncingBehavior = null;
  50272. }
  50273. },
  50274. enumerable: true,
  50275. configurable: true
  50276. });
  50277. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  50278. /**
  50279. * Gets the framing behavior of the camera if it has been enabled.
  50280. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50281. */
  50282. get: function () {
  50283. return this._framingBehavior;
  50284. },
  50285. enumerable: true,
  50286. configurable: true
  50287. });
  50288. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  50289. /**
  50290. * Defines if the framing behavior of the camera is enabled on the camera.
  50291. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50292. */
  50293. get: function () {
  50294. return this._framingBehavior != null;
  50295. },
  50296. set: function (value) {
  50297. if (value === this.useFramingBehavior) {
  50298. return;
  50299. }
  50300. if (value) {
  50301. this._framingBehavior = new BABYLON.FramingBehavior();
  50302. this.addBehavior(this._framingBehavior);
  50303. }
  50304. else if (this._framingBehavior) {
  50305. this.removeBehavior(this._framingBehavior);
  50306. this._framingBehavior = null;
  50307. }
  50308. },
  50309. enumerable: true,
  50310. configurable: true
  50311. });
  50312. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  50313. /**
  50314. * Gets the auto rotation behavior of the camera if it has been enabled.
  50315. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50316. */
  50317. get: function () {
  50318. return this._autoRotationBehavior;
  50319. },
  50320. enumerable: true,
  50321. configurable: true
  50322. });
  50323. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  50324. /**
  50325. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  50326. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50327. */
  50328. get: function () {
  50329. return this._autoRotationBehavior != null;
  50330. },
  50331. set: function (value) {
  50332. if (value === this.useAutoRotationBehavior) {
  50333. return;
  50334. }
  50335. if (value) {
  50336. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  50337. this.addBehavior(this._autoRotationBehavior);
  50338. }
  50339. else if (this._autoRotationBehavior) {
  50340. this.removeBehavior(this._autoRotationBehavior);
  50341. this._autoRotationBehavior = null;
  50342. }
  50343. },
  50344. enumerable: true,
  50345. configurable: true
  50346. });
  50347. // Cache
  50348. /** @hidden */
  50349. ArcRotateCamera.prototype._initCache = function () {
  50350. _super.prototype._initCache.call(this);
  50351. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  50352. this._cache.alpha = undefined;
  50353. this._cache.beta = undefined;
  50354. this._cache.radius = undefined;
  50355. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  50356. };
  50357. /** @hidden */
  50358. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  50359. if (!ignoreParentClass) {
  50360. _super.prototype._updateCache.call(this);
  50361. }
  50362. this._cache._target.copyFrom(this._getTargetPosition());
  50363. this._cache.alpha = this.alpha;
  50364. this._cache.beta = this.beta;
  50365. this._cache.radius = this.radius;
  50366. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  50367. };
  50368. ArcRotateCamera.prototype._getTargetPosition = function () {
  50369. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  50370. var pos = this._targetHost.getAbsolutePosition();
  50371. if (this._targetBoundingCenter) {
  50372. pos.addToRef(this._targetBoundingCenter, this._target);
  50373. }
  50374. else {
  50375. this._target.copyFrom(pos);
  50376. }
  50377. }
  50378. var lockedTargetPosition = this._getLockedTargetPosition();
  50379. if (lockedTargetPosition) {
  50380. return lockedTargetPosition;
  50381. }
  50382. return this._target;
  50383. };
  50384. /**
  50385. * Stores the current state of the camera (alpha, beta, radius and target)
  50386. * @returns the camera itself
  50387. */
  50388. ArcRotateCamera.prototype.storeState = function () {
  50389. this._storedAlpha = this.alpha;
  50390. this._storedBeta = this.beta;
  50391. this._storedRadius = this.radius;
  50392. this._storedTarget = this._getTargetPosition().clone();
  50393. return _super.prototype.storeState.call(this);
  50394. };
  50395. /**
  50396. * @hidden
  50397. * Restored camera state. You must call storeState() first
  50398. */
  50399. ArcRotateCamera.prototype._restoreStateValues = function () {
  50400. if (!_super.prototype._restoreStateValues.call(this)) {
  50401. return false;
  50402. }
  50403. this.alpha = this._storedAlpha;
  50404. this.beta = this._storedBeta;
  50405. this.radius = this._storedRadius;
  50406. this.setTarget(this._storedTarget.clone());
  50407. this.inertialAlphaOffset = 0;
  50408. this.inertialBetaOffset = 0;
  50409. this.inertialRadiusOffset = 0;
  50410. this.inertialPanningX = 0;
  50411. this.inertialPanningY = 0;
  50412. return true;
  50413. };
  50414. // Synchronized
  50415. /** @hidden */
  50416. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  50417. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  50418. return false;
  50419. }
  50420. return this._cache._target.equals(this._getTargetPosition())
  50421. && this._cache.alpha === this.alpha
  50422. && this._cache.beta === this.beta
  50423. && this._cache.radius === this.radius
  50424. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  50425. };
  50426. /**
  50427. * Attached controls to the current camera.
  50428. * @param element Defines the element the controls should be listened from
  50429. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50430. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  50431. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  50432. */
  50433. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  50434. var _this = this;
  50435. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  50436. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  50437. this._useCtrlForPanning = useCtrlForPanning;
  50438. this._panningMouseButton = panningMouseButton;
  50439. this.inputs.attachElement(element, noPreventDefault);
  50440. this._reset = function () {
  50441. _this.inertialAlphaOffset = 0;
  50442. _this.inertialBetaOffset = 0;
  50443. _this.inertialRadiusOffset = 0;
  50444. _this.inertialPanningX = 0;
  50445. _this.inertialPanningY = 0;
  50446. };
  50447. };
  50448. /**
  50449. * Detach the current controls from the camera.
  50450. * The camera will stop reacting to inputs.
  50451. * @param element Defines the element to stop listening the inputs from
  50452. */
  50453. ArcRotateCamera.prototype.detachControl = function (element) {
  50454. this.inputs.detachElement(element);
  50455. if (this._reset) {
  50456. this._reset();
  50457. }
  50458. };
  50459. /** @hidden */
  50460. ArcRotateCamera.prototype._checkInputs = function () {
  50461. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  50462. if (this._collisionTriggered) {
  50463. return;
  50464. }
  50465. this.inputs.checkInputs();
  50466. // Inertia
  50467. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  50468. var inertialAlphaOffset = this.inertialAlphaOffset;
  50469. if (this.beta <= 0) {
  50470. inertialAlphaOffset *= -1;
  50471. }
  50472. if (this.getScene().useRightHandedSystem) {
  50473. inertialAlphaOffset *= -1;
  50474. }
  50475. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  50476. inertialAlphaOffset *= -1;
  50477. }
  50478. this.alpha += inertialAlphaOffset;
  50479. this.beta += this.inertialBetaOffset;
  50480. this.radius -= this.inertialRadiusOffset;
  50481. this.inertialAlphaOffset *= this.inertia;
  50482. this.inertialBetaOffset *= this.inertia;
  50483. this.inertialRadiusOffset *= this.inertia;
  50484. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  50485. this.inertialAlphaOffset = 0;
  50486. }
  50487. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  50488. this.inertialBetaOffset = 0;
  50489. }
  50490. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  50491. this.inertialRadiusOffset = 0;
  50492. }
  50493. }
  50494. // Panning inertia
  50495. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  50496. if (!this._localDirection) {
  50497. this._localDirection = BABYLON.Vector3.Zero();
  50498. this._transformedDirection = BABYLON.Vector3.Zero();
  50499. }
  50500. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  50501. this._localDirection.multiplyInPlace(this.panningAxis);
  50502. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  50503. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  50504. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  50505. if (!this.panningAxis.y) {
  50506. this._transformedDirection.y = 0;
  50507. }
  50508. if (!this._targetHost) {
  50509. if (this.panningDistanceLimit) {
  50510. this._transformedDirection.addInPlace(this._target);
  50511. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  50512. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  50513. this._target.copyFrom(this._transformedDirection);
  50514. }
  50515. }
  50516. else {
  50517. this._target.addInPlace(this._transformedDirection);
  50518. }
  50519. }
  50520. this.inertialPanningX *= this.panningInertia;
  50521. this.inertialPanningY *= this.panningInertia;
  50522. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  50523. this.inertialPanningX = 0;
  50524. }
  50525. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  50526. this.inertialPanningY = 0;
  50527. }
  50528. }
  50529. // Limits
  50530. this._checkLimits();
  50531. _super.prototype._checkInputs.call(this);
  50532. };
  50533. ArcRotateCamera.prototype._checkLimits = function () {
  50534. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  50535. if (this.allowUpsideDown && this.beta > Math.PI) {
  50536. this.beta = this.beta - (2 * Math.PI);
  50537. }
  50538. }
  50539. else {
  50540. if (this.beta < this.lowerBetaLimit) {
  50541. this.beta = this.lowerBetaLimit;
  50542. }
  50543. }
  50544. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  50545. if (this.allowUpsideDown && this.beta < -Math.PI) {
  50546. this.beta = this.beta + (2 * Math.PI);
  50547. }
  50548. }
  50549. else {
  50550. if (this.beta > this.upperBetaLimit) {
  50551. this.beta = this.upperBetaLimit;
  50552. }
  50553. }
  50554. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  50555. this.alpha = this.lowerAlphaLimit;
  50556. }
  50557. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  50558. this.alpha = this.upperAlphaLimit;
  50559. }
  50560. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  50561. this.radius = this.lowerRadiusLimit;
  50562. }
  50563. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  50564. this.radius = this.upperRadiusLimit;
  50565. }
  50566. };
  50567. /**
  50568. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  50569. */
  50570. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  50571. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  50572. this.radius = this._computationVector.length();
  50573. if (this.radius === 0) {
  50574. this.radius = 0.0001; // Just to avoid division by zero
  50575. }
  50576. // Alpha
  50577. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  50578. if (this._computationVector.z < 0) {
  50579. this.alpha = 2 * Math.PI - this.alpha;
  50580. }
  50581. // Beta
  50582. this.beta = Math.acos(this._computationVector.y / this.radius);
  50583. this._checkLimits();
  50584. };
  50585. /**
  50586. * Use a position to define the current camera related information like aplha, beta and radius
  50587. * @param position Defines the position to set the camera at
  50588. */
  50589. ArcRotateCamera.prototype.setPosition = function (position) {
  50590. if (this.position.equals(position)) {
  50591. return;
  50592. }
  50593. this.position.copyFrom(position);
  50594. this.rebuildAnglesAndRadius();
  50595. };
  50596. /**
  50597. * Defines the target the camera should look at.
  50598. * This will automatically adapt alpha beta and radius to fit within the new target.
  50599. * @param target Defines the new target as a Vector or a mesh
  50600. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  50601. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  50602. */
  50603. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  50604. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  50605. if (allowSamePosition === void 0) { allowSamePosition = false; }
  50606. if (target.getBoundingInfo) {
  50607. if (toBoundingCenter) {
  50608. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  50609. }
  50610. else {
  50611. this._targetBoundingCenter = null;
  50612. }
  50613. this._targetHost = target;
  50614. this._target = this._getTargetPosition();
  50615. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  50616. }
  50617. else {
  50618. var newTarget = target;
  50619. var currentTarget = this._getTargetPosition();
  50620. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  50621. return;
  50622. }
  50623. this._targetHost = null;
  50624. this._target = newTarget;
  50625. this._targetBoundingCenter = null;
  50626. this.onMeshTargetChangedObservable.notifyObservers(null);
  50627. }
  50628. this.rebuildAnglesAndRadius();
  50629. };
  50630. /** @hidden */
  50631. ArcRotateCamera.prototype._getViewMatrix = function () {
  50632. // Compute
  50633. var cosa = Math.cos(this.alpha);
  50634. var sina = Math.sin(this.alpha);
  50635. var cosb = Math.cos(this.beta);
  50636. var sinb = Math.sin(this.beta);
  50637. if (sinb === 0) {
  50638. sinb = 0.0001;
  50639. }
  50640. var target = this._getTargetPosition();
  50641. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50642. target.addToRef(this._computationVector, this._newPosition);
  50643. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50644. if (!this._collider) {
  50645. this._collider = new BABYLON.Collider();
  50646. }
  50647. this._collider._radius = this.collisionRadius;
  50648. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50649. this._collisionTriggered = true;
  50650. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50651. }
  50652. else {
  50653. this.position.copyFrom(this._newPosition);
  50654. var up = this.upVector;
  50655. if (this.allowUpsideDown && sinb < 0) {
  50656. up = up.clone();
  50657. up = up.negate();
  50658. }
  50659. this._computeViewMatrix(this.position, target, up);
  50660. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50661. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50662. }
  50663. this._currentTarget = target;
  50664. return this._viewMatrix;
  50665. };
  50666. /**
  50667. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50668. * @param meshes Defines the mesh to zoom on
  50669. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50670. */
  50671. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50672. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50673. meshes = meshes || this.getScene().meshes;
  50674. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50675. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50676. this.radius = distance * this.zoomOnFactor;
  50677. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50678. };
  50679. /**
  50680. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50681. * The target will be changed but the radius
  50682. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50683. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  50684. */
  50685. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50686. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50687. var meshesOrMinMaxVector;
  50688. var distance;
  50689. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50690. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50691. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50692. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50693. }
  50694. else { //minMaxVector and distance
  50695. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50696. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50697. distance = minMaxVectorAndDistance.distance;
  50698. }
  50699. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50700. if (!doNotUpdateMaxZ) {
  50701. this.maxZ = distance * 2;
  50702. }
  50703. };
  50704. /**
  50705. * @override
  50706. * Override Camera.createRigCamera
  50707. */
  50708. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50709. var alphaShift = 0;
  50710. switch (this.cameraRigMode) {
  50711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50714. case BABYLON.Camera.RIG_MODE_VR:
  50715. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50716. break;
  50717. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50718. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50719. break;
  50720. }
  50721. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50722. rigCam._cameraRigParams = {};
  50723. return rigCam;
  50724. };
  50725. /**
  50726. * @hidden
  50727. * @override
  50728. * Override Camera._updateRigCameras
  50729. */
  50730. ArcRotateCamera.prototype._updateRigCameras = function () {
  50731. var camLeft = this._rigCameras[0];
  50732. var camRight = this._rigCameras[1];
  50733. camLeft.beta = camRight.beta = this.beta;
  50734. camLeft.radius = camRight.radius = this.radius;
  50735. switch (this.cameraRigMode) {
  50736. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50737. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50738. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50739. case BABYLON.Camera.RIG_MODE_VR:
  50740. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50741. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50742. break;
  50743. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50744. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50745. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50746. break;
  50747. }
  50748. _super.prototype._updateRigCameras.call(this);
  50749. };
  50750. /**
  50751. * Destroy the camera and release the current resources hold by it.
  50752. */
  50753. ArcRotateCamera.prototype.dispose = function () {
  50754. this.inputs.clear();
  50755. _super.prototype.dispose.call(this);
  50756. };
  50757. /**
  50758. * Gets the current object class name.
  50759. * @return the class name
  50760. */
  50761. ArcRotateCamera.prototype.getClassName = function () {
  50762. return "ArcRotateCamera";
  50763. };
  50764. __decorate([
  50765. BABYLON.serialize()
  50766. ], ArcRotateCamera.prototype, "alpha", void 0);
  50767. __decorate([
  50768. BABYLON.serialize()
  50769. ], ArcRotateCamera.prototype, "beta", void 0);
  50770. __decorate([
  50771. BABYLON.serialize()
  50772. ], ArcRotateCamera.prototype, "radius", void 0);
  50773. __decorate([
  50774. BABYLON.serializeAsVector3("target")
  50775. ], ArcRotateCamera.prototype, "_target", void 0);
  50776. __decorate([
  50777. BABYLON.serialize()
  50778. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50779. __decorate([
  50780. BABYLON.serialize()
  50781. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50782. __decorate([
  50783. BABYLON.serialize()
  50784. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50785. __decorate([
  50786. BABYLON.serialize()
  50787. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50788. __decorate([
  50789. BABYLON.serialize()
  50790. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50791. __decorate([
  50792. BABYLON.serialize()
  50793. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50794. __decorate([
  50795. BABYLON.serialize()
  50796. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50797. __decorate([
  50798. BABYLON.serialize()
  50799. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50800. __decorate([
  50801. BABYLON.serialize()
  50802. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50803. __decorate([
  50804. BABYLON.serialize()
  50805. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50806. __decorate([
  50807. BABYLON.serialize()
  50808. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50809. __decorate([
  50810. BABYLON.serialize()
  50811. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50812. __decorate([
  50813. BABYLON.serialize()
  50814. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50815. __decorate([
  50816. BABYLON.serializeAsVector3()
  50817. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50818. __decorate([
  50819. BABYLON.serialize()
  50820. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50821. __decorate([
  50822. BABYLON.serialize()
  50823. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50824. __decorate([
  50825. BABYLON.serialize()
  50826. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50827. __decorate([
  50828. BABYLON.serialize()
  50829. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50830. __decorate([
  50831. BABYLON.serialize()
  50832. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50833. return ArcRotateCamera;
  50834. }(BABYLON.TargetCamera));
  50835. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50836. })(BABYLON || (BABYLON = {}));
  50837. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50838. var BABYLON;
  50839. (function (BABYLON) {
  50840. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50841. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50842. });
  50843. /**
  50844. * The HemisphericLight simulates the ambient environment light,
  50845. * so the passed direction is the light reflection direction, not the incoming direction.
  50846. */
  50847. var HemisphericLight = /** @class */ (function (_super) {
  50848. __extends(HemisphericLight, _super);
  50849. /**
  50850. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50851. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50852. * The HemisphericLight can't cast shadows.
  50853. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50854. * @param name The friendly name of the light
  50855. * @param direction The direction of the light reflection
  50856. * @param scene The scene the light belongs to
  50857. */
  50858. function HemisphericLight(name, direction, scene) {
  50859. var _this = _super.call(this, name, scene) || this;
  50860. /**
  50861. * The groundColor is the light in the opposite direction to the one specified during creation.
  50862. * 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.
  50863. */
  50864. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50865. _this.direction = direction || BABYLON.Vector3.Up();
  50866. return _this;
  50867. }
  50868. HemisphericLight.prototype._buildUniformLayout = function () {
  50869. this._uniformBuffer.addUniform("vLightData", 4);
  50870. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50871. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50872. this._uniformBuffer.addUniform("vLightGround", 3);
  50873. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50874. this._uniformBuffer.addUniform("depthValues", 2);
  50875. this._uniformBuffer.create();
  50876. };
  50877. /**
  50878. * Returns the string "HemisphericLight".
  50879. * @return The class name
  50880. */
  50881. HemisphericLight.prototype.getClassName = function () {
  50882. return "HemisphericLight";
  50883. };
  50884. /**
  50885. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50886. * Returns the updated direction.
  50887. * @param target The target the direction should point to
  50888. * @return The computed direction
  50889. */
  50890. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50891. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50892. return this.direction;
  50893. };
  50894. /**
  50895. * Returns the shadow generator associated to the light.
  50896. * @returns Always null for hemispheric lights because it does not support shadows.
  50897. */
  50898. HemisphericLight.prototype.getShadowGenerator = function () {
  50899. return null;
  50900. };
  50901. /**
  50902. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50903. * @param effect The effect to update
  50904. * @param lightIndex The index of the light in the effect to update
  50905. * @returns The hemispheric light
  50906. */
  50907. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50908. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50909. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50910. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50911. return this;
  50912. };
  50913. /**
  50914. * Computes the world matrix of the node
  50915. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50916. * @param useWasUpdatedFlag defines a reserved property
  50917. * @returns the world matrix
  50918. */
  50919. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50920. if (!this._worldMatrix) {
  50921. this._worldMatrix = BABYLON.Matrix.Identity();
  50922. }
  50923. return this._worldMatrix;
  50924. };
  50925. /**
  50926. * Returns the integer 3.
  50927. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50928. */
  50929. HemisphericLight.prototype.getTypeID = function () {
  50930. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50931. };
  50932. /**
  50933. * Prepares the list of defines specific to the light type.
  50934. * @param defines the list of defines
  50935. * @param lightIndex defines the index of the light for the effect
  50936. */
  50937. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50938. defines["HEMILIGHT" + lightIndex] = true;
  50939. };
  50940. __decorate([
  50941. BABYLON.serializeAsColor3()
  50942. ], HemisphericLight.prototype, "groundColor", void 0);
  50943. __decorate([
  50944. BABYLON.serializeAsVector3()
  50945. ], HemisphericLight.prototype, "direction", void 0);
  50946. return HemisphericLight;
  50947. }(BABYLON.Light));
  50948. BABYLON.HemisphericLight = HemisphericLight;
  50949. })(BABYLON || (BABYLON = {}));
  50950. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50951. var BABYLON;
  50952. (function (BABYLON) {
  50953. /**
  50954. * Base implementation IShadowLight
  50955. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50956. */
  50957. var ShadowLight = /** @class */ (function (_super) {
  50958. __extends(ShadowLight, _super);
  50959. function ShadowLight() {
  50960. var _this = _super !== null && _super.apply(this, arguments) || this;
  50961. _this._needProjectionMatrixCompute = true;
  50962. return _this;
  50963. }
  50964. ShadowLight.prototype._setPosition = function (value) {
  50965. this._position = value;
  50966. };
  50967. Object.defineProperty(ShadowLight.prototype, "position", {
  50968. /**
  50969. * Sets the position the shadow will be casted from. Also use as the light position for both
  50970. * point and spot lights.
  50971. */
  50972. get: function () {
  50973. return this._position;
  50974. },
  50975. /**
  50976. * Sets the position the shadow will be casted from. Also use as the light position for both
  50977. * point and spot lights.
  50978. */
  50979. set: function (value) {
  50980. this._setPosition(value);
  50981. },
  50982. enumerable: true,
  50983. configurable: true
  50984. });
  50985. ShadowLight.prototype._setDirection = function (value) {
  50986. this._direction = value;
  50987. };
  50988. Object.defineProperty(ShadowLight.prototype, "direction", {
  50989. /**
  50990. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50991. * Also use as the light direction on spot and directional lights.
  50992. */
  50993. get: function () {
  50994. return this._direction;
  50995. },
  50996. /**
  50997. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50998. * Also use as the light direction on spot and directional lights.
  50999. */
  51000. set: function (value) {
  51001. this._setDirection(value);
  51002. },
  51003. enumerable: true,
  51004. configurable: true
  51005. });
  51006. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  51007. /**
  51008. * Gets the shadow projection clipping minimum z value.
  51009. */
  51010. get: function () {
  51011. return this._shadowMinZ;
  51012. },
  51013. /**
  51014. * Sets the shadow projection clipping minimum z value.
  51015. */
  51016. set: function (value) {
  51017. this._shadowMinZ = value;
  51018. this.forceProjectionMatrixCompute();
  51019. },
  51020. enumerable: true,
  51021. configurable: true
  51022. });
  51023. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  51024. /**
  51025. * Sets the shadow projection clipping maximum z value.
  51026. */
  51027. get: function () {
  51028. return this._shadowMaxZ;
  51029. },
  51030. /**
  51031. * Gets the shadow projection clipping maximum z value.
  51032. */
  51033. set: function (value) {
  51034. this._shadowMaxZ = value;
  51035. this.forceProjectionMatrixCompute();
  51036. },
  51037. enumerable: true,
  51038. configurable: true
  51039. });
  51040. /**
  51041. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  51042. * @returns true if the information has been computed, false if it does not need to (no parenting)
  51043. */
  51044. ShadowLight.prototype.computeTransformedInformation = function () {
  51045. if (this.parent && this.parent.getWorldMatrix) {
  51046. if (!this.transformedPosition) {
  51047. this.transformedPosition = BABYLON.Vector3.Zero();
  51048. }
  51049. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  51050. // In case the direction is present.
  51051. if (this.direction) {
  51052. if (!this.transformedDirection) {
  51053. this.transformedDirection = BABYLON.Vector3.Zero();
  51054. }
  51055. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  51056. }
  51057. return true;
  51058. }
  51059. return false;
  51060. };
  51061. /**
  51062. * Return the depth scale used for the shadow map.
  51063. * @returns the depth scale.
  51064. */
  51065. ShadowLight.prototype.getDepthScale = function () {
  51066. return 50.0;
  51067. };
  51068. /**
  51069. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  51070. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51071. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51072. */
  51073. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  51074. return this.transformedDirection ? this.transformedDirection : this.direction;
  51075. };
  51076. /**
  51077. * Returns the ShadowLight absolute position in the World.
  51078. * @returns the position vector in world space
  51079. */
  51080. ShadowLight.prototype.getAbsolutePosition = function () {
  51081. return this.transformedPosition ? this.transformedPosition : this.position;
  51082. };
  51083. /**
  51084. * Sets the ShadowLight direction toward the passed target.
  51085. * @param target The point tot target in local space
  51086. * @returns the updated ShadowLight direction
  51087. */
  51088. ShadowLight.prototype.setDirectionToTarget = function (target) {
  51089. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  51090. return this.direction;
  51091. };
  51092. /**
  51093. * Returns the light rotation in euler definition.
  51094. * @returns the x y z rotation in local space.
  51095. */
  51096. ShadowLight.prototype.getRotation = function () {
  51097. this.direction.normalize();
  51098. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  51099. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  51100. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  51101. };
  51102. /**
  51103. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  51104. * @returns true if a cube texture needs to be use
  51105. */
  51106. ShadowLight.prototype.needCube = function () {
  51107. return false;
  51108. };
  51109. /**
  51110. * Detects if the projection matrix requires to be recomputed this frame.
  51111. * @returns true if it requires to be recomputed otherwise, false.
  51112. */
  51113. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  51114. return this._needProjectionMatrixCompute;
  51115. };
  51116. /**
  51117. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  51118. */
  51119. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  51120. this._needProjectionMatrixCompute = true;
  51121. };
  51122. /** @hidden */
  51123. ShadowLight.prototype._initCache = function () {
  51124. _super.prototype._initCache.call(this);
  51125. this._cache.position = BABYLON.Vector3.Zero();
  51126. };
  51127. /** @hidden */
  51128. ShadowLight.prototype._isSynchronized = function () {
  51129. if (!this._cache.position.equals(this.position)) {
  51130. return false;
  51131. }
  51132. return true;
  51133. };
  51134. /**
  51135. * Computes the world matrix of the node
  51136. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  51137. * @returns the world matrix
  51138. */
  51139. ShadowLight.prototype.computeWorldMatrix = function (force) {
  51140. if (!force && this.isSynchronized()) {
  51141. this._currentRenderId = this.getScene().getRenderId();
  51142. return this._worldMatrix;
  51143. }
  51144. this._updateCache();
  51145. this._cache.position.copyFrom(this.position);
  51146. if (!this._worldMatrix) {
  51147. this._worldMatrix = BABYLON.Matrix.Identity();
  51148. }
  51149. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  51150. if (this.parent && this.parent.getWorldMatrix) {
  51151. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  51152. this._markSyncedWithParent();
  51153. }
  51154. // Cache the determinant
  51155. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  51156. return this._worldMatrix;
  51157. };
  51158. /**
  51159. * Gets the minZ used for shadow according to both the scene and the light.
  51160. * @param activeCamera The camera we are returning the min for
  51161. * @returns the depth min z
  51162. */
  51163. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  51164. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  51165. };
  51166. /**
  51167. * Gets the maxZ used for shadow according to both the scene and the light.
  51168. * @param activeCamera The camera we are returning the max for
  51169. * @returns the depth max z
  51170. */
  51171. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  51172. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  51173. };
  51174. /**
  51175. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  51176. * @param matrix The materix to updated with the projection information
  51177. * @param viewMatrix The transform matrix of the light
  51178. * @param renderList The list of mesh to render in the map
  51179. * @returns The current light
  51180. */
  51181. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51182. if (this.customProjectionMatrixBuilder) {
  51183. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  51184. }
  51185. else {
  51186. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51187. }
  51188. return this;
  51189. };
  51190. __decorate([
  51191. BABYLON.serializeAsVector3()
  51192. ], ShadowLight.prototype, "position", null);
  51193. __decorate([
  51194. BABYLON.serializeAsVector3()
  51195. ], ShadowLight.prototype, "direction", null);
  51196. __decorate([
  51197. BABYLON.serialize()
  51198. ], ShadowLight.prototype, "shadowMinZ", null);
  51199. __decorate([
  51200. BABYLON.serialize()
  51201. ], ShadowLight.prototype, "shadowMaxZ", null);
  51202. return ShadowLight;
  51203. }(BABYLON.Light));
  51204. BABYLON.ShadowLight = ShadowLight;
  51205. })(BABYLON || (BABYLON = {}));
  51206. //# sourceMappingURL=babylon.shadowLight.js.map
  51207. var BABYLON;
  51208. (function (BABYLON) {
  51209. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  51210. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  51211. });
  51212. /**
  51213. * A point light is a light defined by an unique point in world space.
  51214. * The light is emitted in every direction from this point.
  51215. * A good example of a point light is a standard light bulb.
  51216. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51217. */
  51218. var PointLight = /** @class */ (function (_super) {
  51219. __extends(PointLight, _super);
  51220. /**
  51221. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  51222. * A PointLight emits the light in every direction.
  51223. * It can cast shadows.
  51224. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  51225. * ```javascript
  51226. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  51227. * ```
  51228. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51229. * @param name The light friendly name
  51230. * @param position The position of the point light in the scene
  51231. * @param scene The scene the lights belongs to
  51232. */
  51233. function PointLight(name, position, scene) {
  51234. var _this = _super.call(this, name, scene) || this;
  51235. _this._shadowAngle = Math.PI / 2;
  51236. _this.position = position;
  51237. return _this;
  51238. }
  51239. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  51240. /**
  51241. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51242. * This specifies what angle the shadow will use to be created.
  51243. *
  51244. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51245. */
  51246. get: function () {
  51247. return this._shadowAngle;
  51248. },
  51249. /**
  51250. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51251. * This specifies what angle the shadow will use to be created.
  51252. *
  51253. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51254. */
  51255. set: function (value) {
  51256. this._shadowAngle = value;
  51257. this.forceProjectionMatrixCompute();
  51258. },
  51259. enumerable: true,
  51260. configurable: true
  51261. });
  51262. Object.defineProperty(PointLight.prototype, "direction", {
  51263. /**
  51264. * Gets the direction if it has been set.
  51265. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51266. */
  51267. get: function () {
  51268. return this._direction;
  51269. },
  51270. /**
  51271. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51272. */
  51273. set: function (value) {
  51274. var previousNeedCube = this.needCube();
  51275. this._direction = value;
  51276. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  51277. this._shadowGenerator.recreateShadowMap();
  51278. }
  51279. },
  51280. enumerable: true,
  51281. configurable: true
  51282. });
  51283. /**
  51284. * Returns the string "PointLight"
  51285. * @returns the class name
  51286. */
  51287. PointLight.prototype.getClassName = function () {
  51288. return "PointLight";
  51289. };
  51290. /**
  51291. * Returns the integer 0.
  51292. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51293. */
  51294. PointLight.prototype.getTypeID = function () {
  51295. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  51296. };
  51297. /**
  51298. * Specifies wether or not the shadowmap should be a cube texture.
  51299. * @returns true if the shadowmap needs to be a cube texture.
  51300. */
  51301. PointLight.prototype.needCube = function () {
  51302. return !this.direction;
  51303. };
  51304. /**
  51305. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  51306. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51307. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51308. */
  51309. PointLight.prototype.getShadowDirection = function (faceIndex) {
  51310. if (this.direction) {
  51311. return _super.prototype.getShadowDirection.call(this, faceIndex);
  51312. }
  51313. else {
  51314. switch (faceIndex) {
  51315. case 0:
  51316. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  51317. case 1:
  51318. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  51319. case 2:
  51320. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  51321. case 3:
  51322. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  51323. case 4:
  51324. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  51325. case 5:
  51326. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  51327. }
  51328. }
  51329. return BABYLON.Vector3.Zero();
  51330. };
  51331. /**
  51332. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  51333. * - fov = PI / 2
  51334. * - aspect ratio : 1.0
  51335. * - z-near and far equal to the active camera minZ and maxZ.
  51336. * Returns the PointLight.
  51337. */
  51338. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51339. var activeCamera = this.getScene().activeCamera;
  51340. if (!activeCamera) {
  51341. return;
  51342. }
  51343. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51344. };
  51345. PointLight.prototype._buildUniformLayout = function () {
  51346. this._uniformBuffer.addUniform("vLightData", 4);
  51347. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51348. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51349. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51350. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51351. this._uniformBuffer.addUniform("depthValues", 2);
  51352. this._uniformBuffer.create();
  51353. };
  51354. /**
  51355. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  51356. * @param effect The effect to update
  51357. * @param lightIndex The index of the light in the effect to update
  51358. * @returns The point light
  51359. */
  51360. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  51361. if (this.computeTransformedInformation()) {
  51362. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  51363. }
  51364. else {
  51365. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  51366. }
  51367. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  51368. return this;
  51369. };
  51370. /**
  51371. * Prepares the list of defines specific to the light type.
  51372. * @param defines the list of defines
  51373. * @param lightIndex defines the index of the light for the effect
  51374. */
  51375. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51376. defines["POINTLIGHT" + lightIndex] = true;
  51377. };
  51378. __decorate([
  51379. BABYLON.serialize()
  51380. ], PointLight.prototype, "shadowAngle", null);
  51381. return PointLight;
  51382. }(BABYLON.ShadowLight));
  51383. BABYLON.PointLight = PointLight;
  51384. })(BABYLON || (BABYLON = {}));
  51385. //# sourceMappingURL=babylon.pointLight.js.map
  51386. var BABYLON;
  51387. (function (BABYLON) {
  51388. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  51389. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  51390. });
  51391. /**
  51392. * A directional light is defined by a direction (what a surprise!).
  51393. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  51394. * 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.
  51395. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51396. */
  51397. var DirectionalLight = /** @class */ (function (_super) {
  51398. __extends(DirectionalLight, _super);
  51399. /**
  51400. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  51401. * The directional light is emitted from everywhere in the given direction.
  51402. * It can cast shadows.
  51403. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51404. * @param name The friendly name of the light
  51405. * @param direction The direction of the light
  51406. * @param scene The scene the light belongs to
  51407. */
  51408. function DirectionalLight(name, direction, scene) {
  51409. var _this = _super.call(this, name, scene) || this;
  51410. _this._shadowFrustumSize = 0;
  51411. _this._shadowOrthoScale = 0.1;
  51412. /**
  51413. * Automatically compute the projection matrix to best fit (including all the casters)
  51414. * on each frame.
  51415. */
  51416. _this.autoUpdateExtends = true;
  51417. // Cache
  51418. _this._orthoLeft = Number.MAX_VALUE;
  51419. _this._orthoRight = Number.MIN_VALUE;
  51420. _this._orthoTop = Number.MIN_VALUE;
  51421. _this._orthoBottom = Number.MAX_VALUE;
  51422. _this.position = direction.scale(-1.0);
  51423. _this.direction = direction;
  51424. return _this;
  51425. }
  51426. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  51427. /**
  51428. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  51429. */
  51430. get: function () {
  51431. return this._shadowFrustumSize;
  51432. },
  51433. /**
  51434. * Specifies a fix frustum size for the shadow generation.
  51435. */
  51436. set: function (value) {
  51437. this._shadowFrustumSize = value;
  51438. this.forceProjectionMatrixCompute();
  51439. },
  51440. enumerable: true,
  51441. configurable: true
  51442. });
  51443. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  51444. /**
  51445. * Gets the shadow projection scale against the optimal computed one.
  51446. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51447. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51448. */
  51449. get: function () {
  51450. return this._shadowOrthoScale;
  51451. },
  51452. /**
  51453. * Sets the shadow projection scale against the optimal computed one.
  51454. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51455. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51456. */
  51457. set: function (value) {
  51458. this._shadowOrthoScale = value;
  51459. this.forceProjectionMatrixCompute();
  51460. },
  51461. enumerable: true,
  51462. configurable: true
  51463. });
  51464. /**
  51465. * Returns the string "DirectionalLight".
  51466. * @return The class name
  51467. */
  51468. DirectionalLight.prototype.getClassName = function () {
  51469. return "DirectionalLight";
  51470. };
  51471. /**
  51472. * Returns the integer 1.
  51473. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51474. */
  51475. DirectionalLight.prototype.getTypeID = function () {
  51476. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  51477. };
  51478. /**
  51479. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  51480. * Returns the DirectionalLight Shadow projection matrix.
  51481. */
  51482. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51483. if (this.shadowFrustumSize > 0) {
  51484. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  51485. }
  51486. else {
  51487. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51488. }
  51489. };
  51490. /**
  51491. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  51492. * Returns the DirectionalLight Shadow projection matrix.
  51493. */
  51494. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  51495. var activeCamera = this.getScene().activeCamera;
  51496. if (!activeCamera) {
  51497. return;
  51498. }
  51499. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  51500. };
  51501. /**
  51502. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  51503. * Returns the DirectionalLight Shadow projection matrix.
  51504. */
  51505. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51506. var activeCamera = this.getScene().activeCamera;
  51507. if (!activeCamera) {
  51508. return;
  51509. }
  51510. // Check extends
  51511. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  51512. var tempVector3 = BABYLON.Vector3.Zero();
  51513. this._orthoLeft = Number.MAX_VALUE;
  51514. this._orthoRight = Number.MIN_VALUE;
  51515. this._orthoTop = Number.MIN_VALUE;
  51516. this._orthoBottom = Number.MAX_VALUE;
  51517. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  51518. var mesh = renderList[meshIndex];
  51519. if (!mesh) {
  51520. continue;
  51521. }
  51522. var boundingInfo = mesh.getBoundingInfo();
  51523. var boundingBox = boundingInfo.boundingBox;
  51524. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  51525. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  51526. if (tempVector3.x < this._orthoLeft) {
  51527. this._orthoLeft = tempVector3.x;
  51528. }
  51529. if (tempVector3.y < this._orthoBottom) {
  51530. this._orthoBottom = tempVector3.y;
  51531. }
  51532. if (tempVector3.x > this._orthoRight) {
  51533. this._orthoRight = tempVector3.x;
  51534. }
  51535. if (tempVector3.y > this._orthoTop) {
  51536. this._orthoTop = tempVector3.y;
  51537. }
  51538. }
  51539. }
  51540. }
  51541. var xOffset = this._orthoRight - this._orthoLeft;
  51542. var yOffset = this._orthoTop - this._orthoBottom;
  51543. 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);
  51544. };
  51545. DirectionalLight.prototype._buildUniformLayout = function () {
  51546. this._uniformBuffer.addUniform("vLightData", 4);
  51547. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51548. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51549. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51550. this._uniformBuffer.addUniform("depthValues", 2);
  51551. this._uniformBuffer.create();
  51552. };
  51553. /**
  51554. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  51555. * @param effect The effect to update
  51556. * @param lightIndex The index of the light in the effect to update
  51557. * @returns The directional light
  51558. */
  51559. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  51560. if (this.computeTransformedInformation()) {
  51561. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  51562. return this;
  51563. }
  51564. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  51565. return this;
  51566. };
  51567. /**
  51568. * Gets the minZ used for shadow according to both the scene and the light.
  51569. *
  51570. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51571. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51572. * @param activeCamera The camera we are returning the min for
  51573. * @returns the depth min z
  51574. */
  51575. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  51576. return 1;
  51577. };
  51578. /**
  51579. * Gets the maxZ used for shadow according to both the scene and the light.
  51580. *
  51581. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51582. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51583. * @param activeCamera The camera we are returning the max for
  51584. * @returns the depth max z
  51585. */
  51586. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  51587. return 1;
  51588. };
  51589. /**
  51590. * Prepares the list of defines specific to the light type.
  51591. * @param defines the list of defines
  51592. * @param lightIndex defines the index of the light for the effect
  51593. */
  51594. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51595. defines["DIRLIGHT" + lightIndex] = true;
  51596. };
  51597. __decorate([
  51598. BABYLON.serialize()
  51599. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  51600. __decorate([
  51601. BABYLON.serialize()
  51602. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  51603. __decorate([
  51604. BABYLON.serialize()
  51605. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  51606. return DirectionalLight;
  51607. }(BABYLON.ShadowLight));
  51608. BABYLON.DirectionalLight = DirectionalLight;
  51609. })(BABYLON || (BABYLON = {}));
  51610. //# sourceMappingURL=babylon.directionalLight.js.map
  51611. var BABYLON;
  51612. (function (BABYLON) {
  51613. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  51614. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  51615. });
  51616. /**
  51617. * A spot light is defined by a position, a direction, an angle, and an exponent.
  51618. * These values define a cone of light starting from the position, emitting toward the direction.
  51619. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  51620. * and the exponent defines the speed of the decay of the light with distance (reach).
  51621. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51622. */
  51623. var SpotLight = /** @class */ (function (_super) {
  51624. __extends(SpotLight, _super);
  51625. /**
  51626. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  51627. * It can cast shadows.
  51628. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51629. * @param name The light friendly name
  51630. * @param position The position of the spot light in the scene
  51631. * @param direction The direction of the light in the scene
  51632. * @param angle The cone angle of the light in Radians
  51633. * @param exponent The light decay speed with the distance from the emission spot
  51634. * @param scene The scene the lights belongs to
  51635. */
  51636. function SpotLight(name, position, direction, angle, exponent, scene) {
  51637. var _this = _super.call(this, name, scene) || this;
  51638. _this._innerAngle = 0;
  51639. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51640. _this._projectionTextureLightNear = 1e-6;
  51641. _this._projectionTextureLightFar = 1000.0;
  51642. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51643. _this._projectionTextureViewLightDirty = true;
  51644. _this._projectionTextureProjectionLightDirty = true;
  51645. _this._projectionTextureDirty = true;
  51646. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51647. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51648. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51649. _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);
  51650. _this.position = position;
  51651. _this.direction = direction;
  51652. _this.angle = angle;
  51653. _this.exponent = exponent;
  51654. return _this;
  51655. }
  51656. Object.defineProperty(SpotLight.prototype, "angle", {
  51657. /**
  51658. * Gets the cone angle of the spot light in Radians.
  51659. */
  51660. get: function () {
  51661. return this._angle;
  51662. },
  51663. /**
  51664. * Sets the cone angle of the spot light in Radians.
  51665. */
  51666. set: function (value) {
  51667. this._angle = value;
  51668. this._cosHalfAngle = Math.cos(value * 0.5);
  51669. this._projectionTextureProjectionLightDirty = true;
  51670. this.forceProjectionMatrixCompute();
  51671. this._computeAngleValues();
  51672. },
  51673. enumerable: true,
  51674. configurable: true
  51675. });
  51676. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51677. /**
  51678. * Only used in gltf falloff mode, this defines the angle where
  51679. * the directional falloff will start before cutting at angle which could be seen
  51680. * as outer angle.
  51681. */
  51682. get: function () {
  51683. return this._innerAngle;
  51684. },
  51685. /**
  51686. * Only used in gltf falloff mode, this defines the angle where
  51687. * the directional falloff will start before cutting at angle which could be seen
  51688. * as outer angle.
  51689. */
  51690. set: function (value) {
  51691. this._innerAngle = value;
  51692. this._computeAngleValues();
  51693. },
  51694. enumerable: true,
  51695. configurable: true
  51696. });
  51697. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51698. /**
  51699. * Allows scaling the angle of the light for shadow generation only.
  51700. */
  51701. get: function () {
  51702. return this._shadowAngleScale;
  51703. },
  51704. /**
  51705. * Allows scaling the angle of the light for shadow generation only.
  51706. */
  51707. set: function (value) {
  51708. this._shadowAngleScale = value;
  51709. this.forceProjectionMatrixCompute();
  51710. },
  51711. enumerable: true,
  51712. configurable: true
  51713. });
  51714. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51715. /**
  51716. * Allows reading the projecton texture
  51717. */
  51718. get: function () {
  51719. return this._projectionTextureMatrix;
  51720. },
  51721. enumerable: true,
  51722. configurable: true
  51723. });
  51724. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51725. /**
  51726. * Gets the near clip of the Spotlight for texture projection.
  51727. */
  51728. get: function () {
  51729. return this._projectionTextureLightNear;
  51730. },
  51731. /**
  51732. * Sets the near clip of the Spotlight for texture projection.
  51733. */
  51734. set: function (value) {
  51735. this._projectionTextureLightNear = value;
  51736. this._projectionTextureProjectionLightDirty = true;
  51737. },
  51738. enumerable: true,
  51739. configurable: true
  51740. });
  51741. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51742. /**
  51743. * Gets the far clip of the Spotlight for texture projection.
  51744. */
  51745. get: function () {
  51746. return this._projectionTextureLightFar;
  51747. },
  51748. /**
  51749. * Sets the far clip of the Spotlight for texture projection.
  51750. */
  51751. set: function (value) {
  51752. this._projectionTextureLightFar = value;
  51753. this._projectionTextureProjectionLightDirty = true;
  51754. },
  51755. enumerable: true,
  51756. configurable: true
  51757. });
  51758. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51759. /**
  51760. * Gets the Up vector of the Spotlight for texture projection.
  51761. */
  51762. get: function () {
  51763. return this._projectionTextureUpDirection;
  51764. },
  51765. /**
  51766. * Sets the Up vector of the Spotlight for texture projection.
  51767. */
  51768. set: function (value) {
  51769. this._projectionTextureUpDirection = value;
  51770. this._projectionTextureProjectionLightDirty = true;
  51771. },
  51772. enumerable: true,
  51773. configurable: true
  51774. });
  51775. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51776. /**
  51777. * Gets the projection texture of the light.
  51778. */
  51779. get: function () {
  51780. return this._projectionTexture;
  51781. },
  51782. /**
  51783. * Sets the projection texture of the light.
  51784. */
  51785. set: function (value) {
  51786. this._projectionTexture = value;
  51787. this._projectionTextureDirty = true;
  51788. },
  51789. enumerable: true,
  51790. configurable: true
  51791. });
  51792. /**
  51793. * Returns the string "SpotLight".
  51794. * @returns the class name
  51795. */
  51796. SpotLight.prototype.getClassName = function () {
  51797. return "SpotLight";
  51798. };
  51799. /**
  51800. * Returns the integer 2.
  51801. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51802. */
  51803. SpotLight.prototype.getTypeID = function () {
  51804. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51805. };
  51806. /**
  51807. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51808. */
  51809. SpotLight.prototype._setDirection = function (value) {
  51810. _super.prototype._setDirection.call(this, value);
  51811. this._projectionTextureViewLightDirty = true;
  51812. };
  51813. /**
  51814. * Overrides the position setter to recompute the projection texture view light Matrix.
  51815. */
  51816. SpotLight.prototype._setPosition = function (value) {
  51817. _super.prototype._setPosition.call(this, value);
  51818. this._projectionTextureViewLightDirty = true;
  51819. };
  51820. /**
  51821. * 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.
  51822. * Returns the SpotLight.
  51823. */
  51824. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51825. var activeCamera = this.getScene().activeCamera;
  51826. if (!activeCamera) {
  51827. return;
  51828. }
  51829. this._shadowAngleScale = this._shadowAngleScale || 1;
  51830. var angle = this._shadowAngleScale * this._angle;
  51831. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51832. };
  51833. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51834. this._projectionTextureViewLightDirty = false;
  51835. this._projectionTextureDirty = true;
  51836. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51837. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51838. };
  51839. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51840. this._projectionTextureProjectionLightDirty = false;
  51841. this._projectionTextureDirty = true;
  51842. var light_far = this.projectionTextureLightFar;
  51843. var light_near = this.projectionTextureLightNear;
  51844. var P = light_far / (light_far - light_near);
  51845. var Q = -P * light_near;
  51846. var S = 1.0 / Math.tan(this._angle / 2.0);
  51847. var A = 1.0;
  51848. 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);
  51849. };
  51850. /**
  51851. * Main function for light texture projection matrix computing.
  51852. */
  51853. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51854. this._projectionTextureDirty = false;
  51855. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51856. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51857. };
  51858. SpotLight.prototype._buildUniformLayout = function () {
  51859. this._uniformBuffer.addUniform("vLightData", 4);
  51860. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51861. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51862. this._uniformBuffer.addUniform("vLightDirection", 3);
  51863. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51864. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51865. this._uniformBuffer.addUniform("depthValues", 2);
  51866. this._uniformBuffer.create();
  51867. };
  51868. SpotLight.prototype._computeAngleValues = function () {
  51869. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51870. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51871. };
  51872. /**
  51873. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51874. * @param effect The effect to update
  51875. * @param lightIndex The index of the light in the effect to update
  51876. * @returns The spot light
  51877. */
  51878. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51879. var normalizeDirection;
  51880. if (this.computeTransformedInformation()) {
  51881. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51882. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51883. }
  51884. else {
  51885. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51886. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51887. }
  51888. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51889. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51890. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51891. if (this._projectionTextureViewLightDirty) {
  51892. this._computeProjectionTextureViewLightMatrix();
  51893. }
  51894. if (this._projectionTextureProjectionLightDirty) {
  51895. this._computeProjectionTextureProjectionLightMatrix();
  51896. }
  51897. if (this._projectionTextureDirty) {
  51898. this._computeProjectionTextureMatrix();
  51899. }
  51900. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51901. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51902. }
  51903. return this;
  51904. };
  51905. /**
  51906. * Disposes the light and the associated resources.
  51907. */
  51908. SpotLight.prototype.dispose = function () {
  51909. _super.prototype.dispose.call(this);
  51910. if (this._projectionTexture) {
  51911. this._projectionTexture.dispose();
  51912. }
  51913. };
  51914. /**
  51915. * Prepares the list of defines specific to the light type.
  51916. * @param defines the list of defines
  51917. * @param lightIndex defines the index of the light for the effect
  51918. */
  51919. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51920. defines["SPOTLIGHT" + lightIndex] = true;
  51921. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51922. };
  51923. __decorate([
  51924. BABYLON.serialize()
  51925. ], SpotLight.prototype, "angle", null);
  51926. __decorate([
  51927. BABYLON.serialize()
  51928. ], SpotLight.prototype, "innerAngle", null);
  51929. __decorate([
  51930. BABYLON.serialize()
  51931. ], SpotLight.prototype, "shadowAngleScale", null);
  51932. __decorate([
  51933. BABYLON.serialize()
  51934. ], SpotLight.prototype, "exponent", void 0);
  51935. __decorate([
  51936. BABYLON.serialize()
  51937. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51938. __decorate([
  51939. BABYLON.serialize()
  51940. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51941. __decorate([
  51942. BABYLON.serialize()
  51943. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51944. __decorate([
  51945. BABYLON.serializeAsTexture("projectedLightTexture")
  51946. ], SpotLight.prototype, "_projectionTexture", void 0);
  51947. return SpotLight;
  51948. }(BABYLON.ShadowLight));
  51949. BABYLON.SpotLight = SpotLight;
  51950. })(BABYLON || (BABYLON = {}));
  51951. //# sourceMappingURL=babylon.spotLight.js.map
  51952. var BABYLON;
  51953. (function (BABYLON) {
  51954. /**
  51955. * Class used to override all child animations of a given target
  51956. */
  51957. var AnimationPropertiesOverride = /** @class */ (function () {
  51958. function AnimationPropertiesOverride() {
  51959. /**
  51960. * Gets or sets a value indicating if animation blending must be used
  51961. */
  51962. this.enableBlending = false;
  51963. /**
  51964. * Gets or sets the blending speed to use when enableBlending is true
  51965. */
  51966. this.blendingSpeed = 0.01;
  51967. /**
  51968. * Gets or sets the default loop mode to use
  51969. */
  51970. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51971. }
  51972. return AnimationPropertiesOverride;
  51973. }());
  51974. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51975. })(BABYLON || (BABYLON = {}));
  51976. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51977. var BABYLON;
  51978. (function (BABYLON) {
  51979. /**
  51980. * Represents the range of an animation
  51981. */
  51982. var AnimationRange = /** @class */ (function () {
  51983. /**
  51984. * Initializes the range of an animation
  51985. * @param name The name of the animation range
  51986. * @param from The starting frame of the animation
  51987. * @param to The ending frame of the animation
  51988. */
  51989. function AnimationRange(
  51990. /**The name of the animation range**/
  51991. name,
  51992. /**The starting frame of the animation */
  51993. from,
  51994. /**The ending frame of the animation*/
  51995. to) {
  51996. this.name = name;
  51997. this.from = from;
  51998. this.to = to;
  51999. }
  52000. /**
  52001. * Makes a copy of the animation range
  52002. * @returns A copy of the animation range
  52003. */
  52004. AnimationRange.prototype.clone = function () {
  52005. return new AnimationRange(this.name, this.from, this.to);
  52006. };
  52007. return AnimationRange;
  52008. }());
  52009. BABYLON.AnimationRange = AnimationRange;
  52010. /**
  52011. * Composed of a frame, and an action function
  52012. */
  52013. var AnimationEvent = /** @class */ (function () {
  52014. /**
  52015. * Initializes the animation event
  52016. * @param frame The frame for which the event is triggered
  52017. * @param action The event to perform when triggered
  52018. * @param onlyOnce Specifies if the event should be triggered only once
  52019. */
  52020. function AnimationEvent(
  52021. /** The frame for which the event is triggered **/
  52022. frame,
  52023. /** The event to perform when triggered **/
  52024. action,
  52025. /** Specifies if the event should be triggered only once**/
  52026. onlyOnce) {
  52027. this.frame = frame;
  52028. this.action = action;
  52029. this.onlyOnce = onlyOnce;
  52030. /**
  52031. * Specifies if the animation event is done
  52032. */
  52033. this.isDone = false;
  52034. }
  52035. /** @hidden */
  52036. AnimationEvent.prototype._clone = function () {
  52037. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  52038. };
  52039. return AnimationEvent;
  52040. }());
  52041. BABYLON.AnimationEvent = AnimationEvent;
  52042. /**
  52043. * A cursor which tracks a point on a path
  52044. */
  52045. var PathCursor = /** @class */ (function () {
  52046. /**
  52047. * Initializes the path cursor
  52048. * @param path The path to track
  52049. */
  52050. function PathCursor(path) {
  52051. this.path = path;
  52052. /**
  52053. * Stores path cursor callbacks for when an onchange event is triggered
  52054. */
  52055. this._onchange = new Array();
  52056. /**
  52057. * The value of the path cursor
  52058. */
  52059. this.value = 0;
  52060. /**
  52061. * The animation array of the path cursor
  52062. */
  52063. this.animations = new Array();
  52064. }
  52065. /**
  52066. * Gets the cursor point on the path
  52067. * @returns A point on the path cursor at the cursor location
  52068. */
  52069. PathCursor.prototype.getPoint = function () {
  52070. var point = this.path.getPointAtLengthPosition(this.value);
  52071. return new BABYLON.Vector3(point.x, 0, point.y);
  52072. };
  52073. /**
  52074. * Moves the cursor ahead by the step amount
  52075. * @param step The amount to move the cursor forward
  52076. * @returns This path cursor
  52077. */
  52078. PathCursor.prototype.moveAhead = function (step) {
  52079. if (step === void 0) { step = 0.002; }
  52080. this.move(step);
  52081. return this;
  52082. };
  52083. /**
  52084. * Moves the cursor behind by the step amount
  52085. * @param step The amount to move the cursor back
  52086. * @returns This path cursor
  52087. */
  52088. PathCursor.prototype.moveBack = function (step) {
  52089. if (step === void 0) { step = 0.002; }
  52090. this.move(-step);
  52091. return this;
  52092. };
  52093. /**
  52094. * Moves the cursor by the step amount
  52095. * If the step amount is greater than one, an exception is thrown
  52096. * @param step The amount to move the cursor
  52097. * @returns This path cursor
  52098. */
  52099. PathCursor.prototype.move = function (step) {
  52100. if (Math.abs(step) > 1) {
  52101. throw "step size should be less than 1.";
  52102. }
  52103. this.value += step;
  52104. this.ensureLimits();
  52105. this.raiseOnChange();
  52106. return this;
  52107. };
  52108. /**
  52109. * Ensures that the value is limited between zero and one
  52110. * @returns This path cursor
  52111. */
  52112. PathCursor.prototype.ensureLimits = function () {
  52113. while (this.value > 1) {
  52114. this.value -= 1;
  52115. }
  52116. while (this.value < 0) {
  52117. this.value += 1;
  52118. }
  52119. return this;
  52120. };
  52121. /**
  52122. * Runs onchange callbacks on change (used by the animation engine)
  52123. * @returns This path cursor
  52124. */
  52125. PathCursor.prototype.raiseOnChange = function () {
  52126. var _this = this;
  52127. this._onchange.forEach(function (f) { return f(_this); });
  52128. return this;
  52129. };
  52130. /**
  52131. * Executes a function on change
  52132. * @param f A path cursor onchange callback
  52133. * @returns This path cursor
  52134. */
  52135. PathCursor.prototype.onchange = function (f) {
  52136. this._onchange.push(f);
  52137. return this;
  52138. };
  52139. return PathCursor;
  52140. }());
  52141. BABYLON.PathCursor = PathCursor;
  52142. /**
  52143. * Enum for the animation key frame interpolation type
  52144. */
  52145. var AnimationKeyInterpolation;
  52146. (function (AnimationKeyInterpolation) {
  52147. /**
  52148. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  52149. */
  52150. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  52151. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  52152. /**
  52153. * Class used to store any kind of animation
  52154. */
  52155. var Animation = /** @class */ (function () {
  52156. /**
  52157. * Initializes the animation
  52158. * @param name Name of the animation
  52159. * @param targetProperty Property to animate
  52160. * @param framePerSecond The frames per second of the animation
  52161. * @param dataType The data type of the animation
  52162. * @param loopMode The loop mode of the animation
  52163. * @param enableBlendings Specifies if blending should be enabled
  52164. */
  52165. function Animation(
  52166. /**Name of the animation */
  52167. name,
  52168. /**Property to animate */
  52169. targetProperty,
  52170. /**The frames per second of the animation */
  52171. framePerSecond,
  52172. /**The data type of the animation */
  52173. dataType,
  52174. /**The loop mode of the animation */
  52175. loopMode,
  52176. /**Specifies if blending should be enabled */
  52177. enableBlending) {
  52178. this.name = name;
  52179. this.targetProperty = targetProperty;
  52180. this.framePerSecond = framePerSecond;
  52181. this.dataType = dataType;
  52182. this.loopMode = loopMode;
  52183. this.enableBlending = enableBlending;
  52184. /**
  52185. * @hidden Internal use only
  52186. */
  52187. this._runtimeAnimations = new Array();
  52188. /**
  52189. * The set of event that will be linked to this animation
  52190. */
  52191. this._events = new Array();
  52192. /**
  52193. * Stores the blending speed of the animation
  52194. */
  52195. this.blendingSpeed = 0.01;
  52196. /**
  52197. * Stores the animation ranges for the animation
  52198. */
  52199. this._ranges = {};
  52200. this.targetPropertyPath = targetProperty.split(".");
  52201. this.dataType = dataType;
  52202. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  52203. }
  52204. /**
  52205. * @hidden Internal use
  52206. */
  52207. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  52208. var dataType = undefined;
  52209. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  52210. dataType = Animation.ANIMATIONTYPE_FLOAT;
  52211. }
  52212. else if (from instanceof BABYLON.Quaternion) {
  52213. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  52214. }
  52215. else if (from instanceof BABYLON.Vector3) {
  52216. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  52217. }
  52218. else if (from instanceof BABYLON.Vector2) {
  52219. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  52220. }
  52221. else if (from instanceof BABYLON.Color3) {
  52222. dataType = Animation.ANIMATIONTYPE_COLOR3;
  52223. }
  52224. else if (from instanceof BABYLON.Size) {
  52225. dataType = Animation.ANIMATIONTYPE_SIZE;
  52226. }
  52227. if (dataType == undefined) {
  52228. return null;
  52229. }
  52230. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  52231. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  52232. animation.setKeys(keys);
  52233. if (easingFunction !== undefined) {
  52234. animation.setEasingFunction(easingFunction);
  52235. }
  52236. return animation;
  52237. };
  52238. /**
  52239. * Sets up an animation
  52240. * @param property The property to animate
  52241. * @param animationType The animation type to apply
  52242. * @param framePerSecond The frames per second of the animation
  52243. * @param easingFunction The easing function used in the animation
  52244. * @returns The created animation
  52245. */
  52246. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  52247. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  52248. animation.setEasingFunction(easingFunction);
  52249. return animation;
  52250. };
  52251. /**
  52252. * Create and start an animation on a node
  52253. * @param name defines the name of the global animation that will be run on all nodes
  52254. * @param node defines the root node where the animation will take place
  52255. * @param targetProperty defines property to animate
  52256. * @param framePerSecond defines the number of frame per second yo use
  52257. * @param totalFrame defines the number of frames in total
  52258. * @param from defines the initial value
  52259. * @param to defines the final value
  52260. * @param loopMode defines which loop mode you want to use (off by default)
  52261. * @param easingFunction defines the easing function to use (linear by default)
  52262. * @param onAnimationEnd defines the callback to call when animation end
  52263. * @returns the animatable created for this animation
  52264. */
  52265. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52266. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52267. if (!animation) {
  52268. return null;
  52269. }
  52270. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52271. };
  52272. /**
  52273. * Create and start an animation on a node and its descendants
  52274. * @param name defines the name of the global animation that will be run on all nodes
  52275. * @param node defines the root node where the animation will take place
  52276. * @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
  52277. * @param targetProperty defines property to animate
  52278. * @param framePerSecond defines the number of frame per second to use
  52279. * @param totalFrame defines the number of frames in total
  52280. * @param from defines the initial value
  52281. * @param to defines the final value
  52282. * @param loopMode defines which loop mode you want to use (off by default)
  52283. * @param easingFunction defines the easing function to use (linear by default)
  52284. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  52285. * @returns the list of animatables created for all nodes
  52286. * @example https://www.babylonjs-playground.com/#MH0VLI
  52287. */
  52288. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52289. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52290. if (!animation) {
  52291. return null;
  52292. }
  52293. var scene = node.getScene();
  52294. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52295. };
  52296. /**
  52297. * Creates a new animation, merges it with the existing animations and starts it
  52298. * @param name Name of the animation
  52299. * @param node Node which contains the scene that begins the animations
  52300. * @param targetProperty Specifies which property to animate
  52301. * @param framePerSecond The frames per second of the animation
  52302. * @param totalFrame The total number of frames
  52303. * @param from The frame at the beginning of the animation
  52304. * @param to The frame at the end of the animation
  52305. * @param loopMode Specifies the loop mode of the animation
  52306. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  52307. * @param onAnimationEnd Callback to run once the animation is complete
  52308. * @returns Nullable animation
  52309. */
  52310. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52311. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52312. if (!animation) {
  52313. return null;
  52314. }
  52315. node.animations.push(animation);
  52316. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52317. };
  52318. /**
  52319. * Transition property of an host to the target Value
  52320. * @param property The property to transition
  52321. * @param targetValue The target Value of the property
  52322. * @param host The object where the property to animate belongs
  52323. * @param scene Scene used to run the animation
  52324. * @param frameRate Framerate (in frame/s) to use
  52325. * @param transition The transition type we want to use
  52326. * @param duration The duration of the animation, in milliseconds
  52327. * @param onAnimationEnd Callback trigger at the end of the animation
  52328. * @returns Nullable animation
  52329. */
  52330. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  52331. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  52332. if (duration <= 0) {
  52333. host[property] = targetValue;
  52334. if (onAnimationEnd) {
  52335. onAnimationEnd();
  52336. }
  52337. return null;
  52338. }
  52339. var endFrame = frameRate * (duration / 1000);
  52340. transition.setKeys([{
  52341. frame: 0,
  52342. value: host[property].clone ? host[property].clone() : host[property]
  52343. },
  52344. {
  52345. frame: endFrame,
  52346. value: targetValue
  52347. }]);
  52348. if (!host.animations) {
  52349. host.animations = [];
  52350. }
  52351. host.animations.push(transition);
  52352. var animation = scene.beginAnimation(host, 0, endFrame, false);
  52353. animation.onAnimationEnd = onAnimationEnd;
  52354. return animation;
  52355. };
  52356. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  52357. /**
  52358. * Return the array of runtime animations currently using this animation
  52359. */
  52360. get: function () {
  52361. return this._runtimeAnimations;
  52362. },
  52363. enumerable: true,
  52364. configurable: true
  52365. });
  52366. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  52367. /**
  52368. * Specifies if any of the runtime animations are currently running
  52369. */
  52370. get: function () {
  52371. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  52372. var runtimeAnimation = _a[_i];
  52373. if (!runtimeAnimation.isStopped) {
  52374. return true;
  52375. }
  52376. }
  52377. return false;
  52378. },
  52379. enumerable: true,
  52380. configurable: true
  52381. });
  52382. // Methods
  52383. /**
  52384. * Converts the animation to a string
  52385. * @param fullDetails support for multiple levels of logging within scene loading
  52386. * @returns String form of the animation
  52387. */
  52388. Animation.prototype.toString = function (fullDetails) {
  52389. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  52390. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  52391. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  52392. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52393. if (fullDetails) {
  52394. ret += ", Ranges: {";
  52395. var first = true;
  52396. for (var name in this._ranges) {
  52397. if (first) {
  52398. ret += ", ";
  52399. first = false;
  52400. }
  52401. ret += name;
  52402. }
  52403. ret += "}";
  52404. }
  52405. return ret;
  52406. };
  52407. /**
  52408. * Add an event to this animation
  52409. * @param event Event to add
  52410. */
  52411. Animation.prototype.addEvent = function (event) {
  52412. this._events.push(event);
  52413. };
  52414. /**
  52415. * Remove all events found at the given frame
  52416. * @param frame The frame to remove events from
  52417. */
  52418. Animation.prototype.removeEvents = function (frame) {
  52419. for (var index = 0; index < this._events.length; index++) {
  52420. if (this._events[index].frame === frame) {
  52421. this._events.splice(index, 1);
  52422. index--;
  52423. }
  52424. }
  52425. };
  52426. /**
  52427. * Retrieves all the events from the animation
  52428. * @returns Events from the animation
  52429. */
  52430. Animation.prototype.getEvents = function () {
  52431. return this._events;
  52432. };
  52433. /**
  52434. * Creates an animation range
  52435. * @param name Name of the animation range
  52436. * @param from Starting frame of the animation range
  52437. * @param to Ending frame of the animation
  52438. */
  52439. Animation.prototype.createRange = function (name, from, to) {
  52440. // check name not already in use; could happen for bones after serialized
  52441. if (!this._ranges[name]) {
  52442. this._ranges[name] = new AnimationRange(name, from, to);
  52443. }
  52444. };
  52445. /**
  52446. * Deletes an animation range by name
  52447. * @param name Name of the animation range to delete
  52448. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  52449. */
  52450. Animation.prototype.deleteRange = function (name, deleteFrames) {
  52451. if (deleteFrames === void 0) { deleteFrames = true; }
  52452. var range = this._ranges[name];
  52453. if (!range) {
  52454. return;
  52455. }
  52456. if (deleteFrames) {
  52457. var from = range.from;
  52458. var to = range.to;
  52459. // this loop MUST go high to low for multiple splices to work
  52460. for (var key = this._keys.length - 1; key >= 0; key--) {
  52461. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  52462. this._keys.splice(key, 1);
  52463. }
  52464. }
  52465. }
  52466. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  52467. };
  52468. /**
  52469. * Gets the animation range by name, or null if not defined
  52470. * @param name Name of the animation range
  52471. * @returns Nullable animation range
  52472. */
  52473. Animation.prototype.getRange = function (name) {
  52474. return this._ranges[name];
  52475. };
  52476. /**
  52477. * Gets the key frames from the animation
  52478. * @returns The key frames of the animation
  52479. */
  52480. Animation.prototype.getKeys = function () {
  52481. return this._keys;
  52482. };
  52483. /**
  52484. * Gets the highest frame rate of the animation
  52485. * @returns Highest frame rate of the animation
  52486. */
  52487. Animation.prototype.getHighestFrame = function () {
  52488. var ret = 0;
  52489. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  52490. if (ret < this._keys[key].frame) {
  52491. ret = this._keys[key].frame;
  52492. }
  52493. }
  52494. return ret;
  52495. };
  52496. /**
  52497. * Gets the easing function of the animation
  52498. * @returns Easing function of the animation
  52499. */
  52500. Animation.prototype.getEasingFunction = function () {
  52501. return this._easingFunction;
  52502. };
  52503. /**
  52504. * Sets the easing function of the animation
  52505. * @param easingFunction A custom mathematical formula for animation
  52506. */
  52507. Animation.prototype.setEasingFunction = function (easingFunction) {
  52508. this._easingFunction = easingFunction;
  52509. };
  52510. /**
  52511. * Interpolates a scalar linearly
  52512. * @param startValue Start value of the animation curve
  52513. * @param endValue End value of the animation curve
  52514. * @param gradient Scalar amount to interpolate
  52515. * @returns Interpolated scalar value
  52516. */
  52517. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  52518. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  52519. };
  52520. /**
  52521. * Interpolates a scalar cubically
  52522. * @param startValue Start value of the animation curve
  52523. * @param outTangent End tangent of the animation
  52524. * @param endValue End value of the animation curve
  52525. * @param inTangent Start tangent of the animation curve
  52526. * @param gradient Scalar amount to interpolate
  52527. * @returns Interpolated scalar value
  52528. */
  52529. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52530. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52531. };
  52532. /**
  52533. * Interpolates a quaternion using a spherical linear interpolation
  52534. * @param startValue Start value of the animation curve
  52535. * @param endValue End value of the animation curve
  52536. * @param gradient Scalar amount to interpolate
  52537. * @returns Interpolated quaternion value
  52538. */
  52539. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  52540. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  52541. };
  52542. /**
  52543. * Interpolates a quaternion cubically
  52544. * @param startValue Start value of the animation curve
  52545. * @param outTangent End tangent of the animation curve
  52546. * @param endValue End value of the animation curve
  52547. * @param inTangent Start tangent of the animation curve
  52548. * @param gradient Scalar amount to interpolate
  52549. * @returns Interpolated quaternion value
  52550. */
  52551. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52552. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  52553. };
  52554. /**
  52555. * Interpolates a Vector3 linearl
  52556. * @param startValue Start value of the animation curve
  52557. * @param endValue End value of the animation curve
  52558. * @param gradient Scalar amount to interpolate
  52559. * @returns Interpolated scalar value
  52560. */
  52561. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  52562. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  52563. };
  52564. /**
  52565. * Interpolates a Vector3 cubically
  52566. * @param startValue Start value of the animation curve
  52567. * @param outTangent End tangent of the animation
  52568. * @param endValue End value of the animation curve
  52569. * @param inTangent Start tangent of the animation curve
  52570. * @param gradient Scalar amount to interpolate
  52571. * @returns InterpolatedVector3 value
  52572. */
  52573. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52574. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52575. };
  52576. /**
  52577. * Interpolates a Vector2 linearly
  52578. * @param startValue Start value of the animation curve
  52579. * @param endValue End value of the animation curve
  52580. * @param gradient Scalar amount to interpolate
  52581. * @returns Interpolated Vector2 value
  52582. */
  52583. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  52584. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  52585. };
  52586. /**
  52587. * Interpolates a Vector2 cubically
  52588. * @param startValue Start value of the animation curve
  52589. * @param outTangent End tangent of the animation
  52590. * @param endValue End value of the animation curve
  52591. * @param inTangent Start tangent of the animation curve
  52592. * @param gradient Scalar amount to interpolate
  52593. * @returns Interpolated Vector2 value
  52594. */
  52595. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52596. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52597. };
  52598. /**
  52599. * Interpolates a size linearly
  52600. * @param startValue Start value of the animation curve
  52601. * @param endValue End value of the animation curve
  52602. * @param gradient Scalar amount to interpolate
  52603. * @returns Interpolated Size value
  52604. */
  52605. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  52606. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  52607. };
  52608. /**
  52609. * Interpolates a Color3 linearly
  52610. * @param startValue Start value of the animation curve
  52611. * @param endValue End value of the animation curve
  52612. * @param gradient Scalar amount to interpolate
  52613. * @returns Interpolated Color3 value
  52614. */
  52615. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  52616. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  52617. };
  52618. /**
  52619. * @hidden Internal use only
  52620. */
  52621. Animation.prototype._getKeyValue = function (value) {
  52622. if (typeof value === "function") {
  52623. return value();
  52624. }
  52625. return value;
  52626. };
  52627. /**
  52628. * @hidden Internal use only
  52629. */
  52630. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52631. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52632. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52633. }
  52634. var keys = this.getKeys();
  52635. // Try to get a hash to find the right key
  52636. 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));
  52637. if (keys[startKeyIndex].frame >= currentFrame) {
  52638. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52639. startKeyIndex--;
  52640. }
  52641. }
  52642. for (var key = startKeyIndex; key < keys.length; key++) {
  52643. var endKey = keys[key + 1];
  52644. if (endKey.frame >= currentFrame) {
  52645. var startKey = keys[key];
  52646. var startValue = this._getKeyValue(startKey.value);
  52647. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52648. return startValue;
  52649. }
  52650. var endValue = this._getKeyValue(endKey.value);
  52651. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52652. var frameDelta = endKey.frame - startKey.frame;
  52653. // gradient : percent of currentFrame between the frame inf and the frame sup
  52654. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52655. // check for easingFunction and correction of gradient
  52656. var easingFunction = this.getEasingFunction();
  52657. if (easingFunction != null) {
  52658. gradient = easingFunction.ease(gradient);
  52659. }
  52660. switch (this.dataType) {
  52661. // Float
  52662. case Animation.ANIMATIONTYPE_FLOAT:
  52663. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52664. switch (loopMode) {
  52665. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52666. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52667. return floatValue;
  52668. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52669. return offsetValue * repeatCount + floatValue;
  52670. }
  52671. break;
  52672. // Quaternion
  52673. case Animation.ANIMATIONTYPE_QUATERNION:
  52674. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52675. switch (loopMode) {
  52676. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52677. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52678. return quatValue;
  52679. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52680. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52681. }
  52682. return quatValue;
  52683. // Vector3
  52684. case Animation.ANIMATIONTYPE_VECTOR3:
  52685. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52686. switch (loopMode) {
  52687. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52688. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52689. return vec3Value;
  52690. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52691. return vec3Value.add(offsetValue.scale(repeatCount));
  52692. }
  52693. // Vector2
  52694. case Animation.ANIMATIONTYPE_VECTOR2:
  52695. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52696. switch (loopMode) {
  52697. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52698. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52699. return vec2Value;
  52700. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52701. return vec2Value.add(offsetValue.scale(repeatCount));
  52702. }
  52703. // Size
  52704. case Animation.ANIMATIONTYPE_SIZE:
  52705. switch (loopMode) {
  52706. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52707. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52708. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52709. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52710. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52711. }
  52712. // Color3
  52713. case Animation.ANIMATIONTYPE_COLOR3:
  52714. switch (loopMode) {
  52715. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52716. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52717. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52718. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52719. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52720. }
  52721. // Matrix
  52722. case Animation.ANIMATIONTYPE_MATRIX:
  52723. switch (loopMode) {
  52724. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52725. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52726. if (Animation.AllowMatricesInterpolation) {
  52727. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52728. }
  52729. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52730. return startValue;
  52731. }
  52732. default:
  52733. break;
  52734. }
  52735. break;
  52736. }
  52737. }
  52738. return this._getKeyValue(keys[keys.length - 1].value);
  52739. };
  52740. /**
  52741. * Defines the function to use to interpolate matrices
  52742. * @param startValue defines the start matrix
  52743. * @param endValue defines the end matrix
  52744. * @param gradient defines the gradient between both matrices
  52745. * @param result defines an optional target matrix where to store the interpolation
  52746. * @returns the interpolated matrix
  52747. */
  52748. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52749. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52750. if (result) {
  52751. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52752. return result;
  52753. }
  52754. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52755. }
  52756. if (result) {
  52757. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52758. return result;
  52759. }
  52760. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52761. };
  52762. /**
  52763. * Makes a copy of the animation
  52764. * @returns Cloned animation
  52765. */
  52766. Animation.prototype.clone = function () {
  52767. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52768. clone.enableBlending = this.enableBlending;
  52769. clone.blendingSpeed = this.blendingSpeed;
  52770. if (this._keys) {
  52771. clone.setKeys(this._keys);
  52772. }
  52773. if (this._ranges) {
  52774. clone._ranges = {};
  52775. for (var name in this._ranges) {
  52776. var range = this._ranges[name];
  52777. if (!range) {
  52778. continue;
  52779. }
  52780. clone._ranges[name] = range.clone();
  52781. }
  52782. }
  52783. return clone;
  52784. };
  52785. /**
  52786. * Sets the key frames of the animation
  52787. * @param values The animation key frames to set
  52788. */
  52789. Animation.prototype.setKeys = function (values) {
  52790. this._keys = values.slice(0);
  52791. };
  52792. /**
  52793. * Serializes the animation to an object
  52794. * @returns Serialized object
  52795. */
  52796. Animation.prototype.serialize = function () {
  52797. var serializationObject = {};
  52798. serializationObject.name = this.name;
  52799. serializationObject.property = this.targetProperty;
  52800. serializationObject.framePerSecond = this.framePerSecond;
  52801. serializationObject.dataType = this.dataType;
  52802. serializationObject.loopBehavior = this.loopMode;
  52803. serializationObject.enableBlending = this.enableBlending;
  52804. serializationObject.blendingSpeed = this.blendingSpeed;
  52805. var dataType = this.dataType;
  52806. serializationObject.keys = [];
  52807. var keys = this.getKeys();
  52808. for (var index = 0; index < keys.length; index++) {
  52809. var animationKey = keys[index];
  52810. var key = {};
  52811. key.frame = animationKey.frame;
  52812. switch (dataType) {
  52813. case Animation.ANIMATIONTYPE_FLOAT:
  52814. key.values = [animationKey.value];
  52815. break;
  52816. case Animation.ANIMATIONTYPE_QUATERNION:
  52817. case Animation.ANIMATIONTYPE_MATRIX:
  52818. case Animation.ANIMATIONTYPE_VECTOR3:
  52819. case Animation.ANIMATIONTYPE_COLOR3:
  52820. key.values = animationKey.value.asArray();
  52821. break;
  52822. }
  52823. serializationObject.keys.push(key);
  52824. }
  52825. serializationObject.ranges = [];
  52826. for (var name in this._ranges) {
  52827. var source = this._ranges[name];
  52828. if (!source) {
  52829. continue;
  52830. }
  52831. var range = {};
  52832. range.name = name;
  52833. range.from = source.from;
  52834. range.to = source.to;
  52835. serializationObject.ranges.push(range);
  52836. }
  52837. return serializationObject;
  52838. };
  52839. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52840. /**
  52841. * Get the float animation type
  52842. */
  52843. get: function () {
  52844. return Animation._ANIMATIONTYPE_FLOAT;
  52845. },
  52846. enumerable: true,
  52847. configurable: true
  52848. });
  52849. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52850. /**
  52851. * Get the Vector3 animation type
  52852. */
  52853. get: function () {
  52854. return Animation._ANIMATIONTYPE_VECTOR3;
  52855. },
  52856. enumerable: true,
  52857. configurable: true
  52858. });
  52859. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52860. /**
  52861. * Get the Vector2 animation type
  52862. */
  52863. get: function () {
  52864. return Animation._ANIMATIONTYPE_VECTOR2;
  52865. },
  52866. enumerable: true,
  52867. configurable: true
  52868. });
  52869. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52870. /**
  52871. * Get the Size animation type
  52872. */
  52873. get: function () {
  52874. return Animation._ANIMATIONTYPE_SIZE;
  52875. },
  52876. enumerable: true,
  52877. configurable: true
  52878. });
  52879. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52880. /**
  52881. * Get the Quaternion animation type
  52882. */
  52883. get: function () {
  52884. return Animation._ANIMATIONTYPE_QUATERNION;
  52885. },
  52886. enumerable: true,
  52887. configurable: true
  52888. });
  52889. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52890. /**
  52891. * Get the Matrix animation type
  52892. */
  52893. get: function () {
  52894. return Animation._ANIMATIONTYPE_MATRIX;
  52895. },
  52896. enumerable: true,
  52897. configurable: true
  52898. });
  52899. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52900. /**
  52901. * Get the Color3 animation type
  52902. */
  52903. get: function () {
  52904. return Animation._ANIMATIONTYPE_COLOR3;
  52905. },
  52906. enumerable: true,
  52907. configurable: true
  52908. });
  52909. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52910. /**
  52911. * Get the Relative Loop Mode
  52912. */
  52913. get: function () {
  52914. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52915. },
  52916. enumerable: true,
  52917. configurable: true
  52918. });
  52919. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52920. /**
  52921. * Get the Cycle Loop Mode
  52922. */
  52923. get: function () {
  52924. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52925. },
  52926. enumerable: true,
  52927. configurable: true
  52928. });
  52929. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52930. /**
  52931. * Get the Constant Loop Mode
  52932. */
  52933. get: function () {
  52934. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52935. },
  52936. enumerable: true,
  52937. configurable: true
  52938. });
  52939. /** @hidden */
  52940. Animation._UniversalLerp = function (left, right, amount) {
  52941. var constructor = left.constructor;
  52942. if (constructor.Lerp) { // Lerp supported
  52943. return constructor.Lerp(left, right, amount);
  52944. }
  52945. else if (constructor.Slerp) { // Slerp supported
  52946. return constructor.Slerp(left, right, amount);
  52947. }
  52948. else if (left.toFixed) { // Number
  52949. return left * (1.0 - amount) + amount * right;
  52950. }
  52951. else { // Blending not supported
  52952. return right;
  52953. }
  52954. };
  52955. /**
  52956. * Parses an animation object and creates an animation
  52957. * @param parsedAnimation Parsed animation object
  52958. * @returns Animation object
  52959. */
  52960. Animation.Parse = function (parsedAnimation) {
  52961. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52962. var dataType = parsedAnimation.dataType;
  52963. var keys = [];
  52964. var data;
  52965. var index;
  52966. if (parsedAnimation.enableBlending) {
  52967. animation.enableBlending = parsedAnimation.enableBlending;
  52968. }
  52969. if (parsedAnimation.blendingSpeed) {
  52970. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52971. }
  52972. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52973. var key = parsedAnimation.keys[index];
  52974. var inTangent;
  52975. var outTangent;
  52976. switch (dataType) {
  52977. case Animation.ANIMATIONTYPE_FLOAT:
  52978. data = key.values[0];
  52979. if (key.values.length >= 1) {
  52980. inTangent = key.values[1];
  52981. }
  52982. if (key.values.length >= 2) {
  52983. outTangent = key.values[2];
  52984. }
  52985. break;
  52986. case Animation.ANIMATIONTYPE_QUATERNION:
  52987. data = BABYLON.Quaternion.FromArray(key.values);
  52988. if (key.values.length >= 8) {
  52989. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52990. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52991. inTangent = _inTangent;
  52992. }
  52993. }
  52994. if (key.values.length >= 12) {
  52995. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52996. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52997. outTangent = _outTangent;
  52998. }
  52999. }
  53000. break;
  53001. case Animation.ANIMATIONTYPE_MATRIX:
  53002. data = BABYLON.Matrix.FromArray(key.values);
  53003. break;
  53004. case Animation.ANIMATIONTYPE_COLOR3:
  53005. data = BABYLON.Color3.FromArray(key.values);
  53006. break;
  53007. case Animation.ANIMATIONTYPE_VECTOR3:
  53008. default:
  53009. data = BABYLON.Vector3.FromArray(key.values);
  53010. break;
  53011. }
  53012. var keyData = {};
  53013. keyData.frame = key.frame;
  53014. keyData.value = data;
  53015. if (inTangent != undefined) {
  53016. keyData.inTangent = inTangent;
  53017. }
  53018. if (outTangent != undefined) {
  53019. keyData.outTangent = outTangent;
  53020. }
  53021. keys.push(keyData);
  53022. }
  53023. animation.setKeys(keys);
  53024. if (parsedAnimation.ranges) {
  53025. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  53026. data = parsedAnimation.ranges[index];
  53027. animation.createRange(data.name, data.from, data.to);
  53028. }
  53029. }
  53030. return animation;
  53031. };
  53032. /**
  53033. * Appends the serialized animations from the source animations
  53034. * @param source Source containing the animations
  53035. * @param destination Target to store the animations
  53036. */
  53037. Animation.AppendSerializedAnimations = function (source, destination) {
  53038. if (source.animations) {
  53039. destination.animations = [];
  53040. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  53041. var animation = source.animations[animationIndex];
  53042. destination.animations.push(animation.serialize());
  53043. }
  53044. }
  53045. };
  53046. /**
  53047. * Use matrix interpolation instead of using direct key value when animating matrices
  53048. */
  53049. Animation.AllowMatricesInterpolation = false;
  53050. /**
  53051. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  53052. */
  53053. Animation.AllowMatrixDecomposeForInterpolation = true;
  53054. // Statics
  53055. /**
  53056. * Float animation type
  53057. */
  53058. Animation._ANIMATIONTYPE_FLOAT = 0;
  53059. /**
  53060. * Vector3 animation type
  53061. */
  53062. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  53063. /**
  53064. * Quaternion animation type
  53065. */
  53066. Animation._ANIMATIONTYPE_QUATERNION = 2;
  53067. /**
  53068. * Matrix animation type
  53069. */
  53070. Animation._ANIMATIONTYPE_MATRIX = 3;
  53071. /**
  53072. * Color3 animation type
  53073. */
  53074. Animation._ANIMATIONTYPE_COLOR3 = 4;
  53075. /**
  53076. * Vector2 animation type
  53077. */
  53078. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  53079. /**
  53080. * Size animation type
  53081. */
  53082. Animation._ANIMATIONTYPE_SIZE = 6;
  53083. /**
  53084. * Relative Loop Mode
  53085. */
  53086. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  53087. /**
  53088. * Cycle Loop Mode
  53089. */
  53090. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  53091. /**
  53092. * Constant Loop Mode
  53093. */
  53094. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  53095. return Animation;
  53096. }());
  53097. BABYLON.Animation = Animation;
  53098. })(BABYLON || (BABYLON = {}));
  53099. //# sourceMappingURL=babylon.animation.js.map
  53100. var BABYLON;
  53101. (function (BABYLON) {
  53102. /**
  53103. * This class defines the direct association between an animation and a target
  53104. */
  53105. var TargetedAnimation = /** @class */ (function () {
  53106. function TargetedAnimation() {
  53107. }
  53108. return TargetedAnimation;
  53109. }());
  53110. BABYLON.TargetedAnimation = TargetedAnimation;
  53111. /**
  53112. * Use this class to create coordinated animations on multiple targets
  53113. */
  53114. var AnimationGroup = /** @class */ (function () {
  53115. /**
  53116. * Instantiates a new Animation Group.
  53117. * This helps managing several animations at once.
  53118. * @see http://doc.babylonjs.com/how_to/group
  53119. * @param name Defines the name of the group
  53120. * @param scene Defines the scene the group belongs to
  53121. */
  53122. function AnimationGroup(
  53123. /** The name of the animation group */
  53124. name, scene) {
  53125. if (scene === void 0) { scene = null; }
  53126. this.name = name;
  53127. this._targetedAnimations = new Array();
  53128. this._animatables = new Array();
  53129. this._from = Number.MAX_VALUE;
  53130. this._to = -Number.MAX_VALUE;
  53131. this._speedRatio = 1;
  53132. /**
  53133. * This observable will notify when one animation have ended.
  53134. */
  53135. this.onAnimationEndObservable = new BABYLON.Observable();
  53136. /**
  53137. * This observable will notify when all animations have ended.
  53138. */
  53139. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  53140. /**
  53141. * This observable will notify when all animations have paused.
  53142. */
  53143. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  53144. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53145. this._scene.animationGroups.push(this);
  53146. }
  53147. Object.defineProperty(AnimationGroup.prototype, "from", {
  53148. /**
  53149. * Gets the first frame
  53150. */
  53151. get: function () {
  53152. return this._from;
  53153. },
  53154. enumerable: true,
  53155. configurable: true
  53156. });
  53157. Object.defineProperty(AnimationGroup.prototype, "to", {
  53158. /**
  53159. * Gets the last frame
  53160. */
  53161. get: function () {
  53162. return this._to;
  53163. },
  53164. enumerable: true,
  53165. configurable: true
  53166. });
  53167. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  53168. /**
  53169. * Define if the animations are started
  53170. */
  53171. get: function () {
  53172. return this._isStarted;
  53173. },
  53174. enumerable: true,
  53175. configurable: true
  53176. });
  53177. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  53178. /**
  53179. * Gets or sets the speed ratio to use for all animations
  53180. */
  53181. get: function () {
  53182. return this._speedRatio;
  53183. },
  53184. /**
  53185. * Gets or sets the speed ratio to use for all animations
  53186. */
  53187. set: function (value) {
  53188. if (this._speedRatio === value) {
  53189. return;
  53190. }
  53191. this._speedRatio = value;
  53192. for (var index = 0; index < this._animatables.length; index++) {
  53193. var animatable = this._animatables[index];
  53194. animatable.speedRatio = this._speedRatio;
  53195. }
  53196. },
  53197. enumerable: true,
  53198. configurable: true
  53199. });
  53200. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  53201. /**
  53202. * Gets the targeted animations for this animation group
  53203. */
  53204. get: function () {
  53205. return this._targetedAnimations;
  53206. },
  53207. enumerable: true,
  53208. configurable: true
  53209. });
  53210. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  53211. /**
  53212. * returning the list of animatables controlled by this animation group.
  53213. */
  53214. get: function () {
  53215. return this._animatables;
  53216. },
  53217. enumerable: true,
  53218. configurable: true
  53219. });
  53220. /**
  53221. * Add an animation (with its target) in the group
  53222. * @param animation defines the animation we want to add
  53223. * @param target defines the target of the animation
  53224. * @returns the TargetedAnimation object
  53225. */
  53226. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  53227. var targetedAnimation = {
  53228. animation: animation,
  53229. target: target
  53230. };
  53231. var keys = animation.getKeys();
  53232. if (this._from > keys[0].frame) {
  53233. this._from = keys[0].frame;
  53234. }
  53235. if (this._to < keys[keys.length - 1].frame) {
  53236. this._to = keys[keys.length - 1].frame;
  53237. }
  53238. this._targetedAnimations.push(targetedAnimation);
  53239. return targetedAnimation;
  53240. };
  53241. /**
  53242. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  53243. * It can add constant keys at begin or end
  53244. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  53245. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  53246. * @returns the animation group
  53247. */
  53248. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  53249. if (beginFrame === void 0) { beginFrame = null; }
  53250. if (endFrame === void 0) { endFrame = null; }
  53251. if (beginFrame == null) {
  53252. beginFrame = this._from;
  53253. }
  53254. if (endFrame == null) {
  53255. endFrame = this._to;
  53256. }
  53257. for (var index = 0; index < this._targetedAnimations.length; index++) {
  53258. var targetedAnimation = this._targetedAnimations[index];
  53259. var keys = targetedAnimation.animation.getKeys();
  53260. var startKey = keys[0];
  53261. var endKey = keys[keys.length - 1];
  53262. if (startKey.frame > beginFrame) {
  53263. var newKey = {
  53264. frame: beginFrame,
  53265. value: startKey.value,
  53266. inTangent: startKey.inTangent,
  53267. outTangent: startKey.outTangent,
  53268. interpolation: startKey.interpolation
  53269. };
  53270. keys.splice(0, 0, newKey);
  53271. }
  53272. if (endKey.frame < endFrame) {
  53273. var newKey = {
  53274. frame: endFrame,
  53275. value: endKey.value,
  53276. inTangent: endKey.outTangent,
  53277. outTangent: endKey.outTangent,
  53278. interpolation: endKey.interpolation
  53279. };
  53280. keys.push(newKey);
  53281. }
  53282. }
  53283. this._from = beginFrame;
  53284. this._to = endFrame;
  53285. return this;
  53286. };
  53287. /**
  53288. * Start all animations on given targets
  53289. * @param loop defines if animations must loop
  53290. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  53291. * @param from defines the from key (optional)
  53292. * @param to defines the to key (optional)
  53293. * @returns the current animation group
  53294. */
  53295. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  53296. var _this = this;
  53297. if (loop === void 0) { loop = false; }
  53298. if (speedRatio === void 0) { speedRatio = 1; }
  53299. if (this._isStarted || this._targetedAnimations.length === 0) {
  53300. return this;
  53301. }
  53302. var _loop_1 = function (targetedAnimation) {
  53303. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  53304. animatable.onAnimationEnd = function () {
  53305. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  53306. _this._checkAnimationGroupEnded(animatable);
  53307. };
  53308. this_1._animatables.push(animatable);
  53309. };
  53310. var this_1 = this;
  53311. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  53312. var targetedAnimation = _a[_i];
  53313. _loop_1(targetedAnimation);
  53314. }
  53315. this._speedRatio = speedRatio;
  53316. this._isStarted = true;
  53317. return this;
  53318. };
  53319. /**
  53320. * Pause all animations
  53321. * @returns the animation group
  53322. */
  53323. AnimationGroup.prototype.pause = function () {
  53324. if (!this._isStarted) {
  53325. return this;
  53326. }
  53327. for (var index = 0; index < this._animatables.length; index++) {
  53328. var animatable = this._animatables[index];
  53329. animatable.pause();
  53330. }
  53331. this.onAnimationGroupPauseObservable.notifyObservers(this);
  53332. return this;
  53333. };
  53334. /**
  53335. * Play all animations to initial state
  53336. * This function will start() the animations if they were not started or will restart() them if they were paused
  53337. * @param loop defines if animations must loop
  53338. * @returns the animation group
  53339. */
  53340. AnimationGroup.prototype.play = function (loop) {
  53341. // only if all animatables are ready and exist
  53342. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  53343. if (loop !== undefined) {
  53344. for (var index = 0; index < this._animatables.length; index++) {
  53345. var animatable = this._animatables[index];
  53346. animatable.loopAnimation = loop;
  53347. }
  53348. }
  53349. this.restart();
  53350. }
  53351. else {
  53352. this.stop();
  53353. this.start(loop, this._speedRatio);
  53354. }
  53355. return this;
  53356. };
  53357. /**
  53358. * Reset all animations to initial state
  53359. * @returns the animation group
  53360. */
  53361. AnimationGroup.prototype.reset = function () {
  53362. if (!this._isStarted) {
  53363. return this;
  53364. }
  53365. for (var index = 0; index < this._animatables.length; index++) {
  53366. var animatable = this._animatables[index];
  53367. animatable.reset();
  53368. }
  53369. return this;
  53370. };
  53371. /**
  53372. * Restart animations from key 0
  53373. * @returns the animation group
  53374. */
  53375. AnimationGroup.prototype.restart = function () {
  53376. if (!this._isStarted) {
  53377. return this;
  53378. }
  53379. for (var index = 0; index < this._animatables.length; index++) {
  53380. var animatable = this._animatables[index];
  53381. animatable.restart();
  53382. }
  53383. return this;
  53384. };
  53385. /**
  53386. * Stop all animations
  53387. * @returns the animation group
  53388. */
  53389. AnimationGroup.prototype.stop = function () {
  53390. if (!this._isStarted) {
  53391. return this;
  53392. }
  53393. var list = this._animatables.slice();
  53394. for (var index = 0; index < list.length; index++) {
  53395. list[index].stop();
  53396. }
  53397. this._isStarted = false;
  53398. return this;
  53399. };
  53400. /**
  53401. * Set animation weight for all animatables
  53402. * @param weight defines the weight to use
  53403. * @return the animationGroup
  53404. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53405. */
  53406. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  53407. for (var index = 0; index < this._animatables.length; index++) {
  53408. var animatable = this._animatables[index];
  53409. animatable.weight = weight;
  53410. }
  53411. return this;
  53412. };
  53413. /**
  53414. * Synchronize and normalize all animatables with a source animatable
  53415. * @param root defines the root animatable to synchronize with
  53416. * @return the animationGroup
  53417. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53418. */
  53419. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  53420. for (var index = 0; index < this._animatables.length; index++) {
  53421. var animatable = this._animatables[index];
  53422. animatable.syncWith(root);
  53423. }
  53424. return this;
  53425. };
  53426. /**
  53427. * Goes to a specific frame in this animation group
  53428. * @param frame the frame number to go to
  53429. * @return the animationGroup
  53430. */
  53431. AnimationGroup.prototype.goToFrame = function (frame) {
  53432. if (!this._isStarted) {
  53433. return this;
  53434. }
  53435. for (var index = 0; index < this._animatables.length; index++) {
  53436. var animatable = this._animatables[index];
  53437. animatable.goToFrame(frame);
  53438. }
  53439. return this;
  53440. };
  53441. /**
  53442. * Dispose all associated resources
  53443. */
  53444. AnimationGroup.prototype.dispose = function () {
  53445. this._targetedAnimations = [];
  53446. this._animatables = [];
  53447. var index = this._scene.animationGroups.indexOf(this);
  53448. if (index > -1) {
  53449. this._scene.animationGroups.splice(index, 1);
  53450. }
  53451. };
  53452. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  53453. // animatable should be taken out of the array
  53454. var idx = this._animatables.indexOf(animatable);
  53455. if (idx > -1) {
  53456. this._animatables.splice(idx, 1);
  53457. }
  53458. // all animatables were removed? animation group ended!
  53459. if (this._animatables.length === 0) {
  53460. this._isStarted = false;
  53461. this.onAnimationGroupEndObservable.notifyObservers(this);
  53462. }
  53463. };
  53464. // Statics
  53465. /**
  53466. * Returns a new AnimationGroup object parsed from the source provided.
  53467. * @param parsedAnimationGroup defines the source
  53468. * @param scene defines the scene that will receive the animationGroup
  53469. * @returns a new AnimationGroup
  53470. */
  53471. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  53472. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  53473. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  53474. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  53475. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  53476. var id = targetedAnimation.targetId;
  53477. var targetNode = scene.getNodeByID(id);
  53478. if (targetNode != null) {
  53479. animationGroup.addTargetedAnimation(animation, targetNode);
  53480. }
  53481. }
  53482. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  53483. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  53484. }
  53485. return animationGroup;
  53486. };
  53487. /**
  53488. * Returns the string "AnimationGroup"
  53489. * @returns "AnimationGroup"
  53490. */
  53491. AnimationGroup.prototype.getClassName = function () {
  53492. return "AnimationGroup";
  53493. };
  53494. /**
  53495. * Creates a detailled string about the object
  53496. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  53497. * @returns a string representing the object
  53498. */
  53499. AnimationGroup.prototype.toString = function (fullDetails) {
  53500. var ret = "Name: " + this.name;
  53501. ret += ", type: " + this.getClassName();
  53502. if (fullDetails) {
  53503. ret += ", from: " + this._from;
  53504. ret += ", to: " + this._to;
  53505. ret += ", isStarted: " + this._isStarted;
  53506. ret += ", speedRatio: " + this._speedRatio;
  53507. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  53508. ret += ", animatables length: " + this._animatables;
  53509. }
  53510. return ret;
  53511. };
  53512. return AnimationGroup;
  53513. }());
  53514. BABYLON.AnimationGroup = AnimationGroup;
  53515. })(BABYLON || (BABYLON = {}));
  53516. //# sourceMappingURL=babylon.animationGroup.js.map
  53517. var BABYLON;
  53518. (function (BABYLON) {
  53519. // Static values to help the garbage collector
  53520. // Quaternion
  53521. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  53522. // Vector3
  53523. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  53524. // Vector2
  53525. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  53526. // Size
  53527. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  53528. // Color3
  53529. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  53530. /**
  53531. * Defines a runtime animation
  53532. */
  53533. var RuntimeAnimation = /** @class */ (function () {
  53534. /**
  53535. * Create a new RuntimeAnimation object
  53536. * @param target defines the target of the animation
  53537. * @param animation defines the source animation object
  53538. * @param scene defines the hosting scene
  53539. * @param host defines the initiating Animatable
  53540. */
  53541. function RuntimeAnimation(target, animation, scene, host) {
  53542. var _this = this;
  53543. this._events = new Array();
  53544. /**
  53545. * The current frame of the runtime animation
  53546. */
  53547. this._currentFrame = 0;
  53548. /**
  53549. * The original value of the runtime animation
  53550. */
  53551. this._originalValue = new Array();
  53552. /**
  53553. * The offsets cache of the runtime animation
  53554. */
  53555. this._offsetsCache = {};
  53556. /**
  53557. * The high limits cache of the runtime animation
  53558. */
  53559. this._highLimitsCache = {};
  53560. /**
  53561. * Specifies if the runtime animation has been stopped
  53562. */
  53563. this._stopped = false;
  53564. /**
  53565. * The blending factor of the runtime animation
  53566. */
  53567. this._blendingFactor = 0;
  53568. /**
  53569. * The target path of the runtime animation
  53570. */
  53571. this._targetPath = "";
  53572. /**
  53573. * The weight of the runtime animation
  53574. */
  53575. this._weight = 1.0;
  53576. /**
  53577. * The ratio offset of the runtime animation
  53578. */
  53579. this._ratioOffset = 0;
  53580. /**
  53581. * The previous delay of the runtime animation
  53582. */
  53583. this._previousDelay = 0;
  53584. /**
  53585. * The previous ratio of the runtime animation
  53586. */
  53587. this._previousRatio = 0;
  53588. this._animation = animation;
  53589. this._target = target;
  53590. this._scene = scene;
  53591. this._host = host;
  53592. animation._runtimeAnimations.push(this);
  53593. // Cloning events locally
  53594. var events = animation.getEvents();
  53595. if (events && events.length > 0) {
  53596. events.forEach(function (e) {
  53597. _this._events.push(e._clone());
  53598. });
  53599. }
  53600. }
  53601. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  53602. /**
  53603. * Gets the current frame of the runtime animation
  53604. */
  53605. get: function () {
  53606. return this._currentFrame;
  53607. },
  53608. enumerable: true,
  53609. configurable: true
  53610. });
  53611. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  53612. /**
  53613. * Gets the weight of the runtime animation
  53614. */
  53615. get: function () {
  53616. return this._weight;
  53617. },
  53618. enumerable: true,
  53619. configurable: true
  53620. });
  53621. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  53622. /**
  53623. * Gets the current value of the runtime animation
  53624. */
  53625. get: function () {
  53626. return this._currentValue;
  53627. },
  53628. enumerable: true,
  53629. configurable: true
  53630. });
  53631. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  53632. /**
  53633. * Gets the target path of the runtime animation
  53634. */
  53635. get: function () {
  53636. return this._targetPath;
  53637. },
  53638. enumerable: true,
  53639. configurable: true
  53640. });
  53641. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53642. /**
  53643. * Gets the actual target of the runtime animation
  53644. */
  53645. get: function () {
  53646. return this._activeTarget;
  53647. },
  53648. enumerable: true,
  53649. configurable: true
  53650. });
  53651. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53652. /**
  53653. * Gets the animation from the runtime animation
  53654. */
  53655. get: function () {
  53656. return this._animation;
  53657. },
  53658. enumerable: true,
  53659. configurable: true
  53660. });
  53661. /**
  53662. * Resets the runtime animation to the beginning
  53663. * @param restoreOriginal defines whether to restore the target property to the original value
  53664. */
  53665. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53666. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53667. if (restoreOriginal) {
  53668. if (this._target instanceof Array) {
  53669. var index = 0;
  53670. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53671. var target = _a[_i];
  53672. if (this._originalValue[index] !== undefined) {
  53673. this._setValue(target, this._originalValue[index], -1);
  53674. }
  53675. index++;
  53676. }
  53677. }
  53678. else {
  53679. if (this._originalValue[0] !== undefined) {
  53680. this._setValue(this._target, this._originalValue[0], -1);
  53681. }
  53682. }
  53683. }
  53684. this._offsetsCache = {};
  53685. this._highLimitsCache = {};
  53686. this._currentFrame = 0;
  53687. this._blendingFactor = 0;
  53688. this._originalValue = new Array();
  53689. // Events
  53690. for (var index = 0; index < this._events.length; index++) {
  53691. this._events[index].isDone = false;
  53692. }
  53693. };
  53694. /**
  53695. * Specifies if the runtime animation is stopped
  53696. * @returns Boolean specifying if the runtime animation is stopped
  53697. */
  53698. RuntimeAnimation.prototype.isStopped = function () {
  53699. return this._stopped;
  53700. };
  53701. /**
  53702. * Disposes of the runtime animation
  53703. */
  53704. RuntimeAnimation.prototype.dispose = function () {
  53705. var index = this._animation.runtimeAnimations.indexOf(this);
  53706. if (index > -1) {
  53707. this._animation.runtimeAnimations.splice(index, 1);
  53708. }
  53709. };
  53710. /**
  53711. * Interpolates the animation from the current frame
  53712. * @param currentFrame The frame to interpolate the animation to
  53713. * @param repeatCount The number of times that the animation should loop
  53714. * @param loopMode The type of looping mode to use
  53715. * @param offsetValue Animation offset value
  53716. * @param highLimitValue The high limit value
  53717. * @returns The interpolated value
  53718. */
  53719. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53720. this._currentFrame = currentFrame;
  53721. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53722. this._workValue = BABYLON.Matrix.Zero();
  53723. }
  53724. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53725. };
  53726. /**
  53727. * Apply the interpolated value to the target
  53728. * @param currentValue defines the value computed by the animation
  53729. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53730. */
  53731. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53732. if (weight === void 0) { weight = 1.0; }
  53733. if (this._target instanceof Array) {
  53734. var index = 0;
  53735. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53736. var target = _a[_i];
  53737. this._setValue(target, currentValue, weight, index);
  53738. index++;
  53739. }
  53740. }
  53741. else {
  53742. this._setValue(this._target, currentValue, weight);
  53743. }
  53744. };
  53745. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53746. if (targetIndex === void 0) { targetIndex = 0; }
  53747. // Set value
  53748. var path;
  53749. var destination;
  53750. var targetPropertyPath = this._animation.targetPropertyPath;
  53751. if (targetPropertyPath.length > 1) {
  53752. var property = target[targetPropertyPath[0]];
  53753. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53754. property = property[targetPropertyPath[index]];
  53755. }
  53756. path = targetPropertyPath[targetPropertyPath.length - 1];
  53757. destination = property;
  53758. }
  53759. else {
  53760. path = targetPropertyPath[0];
  53761. destination = target;
  53762. }
  53763. this._targetPath = path;
  53764. this._activeTarget = destination;
  53765. this._weight = weight;
  53766. if (this._originalValue[targetIndex] === undefined) {
  53767. var originalValue = void 0;
  53768. if (destination.getRestPose && path === "_matrix") { // For bones
  53769. originalValue = destination.getRestPose();
  53770. }
  53771. else {
  53772. originalValue = destination[path];
  53773. }
  53774. if (originalValue && originalValue.clone) {
  53775. this._originalValue[targetIndex] = originalValue.clone();
  53776. }
  53777. else {
  53778. this._originalValue[targetIndex] = originalValue;
  53779. }
  53780. }
  53781. // Blending
  53782. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53783. if (enableBlending && this._blendingFactor <= 1.0) {
  53784. if (!this._originalBlendValue) {
  53785. var originalValue = destination[path];
  53786. if (originalValue.clone) {
  53787. this._originalBlendValue = originalValue.clone();
  53788. }
  53789. else {
  53790. this._originalBlendValue = originalValue;
  53791. }
  53792. }
  53793. if (this._originalBlendValue.m) { // Matrix
  53794. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53795. if (this._currentValue) {
  53796. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53797. }
  53798. else {
  53799. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53800. }
  53801. }
  53802. else {
  53803. if (this._currentValue) {
  53804. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53805. }
  53806. else {
  53807. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53808. }
  53809. }
  53810. }
  53811. else {
  53812. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53813. }
  53814. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53815. this._blendingFactor += blendingSpeed;
  53816. }
  53817. else {
  53818. this._currentValue = currentValue;
  53819. }
  53820. if (weight !== -1.0) {
  53821. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53822. }
  53823. else {
  53824. destination[path] = this._currentValue;
  53825. }
  53826. if (target.markAsDirty) {
  53827. target.markAsDirty(this._animation.targetProperty);
  53828. }
  53829. };
  53830. /**
  53831. * Gets the loop pmode of the runtime animation
  53832. * @returns Loop Mode
  53833. */
  53834. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53835. if (this._target && this._target.animationPropertiesOverride) {
  53836. return this._target.animationPropertiesOverride.loopMode;
  53837. }
  53838. return this._animation.loopMode;
  53839. };
  53840. /**
  53841. * Move the current animation to a given frame
  53842. * @param frame defines the frame to move to
  53843. */
  53844. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53845. var keys = this._animation.getKeys();
  53846. if (frame < keys[0].frame) {
  53847. frame = keys[0].frame;
  53848. }
  53849. else if (frame > keys[keys.length - 1].frame) {
  53850. frame = keys[keys.length - 1].frame;
  53851. }
  53852. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53853. this.setValue(currentValue, -1);
  53854. };
  53855. /**
  53856. * @hidden Internal use only
  53857. */
  53858. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53859. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53860. this._ratioOffset = this._previousRatio - newRatio;
  53861. };
  53862. /**
  53863. * Execute the current animation
  53864. * @param delay defines the delay to add to the current frame
  53865. * @param from defines the lower bound of the animation range
  53866. * @param to defines the upper bound of the animation range
  53867. * @param loop defines if the current animation must loop
  53868. * @param speedRatio defines the current speed ratio
  53869. * @param weight defines the weight of the animation (default is -1 so no weight)
  53870. * @returns a boolean indicating if the animation is running
  53871. */
  53872. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53873. if (weight === void 0) { weight = -1.0; }
  53874. var targetPropertyPath = this._animation.targetPropertyPath;
  53875. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53876. this._stopped = true;
  53877. return false;
  53878. }
  53879. var returnValue = true;
  53880. var keys = this._animation.getKeys();
  53881. // Adding a start key at frame 0 if missing
  53882. if (keys[0].frame !== 0) {
  53883. var newKey = { frame: 0, value: keys[0].value };
  53884. keys.splice(0, 0, newKey);
  53885. }
  53886. // Adding a duplicate key when there is only one key at frame zero
  53887. else if (keys.length === 1) {
  53888. var newKey = { frame: 0.001, value: keys[0].value };
  53889. keys.push(newKey);
  53890. }
  53891. // Check limits
  53892. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53893. from = keys[0].frame;
  53894. }
  53895. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53896. to = keys[keys.length - 1].frame;
  53897. }
  53898. //to and from cannot be the same key
  53899. if (from === to) {
  53900. if (from > keys[0].frame) {
  53901. from--;
  53902. }
  53903. else if (to < keys[keys.length - 1].frame) {
  53904. to++;
  53905. }
  53906. }
  53907. // Compute ratio
  53908. var range = to - from;
  53909. var offsetValue;
  53910. // ratio represents the frame delta between from and to
  53911. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53912. var highLimitValue = 0;
  53913. this._previousDelay = delay;
  53914. this._previousRatio = ratio;
  53915. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53916. returnValue = false;
  53917. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53918. }
  53919. else {
  53920. // Get max value if required
  53921. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53922. var keyOffset = to.toString() + from.toString();
  53923. if (!this._offsetsCache[keyOffset]) {
  53924. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53925. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53926. switch (this._animation.dataType) {
  53927. // Float
  53928. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53929. this._offsetsCache[keyOffset] = toValue - fromValue;
  53930. break;
  53931. // Quaternion
  53932. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53933. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53934. break;
  53935. // Vector3
  53936. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53937. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53938. // Vector2
  53939. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53940. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53941. // Size
  53942. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53943. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53944. // Color3
  53945. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53946. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53947. default:
  53948. break;
  53949. }
  53950. this._highLimitsCache[keyOffset] = toValue;
  53951. }
  53952. highLimitValue = this._highLimitsCache[keyOffset];
  53953. offsetValue = this._offsetsCache[keyOffset];
  53954. }
  53955. }
  53956. if (offsetValue === undefined) {
  53957. switch (this._animation.dataType) {
  53958. // Float
  53959. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53960. offsetValue = 0;
  53961. break;
  53962. // Quaternion
  53963. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53964. offsetValue = _staticOffsetValueQuaternion;
  53965. break;
  53966. // Vector3
  53967. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53968. offsetValue = _staticOffsetValueVector3;
  53969. break;
  53970. // Vector2
  53971. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53972. offsetValue = _staticOffsetValueVector2;
  53973. break;
  53974. // Size
  53975. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53976. offsetValue = _staticOffsetValueSize;
  53977. break;
  53978. // Color3
  53979. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53980. offsetValue = _staticOffsetValueColor3;
  53981. }
  53982. }
  53983. // Compute value
  53984. var repeatCount = (ratio / range) >> 0;
  53985. var currentFrame = returnValue ? from + ratio % range : to;
  53986. // Need to normalize?
  53987. if (this._host && this._host.syncRoot) {
  53988. var syncRoot = this._host.syncRoot;
  53989. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53990. currentFrame = from + (to - from) * hostNormalizedFrame;
  53991. }
  53992. // Reset events if looping
  53993. var events = this._events;
  53994. if (range > 0 && this.currentFrame > currentFrame ||
  53995. range < 0 && this.currentFrame < currentFrame) {
  53996. // Need to reset animation events
  53997. for (var index = 0; index < events.length; index++) {
  53998. if (!events[index].onlyOnce) {
  53999. // reset event, the animation is looping
  54000. events[index].isDone = false;
  54001. }
  54002. }
  54003. }
  54004. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  54005. // Set value
  54006. this.setValue(currentValue, weight);
  54007. // Check events
  54008. for (var index = 0; index < events.length; index++) {
  54009. // Make sure current frame has passed event frame and that event frame is within the current range
  54010. // Also, handle both forward and reverse animations
  54011. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  54012. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  54013. var event = events[index];
  54014. if (!event.isDone) {
  54015. // If event should be done only once, remove it.
  54016. if (event.onlyOnce) {
  54017. events.splice(index, 1);
  54018. index--;
  54019. }
  54020. event.isDone = true;
  54021. event.action(currentFrame);
  54022. } // Don't do anything if the event has already be done.
  54023. }
  54024. }
  54025. if (!returnValue) {
  54026. this._stopped = true;
  54027. }
  54028. return returnValue;
  54029. };
  54030. return RuntimeAnimation;
  54031. }());
  54032. BABYLON.RuntimeAnimation = RuntimeAnimation;
  54033. })(BABYLON || (BABYLON = {}));
  54034. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  54035. var BABYLON;
  54036. (function (BABYLON) {
  54037. /**
  54038. * Class used to store an actual running animation
  54039. */
  54040. var Animatable = /** @class */ (function () {
  54041. /**
  54042. * Creates a new Animatable
  54043. * @param scene defines the hosting scene
  54044. * @param target defines the target object
  54045. * @param fromFrame defines the starting frame number (default is 0)
  54046. * @param toFrame defines the ending frame number (default is 100)
  54047. * @param loopAnimation defines if the animation must loop (default is false)
  54048. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  54049. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  54050. * @param animations defines a group of animation to add to the new Animatable
  54051. */
  54052. function Animatable(scene,
  54053. /** defines the target object */
  54054. target,
  54055. /** defines the starting frame number (default is 0) */
  54056. fromFrame,
  54057. /** defines the ending frame number (default is 100) */
  54058. toFrame,
  54059. /** defines if the animation must loop (default is false) */
  54060. loopAnimation, speedRatio,
  54061. /** defines a callback to call when animation ends if it is not looping */
  54062. onAnimationEnd, animations) {
  54063. if (fromFrame === void 0) { fromFrame = 0; }
  54064. if (toFrame === void 0) { toFrame = 100; }
  54065. if (loopAnimation === void 0) { loopAnimation = false; }
  54066. if (speedRatio === void 0) { speedRatio = 1.0; }
  54067. this.target = target;
  54068. this.fromFrame = fromFrame;
  54069. this.toFrame = toFrame;
  54070. this.loopAnimation = loopAnimation;
  54071. this.onAnimationEnd = onAnimationEnd;
  54072. this._localDelayOffset = null;
  54073. this._pausedDelay = null;
  54074. this._runtimeAnimations = new Array();
  54075. this._paused = false;
  54076. this._speedRatio = 1;
  54077. this._weight = -1.0;
  54078. /**
  54079. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  54080. * This will only apply for non looping animation (default is true)
  54081. */
  54082. this.disposeOnEnd = true;
  54083. /**
  54084. * Gets a boolean indicating if the animation has started
  54085. */
  54086. this.animationStarted = false;
  54087. /**
  54088. * Observer raised when the animation ends
  54089. */
  54090. this.onAnimationEndObservable = new BABYLON.Observable();
  54091. this._scene = scene;
  54092. if (animations) {
  54093. this.appendAnimations(target, animations);
  54094. }
  54095. this._speedRatio = speedRatio;
  54096. scene._activeAnimatables.push(this);
  54097. }
  54098. Object.defineProperty(Animatable.prototype, "syncRoot", {
  54099. /**
  54100. * Gets the root Animatable used to synchronize and normalize animations
  54101. */
  54102. get: function () {
  54103. return this._syncRoot;
  54104. },
  54105. enumerable: true,
  54106. configurable: true
  54107. });
  54108. Object.defineProperty(Animatable.prototype, "masterFrame", {
  54109. /**
  54110. * Gets the current frame of the first RuntimeAnimation
  54111. * Used to synchronize Animatables
  54112. */
  54113. get: function () {
  54114. if (this._runtimeAnimations.length === 0) {
  54115. return 0;
  54116. }
  54117. return this._runtimeAnimations[0].currentFrame;
  54118. },
  54119. enumerable: true,
  54120. configurable: true
  54121. });
  54122. Object.defineProperty(Animatable.prototype, "weight", {
  54123. /**
  54124. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  54125. */
  54126. get: function () {
  54127. return this._weight;
  54128. },
  54129. set: function (value) {
  54130. if (value === -1) { // -1 is ok and means no weight
  54131. this._weight = -1;
  54132. return;
  54133. }
  54134. // Else weight must be in [0, 1] range
  54135. this._weight = Math.min(Math.max(value, 0), 1.0);
  54136. },
  54137. enumerable: true,
  54138. configurable: true
  54139. });
  54140. Object.defineProperty(Animatable.prototype, "speedRatio", {
  54141. /**
  54142. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  54143. */
  54144. get: function () {
  54145. return this._speedRatio;
  54146. },
  54147. set: function (value) {
  54148. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  54149. var animation = this._runtimeAnimations[index];
  54150. animation._prepareForSpeedRatioChange(value);
  54151. }
  54152. this._speedRatio = value;
  54153. },
  54154. enumerable: true,
  54155. configurable: true
  54156. });
  54157. // Methods
  54158. /**
  54159. * Synchronize and normalize current Animatable with a source Animatable
  54160. * This is useful when using animation weights and when animations are not of the same length
  54161. * @param root defines the root Animatable to synchronize with
  54162. * @returns the current Animatable
  54163. */
  54164. Animatable.prototype.syncWith = function (root) {
  54165. this._syncRoot = root;
  54166. if (root) {
  54167. // Make sure this animatable will animate after the root
  54168. var index = this._scene._activeAnimatables.indexOf(this);
  54169. if (index > -1) {
  54170. this._scene._activeAnimatables.splice(index, 1);
  54171. this._scene._activeAnimatables.push(this);
  54172. }
  54173. }
  54174. return this;
  54175. };
  54176. /**
  54177. * Gets the list of runtime animations
  54178. * @returns an array of RuntimeAnimation
  54179. */
  54180. Animatable.prototype.getAnimations = function () {
  54181. return this._runtimeAnimations;
  54182. };
  54183. /**
  54184. * Adds more animations to the current animatable
  54185. * @param target defines the target of the animations
  54186. * @param animations defines the new animations to add
  54187. */
  54188. Animatable.prototype.appendAnimations = function (target, animations) {
  54189. for (var index = 0; index < animations.length; index++) {
  54190. var animation = animations[index];
  54191. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  54192. }
  54193. };
  54194. /**
  54195. * Gets the source animation for a specific property
  54196. * @param property defines the propertyu to look for
  54197. * @returns null or the source animation for the given property
  54198. */
  54199. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  54200. var runtimeAnimations = this._runtimeAnimations;
  54201. for (var index = 0; index < runtimeAnimations.length; index++) {
  54202. if (runtimeAnimations[index].animation.targetProperty === property) {
  54203. return runtimeAnimations[index].animation;
  54204. }
  54205. }
  54206. return null;
  54207. };
  54208. /**
  54209. * Gets the runtime animation for a specific property
  54210. * @param property defines the propertyu to look for
  54211. * @returns null or the runtime animation for the given property
  54212. */
  54213. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  54214. var runtimeAnimations = this._runtimeAnimations;
  54215. for (var index = 0; index < runtimeAnimations.length; index++) {
  54216. if (runtimeAnimations[index].animation.targetProperty === property) {
  54217. return runtimeAnimations[index];
  54218. }
  54219. }
  54220. return null;
  54221. };
  54222. /**
  54223. * Resets the animatable to its original state
  54224. */
  54225. Animatable.prototype.reset = function () {
  54226. var runtimeAnimations = this._runtimeAnimations;
  54227. for (var index = 0; index < runtimeAnimations.length; index++) {
  54228. runtimeAnimations[index].reset(true);
  54229. }
  54230. this._localDelayOffset = null;
  54231. this._pausedDelay = null;
  54232. };
  54233. /**
  54234. * Allows the animatable to blend with current running animations
  54235. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54236. * @param blendingSpeed defines the blending speed to use
  54237. */
  54238. Animatable.prototype.enableBlending = function (blendingSpeed) {
  54239. var runtimeAnimations = this._runtimeAnimations;
  54240. for (var index = 0; index < runtimeAnimations.length; index++) {
  54241. runtimeAnimations[index].animation.enableBlending = true;
  54242. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  54243. }
  54244. };
  54245. /**
  54246. * Disable animation blending
  54247. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54248. */
  54249. Animatable.prototype.disableBlending = function () {
  54250. var runtimeAnimations = this._runtimeAnimations;
  54251. for (var index = 0; index < runtimeAnimations.length; index++) {
  54252. runtimeAnimations[index].animation.enableBlending = false;
  54253. }
  54254. };
  54255. /**
  54256. * Jump directly to a given frame
  54257. * @param frame defines the frame to jump to
  54258. */
  54259. Animatable.prototype.goToFrame = function (frame) {
  54260. var runtimeAnimations = this._runtimeAnimations;
  54261. if (runtimeAnimations[0]) {
  54262. var fps = runtimeAnimations[0].animation.framePerSecond;
  54263. var currentFrame = runtimeAnimations[0].currentFrame;
  54264. var adjustTime = frame - currentFrame;
  54265. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  54266. if (this._localDelayOffset === null) {
  54267. this._localDelayOffset = 0;
  54268. }
  54269. this._localDelayOffset -= delay;
  54270. }
  54271. for (var index = 0; index < runtimeAnimations.length; index++) {
  54272. runtimeAnimations[index].goToFrame(frame);
  54273. }
  54274. };
  54275. /**
  54276. * Pause the animation
  54277. */
  54278. Animatable.prototype.pause = function () {
  54279. if (this._paused) {
  54280. return;
  54281. }
  54282. this._paused = true;
  54283. };
  54284. /**
  54285. * Restart the animation
  54286. */
  54287. Animatable.prototype.restart = function () {
  54288. this._paused = false;
  54289. };
  54290. Animatable.prototype._raiseOnAnimationEnd = function () {
  54291. if (this.onAnimationEnd) {
  54292. this.onAnimationEnd();
  54293. }
  54294. this.onAnimationEndObservable.notifyObservers(this);
  54295. };
  54296. /**
  54297. * Stop and delete the current animation
  54298. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  54299. * @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)
  54300. */
  54301. Animatable.prototype.stop = function (animationName, targetMask) {
  54302. if (animationName || targetMask) {
  54303. var idx = this._scene._activeAnimatables.indexOf(this);
  54304. if (idx > -1) {
  54305. var runtimeAnimations = this._runtimeAnimations;
  54306. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  54307. var runtimeAnimation = runtimeAnimations[index];
  54308. if (animationName && runtimeAnimation.animation.name != animationName) {
  54309. continue;
  54310. }
  54311. if (targetMask && !targetMask(runtimeAnimation.target)) {
  54312. continue;
  54313. }
  54314. runtimeAnimation.dispose();
  54315. runtimeAnimations.splice(index, 1);
  54316. }
  54317. if (runtimeAnimations.length == 0) {
  54318. this._scene._activeAnimatables.splice(idx, 1);
  54319. this._raiseOnAnimationEnd();
  54320. }
  54321. }
  54322. }
  54323. else {
  54324. var index = this._scene._activeAnimatables.indexOf(this);
  54325. if (index > -1) {
  54326. this._scene._activeAnimatables.splice(index, 1);
  54327. var runtimeAnimations = this._runtimeAnimations;
  54328. for (var index = 0; index < runtimeAnimations.length; index++) {
  54329. runtimeAnimations[index].dispose();
  54330. }
  54331. this._raiseOnAnimationEnd();
  54332. }
  54333. }
  54334. };
  54335. /**
  54336. * Wait asynchronously for the animation to end
  54337. * @returns a promise which will be fullfilled when the animation ends
  54338. */
  54339. Animatable.prototype.waitAsync = function () {
  54340. var _this = this;
  54341. return new Promise(function (resolve, reject) {
  54342. _this.onAnimationEndObservable.add(function () {
  54343. resolve(_this);
  54344. }, undefined, undefined, _this, true);
  54345. });
  54346. };
  54347. /** @hidden */
  54348. Animatable.prototype._animate = function (delay) {
  54349. if (this._paused) {
  54350. this.animationStarted = false;
  54351. if (this._pausedDelay === null) {
  54352. this._pausedDelay = delay;
  54353. }
  54354. return true;
  54355. }
  54356. if (this._localDelayOffset === null) {
  54357. this._localDelayOffset = delay;
  54358. this._pausedDelay = null;
  54359. }
  54360. else if (this._pausedDelay !== null) {
  54361. this._localDelayOffset += delay - this._pausedDelay;
  54362. this._pausedDelay = null;
  54363. }
  54364. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  54365. return true;
  54366. }
  54367. // Animating
  54368. var running = false;
  54369. var runtimeAnimations = this._runtimeAnimations;
  54370. var index;
  54371. for (index = 0; index < runtimeAnimations.length; index++) {
  54372. var animation = runtimeAnimations[index];
  54373. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  54374. running = running || isRunning;
  54375. }
  54376. this.animationStarted = running;
  54377. if (!running) {
  54378. if (this.disposeOnEnd) {
  54379. // Remove from active animatables
  54380. index = this._scene._activeAnimatables.indexOf(this);
  54381. this._scene._activeAnimatables.splice(index, 1);
  54382. // Dispose all runtime animations
  54383. for (index = 0; index < runtimeAnimations.length; index++) {
  54384. runtimeAnimations[index].dispose();
  54385. }
  54386. }
  54387. this._raiseOnAnimationEnd();
  54388. if (this.disposeOnEnd) {
  54389. this.onAnimationEnd = null;
  54390. this.onAnimationEndObservable.clear();
  54391. }
  54392. }
  54393. return running;
  54394. };
  54395. return Animatable;
  54396. }());
  54397. BABYLON.Animatable = Animatable;
  54398. })(BABYLON || (BABYLON = {}));
  54399. //# sourceMappingURL=babylon.animatable.js.map
  54400. var BABYLON;
  54401. (function (BABYLON) {
  54402. /**
  54403. * Base class used for every default easing function.
  54404. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54405. */
  54406. var EasingFunction = /** @class */ (function () {
  54407. function EasingFunction() {
  54408. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  54409. }
  54410. /**
  54411. * Sets the easing mode of the current function.
  54412. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  54413. */
  54414. EasingFunction.prototype.setEasingMode = function (easingMode) {
  54415. var n = Math.min(Math.max(easingMode, 0), 2);
  54416. this._easingMode = n;
  54417. };
  54418. /**
  54419. * Gets the current easing mode.
  54420. * @returns the easing mode
  54421. */
  54422. EasingFunction.prototype.getEasingMode = function () {
  54423. return this._easingMode;
  54424. };
  54425. /**
  54426. * @hidden
  54427. */
  54428. EasingFunction.prototype.easeInCore = function (gradient) {
  54429. throw new Error('You must implement this method');
  54430. };
  54431. /**
  54432. * Given an input gradient between 0 and 1, this returns the corrseponding value
  54433. * of the easing function.
  54434. * @param gradient Defines the value between 0 and 1 we want the easing value for
  54435. * @returns the corresponding value on the curve defined by the easing function
  54436. */
  54437. EasingFunction.prototype.ease = function (gradient) {
  54438. switch (this._easingMode) {
  54439. case EasingFunction.EASINGMODE_EASEIN:
  54440. return this.easeInCore(gradient);
  54441. case EasingFunction.EASINGMODE_EASEOUT:
  54442. return (1 - this.easeInCore(1 - gradient));
  54443. }
  54444. if (gradient >= 0.5) {
  54445. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  54446. }
  54447. return (this.easeInCore(gradient * 2) * 0.5);
  54448. };
  54449. /**
  54450. * Interpolation follows the mathematical formula associated with the easing function.
  54451. */
  54452. EasingFunction.EASINGMODE_EASEIN = 0;
  54453. /**
  54454. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  54455. */
  54456. EasingFunction.EASINGMODE_EASEOUT = 1;
  54457. /**
  54458. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  54459. */
  54460. EasingFunction.EASINGMODE_EASEINOUT = 2;
  54461. return EasingFunction;
  54462. }());
  54463. BABYLON.EasingFunction = EasingFunction;
  54464. /**
  54465. * Easing function with a circle shape (see link below).
  54466. * @see https://easings.net/#easeInCirc
  54467. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54468. */
  54469. var CircleEase = /** @class */ (function (_super) {
  54470. __extends(CircleEase, _super);
  54471. function CircleEase() {
  54472. return _super !== null && _super.apply(this, arguments) || this;
  54473. }
  54474. /** @hidden */
  54475. CircleEase.prototype.easeInCore = function (gradient) {
  54476. gradient = Math.max(0, Math.min(1, gradient));
  54477. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  54478. };
  54479. return CircleEase;
  54480. }(EasingFunction));
  54481. BABYLON.CircleEase = CircleEase;
  54482. /**
  54483. * Easing function with a ease back shape (see link below).
  54484. * @see https://easings.net/#easeInBack
  54485. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54486. */
  54487. var BackEase = /** @class */ (function (_super) {
  54488. __extends(BackEase, _super);
  54489. /**
  54490. * Instantiates a back ease easing
  54491. * @see https://easings.net/#easeInBack
  54492. * @param amplitude Defines the amplitude of the function
  54493. */
  54494. function BackEase(
  54495. /** Defines the amplitude of the function */
  54496. amplitude) {
  54497. if (amplitude === void 0) { amplitude = 1; }
  54498. var _this = _super.call(this) || this;
  54499. _this.amplitude = amplitude;
  54500. return _this;
  54501. }
  54502. /** @hidden */
  54503. BackEase.prototype.easeInCore = function (gradient) {
  54504. var num = Math.max(0, this.amplitude);
  54505. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  54506. };
  54507. return BackEase;
  54508. }(EasingFunction));
  54509. BABYLON.BackEase = BackEase;
  54510. /**
  54511. * Easing function with a bouncing shape (see link below).
  54512. * @see https://easings.net/#easeInBounce
  54513. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54514. */
  54515. var BounceEase = /** @class */ (function (_super) {
  54516. __extends(BounceEase, _super);
  54517. /**
  54518. * Instantiates a bounce easing
  54519. * @see https://easings.net/#easeInBounce
  54520. * @param bounces Defines the number of bounces
  54521. * @param bounciness Defines the amplitude of the bounce
  54522. */
  54523. function BounceEase(
  54524. /** Defines the number of bounces */
  54525. bounces,
  54526. /** Defines the amplitude of the bounce */
  54527. bounciness) {
  54528. if (bounces === void 0) { bounces = 3; }
  54529. if (bounciness === void 0) { bounciness = 2; }
  54530. var _this = _super.call(this) || this;
  54531. _this.bounces = bounces;
  54532. _this.bounciness = bounciness;
  54533. return _this;
  54534. }
  54535. /** @hidden */
  54536. BounceEase.prototype.easeInCore = function (gradient) {
  54537. var y = Math.max(0.0, this.bounces);
  54538. var bounciness = this.bounciness;
  54539. if (bounciness <= 1.0) {
  54540. bounciness = 1.001;
  54541. }
  54542. var num9 = Math.pow(bounciness, y);
  54543. var num5 = 1.0 - bounciness;
  54544. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  54545. var num15 = gradient * num4;
  54546. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  54547. var num3 = Math.floor(num65);
  54548. var num13 = num3 + 1.0;
  54549. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  54550. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  54551. var num7 = (num8 + num12) * 0.5;
  54552. var num6 = gradient - num7;
  54553. var num2 = num7 - num8;
  54554. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  54555. };
  54556. return BounceEase;
  54557. }(EasingFunction));
  54558. BABYLON.BounceEase = BounceEase;
  54559. /**
  54560. * Easing function with a power of 3 shape (see link below).
  54561. * @see https://easings.net/#easeInCubic
  54562. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54563. */
  54564. var CubicEase = /** @class */ (function (_super) {
  54565. __extends(CubicEase, _super);
  54566. function CubicEase() {
  54567. return _super !== null && _super.apply(this, arguments) || this;
  54568. }
  54569. /** @hidden */
  54570. CubicEase.prototype.easeInCore = function (gradient) {
  54571. return (gradient * gradient * gradient);
  54572. };
  54573. return CubicEase;
  54574. }(EasingFunction));
  54575. BABYLON.CubicEase = CubicEase;
  54576. /**
  54577. * Easing function with an elastic shape (see link below).
  54578. * @see https://easings.net/#easeInElastic
  54579. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54580. */
  54581. var ElasticEase = /** @class */ (function (_super) {
  54582. __extends(ElasticEase, _super);
  54583. /**
  54584. * Instantiates an elastic easing function
  54585. * @see https://easings.net/#easeInElastic
  54586. * @param oscillations Defines the number of oscillations
  54587. * @param springiness Defines the amplitude of the oscillations
  54588. */
  54589. function ElasticEase(
  54590. /** Defines the number of oscillations*/
  54591. oscillations,
  54592. /** Defines the amplitude of the oscillations*/
  54593. springiness) {
  54594. if (oscillations === void 0) { oscillations = 3; }
  54595. if (springiness === void 0) { springiness = 3; }
  54596. var _this = _super.call(this) || this;
  54597. _this.oscillations = oscillations;
  54598. _this.springiness = springiness;
  54599. return _this;
  54600. }
  54601. /** @hidden */
  54602. ElasticEase.prototype.easeInCore = function (gradient) {
  54603. var num2;
  54604. var num3 = Math.max(0.0, this.oscillations);
  54605. var num = Math.max(0.0, this.springiness);
  54606. if (num == 0) {
  54607. num2 = gradient;
  54608. }
  54609. else {
  54610. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  54611. }
  54612. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  54613. };
  54614. return ElasticEase;
  54615. }(EasingFunction));
  54616. BABYLON.ElasticEase = ElasticEase;
  54617. /**
  54618. * Easing function with an exponential shape (see link below).
  54619. * @see https://easings.net/#easeInExpo
  54620. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54621. */
  54622. var ExponentialEase = /** @class */ (function (_super) {
  54623. __extends(ExponentialEase, _super);
  54624. /**
  54625. * Instantiates an exponential easing function
  54626. * @see https://easings.net/#easeInExpo
  54627. * @param exponent Defines the exponent of the function
  54628. */
  54629. function ExponentialEase(
  54630. /** Defines the exponent of the function */
  54631. exponent) {
  54632. if (exponent === void 0) { exponent = 2; }
  54633. var _this = _super.call(this) || this;
  54634. _this.exponent = exponent;
  54635. return _this;
  54636. }
  54637. /** @hidden */
  54638. ExponentialEase.prototype.easeInCore = function (gradient) {
  54639. if (this.exponent <= 0) {
  54640. return gradient;
  54641. }
  54642. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54643. };
  54644. return ExponentialEase;
  54645. }(EasingFunction));
  54646. BABYLON.ExponentialEase = ExponentialEase;
  54647. /**
  54648. * Easing function with a power shape (see link below).
  54649. * @see https://easings.net/#easeInQuad
  54650. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54651. */
  54652. var PowerEase = /** @class */ (function (_super) {
  54653. __extends(PowerEase, _super);
  54654. /**
  54655. * Instantiates an power base easing function
  54656. * @see https://easings.net/#easeInQuad
  54657. * @param power Defines the power of the function
  54658. */
  54659. function PowerEase(
  54660. /** Defines the power of the function */
  54661. power) {
  54662. if (power === void 0) { power = 2; }
  54663. var _this = _super.call(this) || this;
  54664. _this.power = power;
  54665. return _this;
  54666. }
  54667. /** @hidden */
  54668. PowerEase.prototype.easeInCore = function (gradient) {
  54669. var y = Math.max(0.0, this.power);
  54670. return Math.pow(gradient, y);
  54671. };
  54672. return PowerEase;
  54673. }(EasingFunction));
  54674. BABYLON.PowerEase = PowerEase;
  54675. /**
  54676. * Easing function with a power of 2 shape (see link below).
  54677. * @see https://easings.net/#easeInQuad
  54678. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54679. */
  54680. var QuadraticEase = /** @class */ (function (_super) {
  54681. __extends(QuadraticEase, _super);
  54682. function QuadraticEase() {
  54683. return _super !== null && _super.apply(this, arguments) || this;
  54684. }
  54685. /** @hidden */
  54686. QuadraticEase.prototype.easeInCore = function (gradient) {
  54687. return (gradient * gradient);
  54688. };
  54689. return QuadraticEase;
  54690. }(EasingFunction));
  54691. BABYLON.QuadraticEase = QuadraticEase;
  54692. /**
  54693. * Easing function with a power of 4 shape (see link below).
  54694. * @see https://easings.net/#easeInQuart
  54695. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54696. */
  54697. var QuarticEase = /** @class */ (function (_super) {
  54698. __extends(QuarticEase, _super);
  54699. function QuarticEase() {
  54700. return _super !== null && _super.apply(this, arguments) || this;
  54701. }
  54702. /** @hidden */
  54703. QuarticEase.prototype.easeInCore = function (gradient) {
  54704. return (gradient * gradient * gradient * gradient);
  54705. };
  54706. return QuarticEase;
  54707. }(EasingFunction));
  54708. BABYLON.QuarticEase = QuarticEase;
  54709. /**
  54710. * Easing function with a power of 5 shape (see link below).
  54711. * @see https://easings.net/#easeInQuint
  54712. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54713. */
  54714. var QuinticEase = /** @class */ (function (_super) {
  54715. __extends(QuinticEase, _super);
  54716. function QuinticEase() {
  54717. return _super !== null && _super.apply(this, arguments) || this;
  54718. }
  54719. /** @hidden */
  54720. QuinticEase.prototype.easeInCore = function (gradient) {
  54721. return (gradient * gradient * gradient * gradient * gradient);
  54722. };
  54723. return QuinticEase;
  54724. }(EasingFunction));
  54725. BABYLON.QuinticEase = QuinticEase;
  54726. /**
  54727. * Easing function with a sin shape (see link below).
  54728. * @see https://easings.net/#easeInSine
  54729. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54730. */
  54731. var SineEase = /** @class */ (function (_super) {
  54732. __extends(SineEase, _super);
  54733. function SineEase() {
  54734. return _super !== null && _super.apply(this, arguments) || this;
  54735. }
  54736. /** @hidden */
  54737. SineEase.prototype.easeInCore = function (gradient) {
  54738. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54739. };
  54740. return SineEase;
  54741. }(EasingFunction));
  54742. BABYLON.SineEase = SineEase;
  54743. /**
  54744. * Easing function with a bezier shape (see link below).
  54745. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54746. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54747. */
  54748. var BezierCurveEase = /** @class */ (function (_super) {
  54749. __extends(BezierCurveEase, _super);
  54750. /**
  54751. * Instantiates a bezier function
  54752. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54753. * @param x1 Defines the x component of the start tangent in the bezier curve
  54754. * @param y1 Defines the y component of the start tangent in the bezier curve
  54755. * @param x2 Defines the x component of the end tangent in the bezier curve
  54756. * @param y2 Defines the y component of the end tangent in the bezier curve
  54757. */
  54758. function BezierCurveEase(
  54759. /** Defines the x component of the start tangent in the bezier curve */
  54760. x1,
  54761. /** Defines the y component of the start tangent in the bezier curve */
  54762. y1,
  54763. /** Defines the x component of the end tangent in the bezier curve */
  54764. x2,
  54765. /** Defines the y component of the end tangent in the bezier curve */
  54766. y2) {
  54767. if (x1 === void 0) { x1 = 0; }
  54768. if (y1 === void 0) { y1 = 0; }
  54769. if (x2 === void 0) { x2 = 1; }
  54770. if (y2 === void 0) { y2 = 1; }
  54771. var _this = _super.call(this) || this;
  54772. _this.x1 = x1;
  54773. _this.y1 = y1;
  54774. _this.x2 = x2;
  54775. _this.y2 = y2;
  54776. return _this;
  54777. }
  54778. /** @hidden */
  54779. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54780. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54781. };
  54782. return BezierCurveEase;
  54783. }(EasingFunction));
  54784. BABYLON.BezierCurveEase = BezierCurveEase;
  54785. })(BABYLON || (BABYLON = {}));
  54786. //# sourceMappingURL=babylon.easing.js.map
  54787. var BABYLON;
  54788. (function (BABYLON) {
  54789. /**
  54790. * A Condition applied to an Action
  54791. */
  54792. var Condition = /** @class */ (function () {
  54793. /**
  54794. * Creates a new Condition
  54795. * @param actionManager the manager of the action the condition is applied to
  54796. */
  54797. function Condition(actionManager) {
  54798. this._actionManager = actionManager;
  54799. }
  54800. /**
  54801. * Check if the current condition is valid
  54802. * @returns a boolean
  54803. */
  54804. Condition.prototype.isValid = function () {
  54805. return true;
  54806. };
  54807. /**
  54808. * Internal only
  54809. * @hidden
  54810. */
  54811. Condition.prototype._getProperty = function (propertyPath) {
  54812. return this._actionManager._getProperty(propertyPath);
  54813. };
  54814. /**
  54815. * Internal only
  54816. * @hidden
  54817. */
  54818. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54819. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54820. };
  54821. /**
  54822. * Serialize placeholder for child classes
  54823. * @returns the serialized object
  54824. */
  54825. Condition.prototype.serialize = function () {
  54826. };
  54827. /**
  54828. * Internal only
  54829. * @hidden
  54830. */
  54831. Condition.prototype._serialize = function (serializedCondition) {
  54832. return {
  54833. type: 2,
  54834. children: [],
  54835. name: serializedCondition.name,
  54836. properties: serializedCondition.properties
  54837. };
  54838. };
  54839. return Condition;
  54840. }());
  54841. BABYLON.Condition = Condition;
  54842. /**
  54843. * Defines specific conditional operators as extensions of Condition
  54844. */
  54845. var ValueCondition = /** @class */ (function (_super) {
  54846. __extends(ValueCondition, _super);
  54847. /**
  54848. * Creates a new ValueCondition
  54849. * @param actionManager manager for the action the condition applies to
  54850. * @param target for the action
  54851. * @param propertyPath path to specify the property of the target the conditional operator uses
  54852. * @param value the value compared by the conditional operator against the current value of the property
  54853. * @param operator the conditional operator, default ValueCondition.IsEqual
  54854. */
  54855. function ValueCondition(actionManager, target,
  54856. /** path to specify the property of the target the conditional operator uses */
  54857. propertyPath,
  54858. /** the value compared by the conditional operator against the current value of the property */
  54859. value,
  54860. /** the conditional operator, default ValueCondition.IsEqual */
  54861. operator) {
  54862. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54863. var _this = _super.call(this, actionManager) || this;
  54864. _this.propertyPath = propertyPath;
  54865. _this.value = value;
  54866. _this.operator = operator;
  54867. _this._target = target;
  54868. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54869. _this._property = _this._getProperty(_this.propertyPath);
  54870. return _this;
  54871. }
  54872. Object.defineProperty(ValueCondition, "IsEqual", {
  54873. /**
  54874. * returns the number for IsEqual
  54875. */
  54876. get: function () {
  54877. return ValueCondition._IsEqual;
  54878. },
  54879. enumerable: true,
  54880. configurable: true
  54881. });
  54882. Object.defineProperty(ValueCondition, "IsDifferent", {
  54883. /**
  54884. * Returns the number for IsDifferent
  54885. */
  54886. get: function () {
  54887. return ValueCondition._IsDifferent;
  54888. },
  54889. enumerable: true,
  54890. configurable: true
  54891. });
  54892. Object.defineProperty(ValueCondition, "IsGreater", {
  54893. /**
  54894. * Returns the number for IsGreater
  54895. */
  54896. get: function () {
  54897. return ValueCondition._IsGreater;
  54898. },
  54899. enumerable: true,
  54900. configurable: true
  54901. });
  54902. Object.defineProperty(ValueCondition, "IsLesser", {
  54903. /**
  54904. * Returns the number for IsLesser
  54905. */
  54906. get: function () {
  54907. return ValueCondition._IsLesser;
  54908. },
  54909. enumerable: true,
  54910. configurable: true
  54911. });
  54912. /**
  54913. * Compares the given value with the property value for the specified conditional operator
  54914. * @returns the result of the comparison
  54915. */
  54916. ValueCondition.prototype.isValid = function () {
  54917. switch (this.operator) {
  54918. case ValueCondition.IsGreater:
  54919. return this._effectiveTarget[this._property] > this.value;
  54920. case ValueCondition.IsLesser:
  54921. return this._effectiveTarget[this._property] < this.value;
  54922. case ValueCondition.IsEqual:
  54923. case ValueCondition.IsDifferent:
  54924. var check;
  54925. if (this.value.equals) {
  54926. check = this.value.equals(this._effectiveTarget[this._property]);
  54927. }
  54928. else {
  54929. check = this.value === this._effectiveTarget[this._property];
  54930. }
  54931. return this.operator === ValueCondition.IsEqual ? check : !check;
  54932. }
  54933. return false;
  54934. };
  54935. /**
  54936. * Serialize the ValueCondition into a JSON compatible object
  54937. * @returns serialization object
  54938. */
  54939. ValueCondition.prototype.serialize = function () {
  54940. return this._serialize({
  54941. name: "ValueCondition",
  54942. properties: [
  54943. BABYLON.Action._GetTargetProperty(this._target),
  54944. { name: "propertyPath", value: this.propertyPath },
  54945. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54946. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54947. ]
  54948. });
  54949. };
  54950. /**
  54951. * Gets the name of the conditional operator for the ValueCondition
  54952. * @param operator the conditional operator
  54953. * @returns the name
  54954. */
  54955. ValueCondition.GetOperatorName = function (operator) {
  54956. switch (operator) {
  54957. case ValueCondition._IsEqual: return "IsEqual";
  54958. case ValueCondition._IsDifferent: return "IsDifferent";
  54959. case ValueCondition._IsGreater: return "IsGreater";
  54960. case ValueCondition._IsLesser: return "IsLesser";
  54961. default: return "";
  54962. }
  54963. };
  54964. /**
  54965. * Internal only
  54966. * @hidden
  54967. */
  54968. ValueCondition._IsEqual = 0;
  54969. /**
  54970. * Internal only
  54971. * @hidden
  54972. */
  54973. ValueCondition._IsDifferent = 1;
  54974. /**
  54975. * Internal only
  54976. * @hidden
  54977. */
  54978. ValueCondition._IsGreater = 2;
  54979. /**
  54980. * Internal only
  54981. * @hidden
  54982. */
  54983. ValueCondition._IsLesser = 3;
  54984. return ValueCondition;
  54985. }(Condition));
  54986. BABYLON.ValueCondition = ValueCondition;
  54987. /**
  54988. * Defines a predicate condition as an extension of Condition
  54989. */
  54990. var PredicateCondition = /** @class */ (function (_super) {
  54991. __extends(PredicateCondition, _super);
  54992. /**
  54993. * Creates a new PredicateCondition
  54994. * @param actionManager manager for the action the condition applies to
  54995. * @param predicate defines the predicate function used to validate the condition
  54996. */
  54997. function PredicateCondition(actionManager,
  54998. /** defines the predicate function used to validate the condition */
  54999. predicate) {
  55000. var _this = _super.call(this, actionManager) || this;
  55001. _this.predicate = predicate;
  55002. return _this;
  55003. }
  55004. /**
  55005. * @returns the validity of the predicate condition
  55006. */
  55007. PredicateCondition.prototype.isValid = function () {
  55008. return this.predicate();
  55009. };
  55010. return PredicateCondition;
  55011. }(Condition));
  55012. BABYLON.PredicateCondition = PredicateCondition;
  55013. /**
  55014. * Defines a state condition as an extension of Condition
  55015. */
  55016. var StateCondition = /** @class */ (function (_super) {
  55017. __extends(StateCondition, _super);
  55018. /**
  55019. * Creates a new StateCondition
  55020. * @param actionManager manager for the action the condition applies to
  55021. * @param target of the condition
  55022. * @param value to compare with target state
  55023. */
  55024. function StateCondition(actionManager, target,
  55025. /** Value to compare with target state */
  55026. value) {
  55027. var _this = _super.call(this, actionManager) || this;
  55028. _this.value = value;
  55029. _this._target = target;
  55030. return _this;
  55031. }
  55032. /**
  55033. * Gets a boolean indicating if the current condition is met
  55034. * @returns the validity of the state
  55035. */
  55036. StateCondition.prototype.isValid = function () {
  55037. return this._target.state === this.value;
  55038. };
  55039. /**
  55040. * Serialize the StateCondition into a JSON compatible object
  55041. * @returns serialization object
  55042. */
  55043. StateCondition.prototype.serialize = function () {
  55044. return this._serialize({
  55045. name: "StateCondition",
  55046. properties: [
  55047. BABYLON.Action._GetTargetProperty(this._target),
  55048. { name: "value", value: this.value }
  55049. ]
  55050. });
  55051. };
  55052. return StateCondition;
  55053. }(Condition));
  55054. BABYLON.StateCondition = StateCondition;
  55055. })(BABYLON || (BABYLON = {}));
  55056. //# sourceMappingURL=babylon.condition.js.map
  55057. var BABYLON;
  55058. (function (BABYLON) {
  55059. /**
  55060. * The action to be carried out following a trigger
  55061. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  55062. */
  55063. var Action = /** @class */ (function () {
  55064. /**
  55065. * Creates a new Action
  55066. * @param triggerOptions the trigger, with or without parameters, for the action
  55067. * @param condition an optional determinant of action
  55068. */
  55069. function Action(
  55070. /** the trigger, with or without parameters, for the action */
  55071. triggerOptions, condition) {
  55072. this.triggerOptions = triggerOptions;
  55073. /**
  55074. * An event triggered prior to action being executed.
  55075. */
  55076. this.onBeforeExecuteObservable = new BABYLON.Observable();
  55077. if (triggerOptions.parameter) {
  55078. this.trigger = triggerOptions.trigger;
  55079. this._triggerParameter = triggerOptions.parameter;
  55080. }
  55081. else if (triggerOptions.trigger) {
  55082. this.trigger = triggerOptions.trigger;
  55083. }
  55084. else {
  55085. this.trigger = triggerOptions;
  55086. }
  55087. this._nextActiveAction = this;
  55088. this._condition = condition;
  55089. }
  55090. /**
  55091. * Internal only
  55092. * @hidden
  55093. */
  55094. Action.prototype._prepare = function () {
  55095. };
  55096. /**
  55097. * Gets the trigger parameters
  55098. * @returns the trigger parameters
  55099. */
  55100. Action.prototype.getTriggerParameter = function () {
  55101. return this._triggerParameter;
  55102. };
  55103. /**
  55104. * Internal only - executes current action event
  55105. * @hidden
  55106. */
  55107. Action.prototype._executeCurrent = function (evt) {
  55108. if (this._nextActiveAction._condition) {
  55109. var condition = this._nextActiveAction._condition;
  55110. var currentRenderId = this._actionManager.getScene().getRenderId();
  55111. // We cache the current evaluation for the current frame
  55112. if (condition._evaluationId === currentRenderId) {
  55113. if (!condition._currentResult) {
  55114. return;
  55115. }
  55116. }
  55117. else {
  55118. condition._evaluationId = currentRenderId;
  55119. if (!condition.isValid()) {
  55120. condition._currentResult = false;
  55121. return;
  55122. }
  55123. condition._currentResult = true;
  55124. }
  55125. }
  55126. this.onBeforeExecuteObservable.notifyObservers(this);
  55127. this._nextActiveAction.execute(evt);
  55128. this.skipToNextActiveAction();
  55129. };
  55130. /**
  55131. * Execute placeholder for child classes
  55132. * @param evt optional action event
  55133. */
  55134. Action.prototype.execute = function (evt) {
  55135. };
  55136. /**
  55137. * Skips to next active action
  55138. */
  55139. Action.prototype.skipToNextActiveAction = function () {
  55140. if (this._nextActiveAction._child) {
  55141. if (!this._nextActiveAction._child._actionManager) {
  55142. this._nextActiveAction._child._actionManager = this._actionManager;
  55143. }
  55144. this._nextActiveAction = this._nextActiveAction._child;
  55145. }
  55146. else {
  55147. this._nextActiveAction = this;
  55148. }
  55149. };
  55150. /**
  55151. * Adds action to chain of actions, may be a DoNothingAction
  55152. * @param action defines the next action to execute
  55153. * @returns The action passed in
  55154. * @see https://www.babylonjs-playground.com/#1T30HR#0
  55155. */
  55156. Action.prototype.then = function (action) {
  55157. this._child = action;
  55158. action._actionManager = this._actionManager;
  55159. action._prepare();
  55160. return action;
  55161. };
  55162. /**
  55163. * Internal only
  55164. * @hidden
  55165. */
  55166. Action.prototype._getProperty = function (propertyPath) {
  55167. return this._actionManager._getProperty(propertyPath);
  55168. };
  55169. /**
  55170. * Internal only
  55171. * @hidden
  55172. */
  55173. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  55174. return this._actionManager._getEffectiveTarget(target, propertyPath);
  55175. };
  55176. /**
  55177. * Serialize placeholder for child classes
  55178. * @param parent of child
  55179. * @returns the serialized object
  55180. */
  55181. Action.prototype.serialize = function (parent) {
  55182. };
  55183. /**
  55184. * Internal only called by serialize
  55185. * @hidden
  55186. */
  55187. Action.prototype._serialize = function (serializedAction, parent) {
  55188. var serializationObject = {
  55189. type: 1,
  55190. children: [],
  55191. name: serializedAction.name,
  55192. properties: serializedAction.properties || []
  55193. };
  55194. // Serialize child
  55195. if (this._child) {
  55196. this._child.serialize(serializationObject);
  55197. }
  55198. // Check if "this" has a condition
  55199. if (this._condition) {
  55200. var serializedCondition = this._condition.serialize();
  55201. serializedCondition.children.push(serializationObject);
  55202. if (parent) {
  55203. parent.children.push(serializedCondition);
  55204. }
  55205. return serializedCondition;
  55206. }
  55207. if (parent) {
  55208. parent.children.push(serializationObject);
  55209. }
  55210. return serializationObject;
  55211. };
  55212. /**
  55213. * Internal only
  55214. * @hidden
  55215. */
  55216. Action._SerializeValueAsString = function (value) {
  55217. if (typeof value === "number") {
  55218. return value.toString();
  55219. }
  55220. if (typeof value === "boolean") {
  55221. return value ? "true" : "false";
  55222. }
  55223. if (value instanceof BABYLON.Vector2) {
  55224. return value.x + ", " + value.y;
  55225. }
  55226. if (value instanceof BABYLON.Vector3) {
  55227. return value.x + ", " + value.y + ", " + value.z;
  55228. }
  55229. if (value instanceof BABYLON.Color3) {
  55230. return value.r + ", " + value.g + ", " + value.b;
  55231. }
  55232. if (value instanceof BABYLON.Color4) {
  55233. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  55234. }
  55235. return value; // string
  55236. };
  55237. /**
  55238. * Internal only
  55239. * @hidden
  55240. */
  55241. Action._GetTargetProperty = function (target) {
  55242. return {
  55243. name: "target",
  55244. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  55245. : target instanceof BABYLON.Light ? "LightProperties"
  55246. : target instanceof BABYLON.Camera ? "CameraProperties"
  55247. : "SceneProperties",
  55248. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  55249. };
  55250. };
  55251. return Action;
  55252. }());
  55253. BABYLON.Action = Action;
  55254. })(BABYLON || (BABYLON = {}));
  55255. //# sourceMappingURL=babylon.action.js.map
  55256. var BABYLON;
  55257. (function (BABYLON) {
  55258. /**
  55259. * ActionEvent is the event being sent when an action is triggered.
  55260. */
  55261. var ActionEvent = /** @class */ (function () {
  55262. /**
  55263. * Creates a new ActionEvent
  55264. * @param source The mesh or sprite that triggered the action
  55265. * @param pointerX The X mouse cursor position at the time of the event
  55266. * @param pointerY The Y mouse cursor position at the time of the event
  55267. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  55268. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  55269. * @param additionalData additional data for the event
  55270. */
  55271. function ActionEvent(
  55272. /** The mesh or sprite that triggered the action */
  55273. source,
  55274. /** The X mouse cursor position at the time of the event */
  55275. pointerX,
  55276. /** The Y mouse cursor position at the time of the event */
  55277. pointerY,
  55278. /** The mesh that is currently pointed at (can be null) */
  55279. meshUnderPointer,
  55280. /** the original (browser) event that triggered the ActionEvent */
  55281. sourceEvent,
  55282. /** additional data for the event */
  55283. additionalData) {
  55284. this.source = source;
  55285. this.pointerX = pointerX;
  55286. this.pointerY = pointerY;
  55287. this.meshUnderPointer = meshUnderPointer;
  55288. this.sourceEvent = sourceEvent;
  55289. this.additionalData = additionalData;
  55290. }
  55291. /**
  55292. * Helper function to auto-create an ActionEvent from a source mesh.
  55293. * @param source The source mesh that triggered the event
  55294. * @param evt The original (browser) event
  55295. * @param additionalData additional data for the event
  55296. * @returns the new ActionEvent
  55297. */
  55298. ActionEvent.CreateNew = function (source, evt, additionalData) {
  55299. var scene = source.getScene();
  55300. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55301. };
  55302. /**
  55303. * Helper function to auto-create an ActionEvent from a source sprite
  55304. * @param source The source sprite that triggered the event
  55305. * @param scene Scene associated with the sprite
  55306. * @param evt The original (browser) event
  55307. * @param additionalData additional data for the event
  55308. * @returns the new ActionEvent
  55309. */
  55310. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  55311. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55312. };
  55313. /**
  55314. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  55315. * @param scene the scene where the event occurred
  55316. * @param evt The original (browser) event
  55317. * @returns the new ActionEvent
  55318. */
  55319. ActionEvent.CreateNewFromScene = function (scene, evt) {
  55320. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  55321. };
  55322. /**
  55323. * Helper function to auto-create an ActionEvent from a primitive
  55324. * @param prim defines the target primitive
  55325. * @param pointerPos defines the pointer position
  55326. * @param evt The original (browser) event
  55327. * @param additionalData additional data for the event
  55328. * @returns the new ActionEvent
  55329. */
  55330. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  55331. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  55332. };
  55333. return ActionEvent;
  55334. }());
  55335. BABYLON.ActionEvent = ActionEvent;
  55336. /**
  55337. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  55338. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  55339. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55340. */
  55341. var ActionManager = /** @class */ (function () {
  55342. /**
  55343. * Creates a new action manager
  55344. * @param scene defines the hosting scene
  55345. */
  55346. function ActionManager(scene) {
  55347. // Members
  55348. /** Gets the list of actions */
  55349. this.actions = new Array();
  55350. /** Gets the cursor to use when hovering items */
  55351. this.hoverCursor = '';
  55352. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55353. scene.actionManagers.push(this);
  55354. }
  55355. // Methods
  55356. /**
  55357. * Releases all associated resources
  55358. */
  55359. ActionManager.prototype.dispose = function () {
  55360. var index = this._scene.actionManagers.indexOf(this);
  55361. for (var i = 0; i < this.actions.length; i++) {
  55362. var action = this.actions[i];
  55363. ActionManager.Triggers[action.trigger]--;
  55364. if (ActionManager.Triggers[action.trigger] === 0) {
  55365. delete ActionManager.Triggers[action.trigger];
  55366. }
  55367. }
  55368. if (index > -1) {
  55369. this._scene.actionManagers.splice(index, 1);
  55370. }
  55371. };
  55372. /**
  55373. * Gets hosting scene
  55374. * @returns the hosting scene
  55375. */
  55376. ActionManager.prototype.getScene = function () {
  55377. return this._scene;
  55378. };
  55379. /**
  55380. * Does this action manager handles actions of any of the given triggers
  55381. * @param triggers defines the triggers to be tested
  55382. * @return a boolean indicating whether one (or more) of the triggers is handled
  55383. */
  55384. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  55385. for (var index = 0; index < this.actions.length; index++) {
  55386. var action = this.actions[index];
  55387. if (triggers.indexOf(action.trigger) > -1) {
  55388. return true;
  55389. }
  55390. }
  55391. return false;
  55392. };
  55393. /**
  55394. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  55395. * speed.
  55396. * @param triggerA defines the trigger to be tested
  55397. * @param triggerB defines the trigger to be tested
  55398. * @return a boolean indicating whether one (or more) of the triggers is handled
  55399. */
  55400. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  55401. for (var index = 0; index < this.actions.length; index++) {
  55402. var action = this.actions[index];
  55403. if (triggerA == action.trigger || triggerB == action.trigger) {
  55404. return true;
  55405. }
  55406. }
  55407. return false;
  55408. };
  55409. /**
  55410. * Does this action manager handles actions of a given trigger
  55411. * @param trigger defines the trigger to be tested
  55412. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  55413. * @return whether the trigger is handled
  55414. */
  55415. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  55416. for (var index = 0; index < this.actions.length; index++) {
  55417. var action = this.actions[index];
  55418. if (action.trigger === trigger) {
  55419. if (parameterPredicate) {
  55420. if (parameterPredicate(action.getTriggerParameter())) {
  55421. return true;
  55422. }
  55423. }
  55424. else {
  55425. return true;
  55426. }
  55427. }
  55428. }
  55429. return false;
  55430. };
  55431. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  55432. /**
  55433. * Does this action manager has pointer triggers
  55434. */
  55435. get: function () {
  55436. for (var index = 0; index < this.actions.length; index++) {
  55437. var action = this.actions[index];
  55438. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  55439. return true;
  55440. }
  55441. }
  55442. return false;
  55443. },
  55444. enumerable: true,
  55445. configurable: true
  55446. });
  55447. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  55448. /**
  55449. * Does this action manager has pick triggers
  55450. */
  55451. get: function () {
  55452. for (var index = 0; index < this.actions.length; index++) {
  55453. var action = this.actions[index];
  55454. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  55455. return true;
  55456. }
  55457. }
  55458. return false;
  55459. },
  55460. enumerable: true,
  55461. configurable: true
  55462. });
  55463. Object.defineProperty(ActionManager, "HasTriggers", {
  55464. /**
  55465. * Does exist one action manager with at least one trigger
  55466. **/
  55467. get: function () {
  55468. for (var t in ActionManager.Triggers) {
  55469. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55470. return true;
  55471. }
  55472. }
  55473. return false;
  55474. },
  55475. enumerable: true,
  55476. configurable: true
  55477. });
  55478. Object.defineProperty(ActionManager, "HasPickTriggers", {
  55479. /**
  55480. * Does exist one action manager with at least one pick trigger
  55481. **/
  55482. get: function () {
  55483. for (var t in ActionManager.Triggers) {
  55484. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55485. var t_int = parseInt(t);
  55486. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  55487. return true;
  55488. }
  55489. }
  55490. }
  55491. return false;
  55492. },
  55493. enumerable: true,
  55494. configurable: true
  55495. });
  55496. /**
  55497. * Does exist one action manager that handles actions of a given trigger
  55498. * @param trigger defines the trigger to be tested
  55499. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  55500. **/
  55501. ActionManager.HasSpecificTrigger = function (trigger) {
  55502. for (var t in ActionManager.Triggers) {
  55503. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55504. var t_int = parseInt(t);
  55505. if (t_int === trigger) {
  55506. return true;
  55507. }
  55508. }
  55509. }
  55510. return false;
  55511. };
  55512. /**
  55513. * Registers an action to this action manager
  55514. * @param action defines the action to be registered
  55515. * @return the action amended (prepared) after registration
  55516. */
  55517. ActionManager.prototype.registerAction = function (action) {
  55518. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  55519. if (this.getScene().actionManager !== this) {
  55520. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  55521. return null;
  55522. }
  55523. }
  55524. this.actions.push(action);
  55525. if (ActionManager.Triggers[action.trigger]) {
  55526. ActionManager.Triggers[action.trigger]++;
  55527. }
  55528. else {
  55529. ActionManager.Triggers[action.trigger] = 1;
  55530. }
  55531. action._actionManager = this;
  55532. action._prepare();
  55533. return action;
  55534. };
  55535. /**
  55536. * Unregisters an action to this action manager
  55537. * @param action defines the action to be unregistered
  55538. * @return a boolean indicating whether the action has been unregistered
  55539. */
  55540. ActionManager.prototype.unregisterAction = function (action) {
  55541. var index = this.actions.indexOf(action);
  55542. if (index !== -1) {
  55543. this.actions.splice(index, 1);
  55544. ActionManager.Triggers[action.trigger] -= 1;
  55545. if (ActionManager.Triggers[action.trigger] === 0) {
  55546. delete ActionManager.Triggers[action.trigger];
  55547. }
  55548. delete action._actionManager;
  55549. return true;
  55550. }
  55551. return false;
  55552. };
  55553. /**
  55554. * Process a specific trigger
  55555. * @param trigger defines the trigger to process
  55556. * @param evt defines the event details to be processed
  55557. */
  55558. ActionManager.prototype.processTrigger = function (trigger, evt) {
  55559. for (var index = 0; index < this.actions.length; index++) {
  55560. var action = this.actions[index];
  55561. if (action.trigger === trigger) {
  55562. if (evt) {
  55563. if (trigger === ActionManager.OnKeyUpTrigger
  55564. || trigger === ActionManager.OnKeyDownTrigger) {
  55565. var parameter = action.getTriggerParameter();
  55566. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  55567. if (!parameter.toLowerCase) {
  55568. continue;
  55569. }
  55570. var lowerCase = parameter.toLowerCase();
  55571. if (lowerCase !== evt.sourceEvent.key) {
  55572. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  55573. var actualkey = String.fromCharCode(unicode).toLowerCase();
  55574. if (actualkey !== lowerCase) {
  55575. continue;
  55576. }
  55577. }
  55578. }
  55579. }
  55580. }
  55581. action._executeCurrent(evt);
  55582. }
  55583. }
  55584. };
  55585. /** @hidden */
  55586. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  55587. var properties = propertyPath.split(".");
  55588. for (var index = 0; index < properties.length - 1; index++) {
  55589. target = target[properties[index]];
  55590. }
  55591. return target;
  55592. };
  55593. /** @hidden */
  55594. ActionManager.prototype._getProperty = function (propertyPath) {
  55595. var properties = propertyPath.split(".");
  55596. return properties[properties.length - 1];
  55597. };
  55598. /**
  55599. * Serialize this manager to a JSON object
  55600. * @param name defines the property name to store this manager
  55601. * @returns a JSON representation of this manager
  55602. */
  55603. ActionManager.prototype.serialize = function (name) {
  55604. var root = {
  55605. children: new Array(),
  55606. name: name,
  55607. type: 3,
  55608. properties: new Array() // Empty for root but required
  55609. };
  55610. for (var i = 0; i < this.actions.length; i++) {
  55611. var triggerObject = {
  55612. type: 0,
  55613. children: new Array(),
  55614. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  55615. properties: new Array()
  55616. };
  55617. var triggerOptions = this.actions[i].triggerOptions;
  55618. if (triggerOptions && typeof triggerOptions !== "number") {
  55619. if (triggerOptions.parameter instanceof BABYLON.Node) {
  55620. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  55621. }
  55622. else {
  55623. var parameter = {};
  55624. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  55625. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  55626. parameter._meshId = triggerOptions.parameter.mesh.id;
  55627. }
  55628. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  55629. }
  55630. }
  55631. // Serialize child action, recursively
  55632. this.actions[i].serialize(triggerObject);
  55633. // Add serialized trigger
  55634. root.children.push(triggerObject);
  55635. }
  55636. return root;
  55637. };
  55638. /**
  55639. * Creates a new ActionManager from a JSON data
  55640. * @param parsedActions defines the JSON data to read from
  55641. * @param object defines the hosting mesh
  55642. * @param scene defines the hosting scene
  55643. */
  55644. ActionManager.Parse = function (parsedActions, object, scene) {
  55645. var actionManager = new ActionManager(scene);
  55646. if (object === null) {
  55647. scene.actionManager = actionManager;
  55648. }
  55649. else {
  55650. object.actionManager = actionManager;
  55651. }
  55652. // instanciate a new object
  55653. var instanciate = function (name, params) {
  55654. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55655. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55656. newInstance.constructor.apply(newInstance, params);
  55657. return newInstance;
  55658. };
  55659. var parseParameter = function (name, value, target, propertyPath) {
  55660. if (propertyPath === null) {
  55661. // String, boolean or float
  55662. var floatValue = parseFloat(value);
  55663. if (value === "true" || value === "false") {
  55664. return value === "true";
  55665. }
  55666. else {
  55667. return isNaN(floatValue) ? value : floatValue;
  55668. }
  55669. }
  55670. var effectiveTarget = propertyPath.split(".");
  55671. var values = value.split(",");
  55672. // Get effective Target
  55673. for (var i = 0; i < effectiveTarget.length; i++) {
  55674. target = target[effectiveTarget[i]];
  55675. }
  55676. // Return appropriate value with its type
  55677. if (typeof (target) === "boolean") {
  55678. return values[0] === "true";
  55679. }
  55680. if (typeof (target) === "string") {
  55681. return values[0];
  55682. }
  55683. // Parameters with multiple values such as Vector3 etc.
  55684. var split = new Array();
  55685. for (var i = 0; i < values.length; i++) {
  55686. split.push(parseFloat(values[i]));
  55687. }
  55688. if (target instanceof BABYLON.Vector3) {
  55689. return BABYLON.Vector3.FromArray(split);
  55690. }
  55691. if (target instanceof BABYLON.Vector4) {
  55692. return BABYLON.Vector4.FromArray(split);
  55693. }
  55694. if (target instanceof BABYLON.Color3) {
  55695. return BABYLON.Color3.FromArray(split);
  55696. }
  55697. if (target instanceof BABYLON.Color4) {
  55698. return BABYLON.Color4.FromArray(split);
  55699. }
  55700. return parseFloat(values[0]);
  55701. };
  55702. // traverse graph per trigger
  55703. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55704. if (combineArray === void 0) { combineArray = null; }
  55705. if (parsedAction.detached) {
  55706. return;
  55707. }
  55708. var parameters = new Array();
  55709. var target = null;
  55710. var propertyPath = null;
  55711. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55712. // Parameters
  55713. if (parsedAction.type === 2) {
  55714. parameters.push(actionManager);
  55715. }
  55716. else {
  55717. parameters.push(trigger);
  55718. }
  55719. if (combine) {
  55720. var actions = new Array();
  55721. for (var j = 0; j < parsedAction.combine.length; j++) {
  55722. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55723. }
  55724. parameters.push(actions);
  55725. }
  55726. else {
  55727. for (var i = 0; i < parsedAction.properties.length; i++) {
  55728. var value = parsedAction.properties[i].value;
  55729. var name = parsedAction.properties[i].name;
  55730. var targetType = parsedAction.properties[i].targetType;
  55731. if (name === "target") {
  55732. if (targetType !== null && targetType === "SceneProperties") {
  55733. value = target = scene;
  55734. }
  55735. else {
  55736. value = target = scene.getNodeByName(value);
  55737. }
  55738. }
  55739. else if (name === "parent") {
  55740. value = scene.getNodeByName(value);
  55741. }
  55742. else if (name === "sound") {
  55743. // Can not externalize to component, so only checks for the presence off the API.
  55744. if (scene.getSoundByName) {
  55745. value = scene.getSoundByName(value);
  55746. }
  55747. }
  55748. else if (name !== "propertyPath") {
  55749. if (parsedAction.type === 2 && name === "operator") {
  55750. value = BABYLON.ValueCondition[value];
  55751. }
  55752. else {
  55753. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55754. }
  55755. }
  55756. else {
  55757. propertyPath = value;
  55758. }
  55759. parameters.push(value);
  55760. }
  55761. }
  55762. if (combineArray === null) {
  55763. parameters.push(condition);
  55764. }
  55765. else {
  55766. parameters.push(null);
  55767. }
  55768. // If interpolate value action
  55769. if (parsedAction.name === "InterpolateValueAction") {
  55770. var param = parameters[parameters.length - 2];
  55771. parameters[parameters.length - 1] = param;
  55772. parameters[parameters.length - 2] = condition;
  55773. }
  55774. // Action or condition(s) and not CombineAction
  55775. var newAction = instanciate(parsedAction.name, parameters);
  55776. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55777. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55778. if (action) {
  55779. action.then(nothing);
  55780. }
  55781. else {
  55782. actionManager.registerAction(nothing);
  55783. }
  55784. action = nothing;
  55785. }
  55786. if (combineArray === null) {
  55787. if (newAction instanceof BABYLON.Condition) {
  55788. condition = newAction;
  55789. newAction = action;
  55790. }
  55791. else {
  55792. condition = null;
  55793. if (action) {
  55794. action.then(newAction);
  55795. }
  55796. else {
  55797. actionManager.registerAction(newAction);
  55798. }
  55799. }
  55800. }
  55801. else {
  55802. combineArray.push(newAction);
  55803. }
  55804. for (var i = 0; i < parsedAction.children.length; i++) {
  55805. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55806. }
  55807. };
  55808. // triggers
  55809. for (var i = 0; i < parsedActions.children.length; i++) {
  55810. var triggerParams;
  55811. var trigger = parsedActions.children[i];
  55812. if (trigger.properties.length > 0) {
  55813. var param = trigger.properties[0].value;
  55814. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55815. if (value._meshId) {
  55816. value.mesh = scene.getMeshByID(value._meshId);
  55817. }
  55818. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55819. }
  55820. else {
  55821. triggerParams = ActionManager[trigger.name];
  55822. }
  55823. for (var j = 0; j < trigger.children.length; j++) {
  55824. if (!trigger.detached) {
  55825. traverse(trigger.children[j], triggerParams, null, null);
  55826. }
  55827. }
  55828. }
  55829. };
  55830. /**
  55831. * Get a trigger name by index
  55832. * @param trigger defines the trigger index
  55833. * @returns a trigger name
  55834. */
  55835. ActionManager.GetTriggerName = function (trigger) {
  55836. switch (trigger) {
  55837. case 0: return "NothingTrigger";
  55838. case 1: return "OnPickTrigger";
  55839. case 2: return "OnLeftPickTrigger";
  55840. case 3: return "OnRightPickTrigger";
  55841. case 4: return "OnCenterPickTrigger";
  55842. case 5: return "OnPickDownTrigger";
  55843. case 6: return "OnPickUpTrigger";
  55844. case 7: return "OnLongPressTrigger";
  55845. case 8: return "OnPointerOverTrigger";
  55846. case 9: return "OnPointerOutTrigger";
  55847. case 10: return "OnEveryFrameTrigger";
  55848. case 11: return "OnIntersectionEnterTrigger";
  55849. case 12: return "OnIntersectionExitTrigger";
  55850. case 13: return "OnKeyDownTrigger";
  55851. case 14: return "OnKeyUpTrigger";
  55852. case 15: return "OnPickOutTrigger";
  55853. default: return "";
  55854. }
  55855. };
  55856. /**
  55857. * Nothing
  55858. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55859. */
  55860. ActionManager.NothingTrigger = 0;
  55861. /**
  55862. * On pick
  55863. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55864. */
  55865. ActionManager.OnPickTrigger = 1;
  55866. /**
  55867. * On left pick
  55868. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55869. */
  55870. ActionManager.OnLeftPickTrigger = 2;
  55871. /**
  55872. * On right pick
  55873. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55874. */
  55875. ActionManager.OnRightPickTrigger = 3;
  55876. /**
  55877. * On center pick
  55878. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55879. */
  55880. ActionManager.OnCenterPickTrigger = 4;
  55881. /**
  55882. * On pick down
  55883. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55884. */
  55885. ActionManager.OnPickDownTrigger = 5;
  55886. /**
  55887. * On double pick
  55888. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55889. */
  55890. ActionManager.OnDoublePickTrigger = 6;
  55891. /**
  55892. * On pick up
  55893. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55894. */
  55895. ActionManager.OnPickUpTrigger = 7;
  55896. /**
  55897. * On pick out.
  55898. * This trigger will only be raised if you also declared a OnPickDown
  55899. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55900. */
  55901. ActionManager.OnPickOutTrigger = 16;
  55902. /**
  55903. * On long press
  55904. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55905. */
  55906. ActionManager.OnLongPressTrigger = 8;
  55907. /**
  55908. * On pointer over
  55909. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55910. */
  55911. ActionManager.OnPointerOverTrigger = 9;
  55912. /**
  55913. * On pointer out
  55914. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55915. */
  55916. ActionManager.OnPointerOutTrigger = 10;
  55917. /**
  55918. * On every frame
  55919. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55920. */
  55921. ActionManager.OnEveryFrameTrigger = 11;
  55922. /**
  55923. * On intersection enter
  55924. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55925. */
  55926. ActionManager.OnIntersectionEnterTrigger = 12;
  55927. /**
  55928. * On intersection exit
  55929. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55930. */
  55931. ActionManager.OnIntersectionExitTrigger = 13;
  55932. /**
  55933. * On key down
  55934. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55935. */
  55936. ActionManager.OnKeyDownTrigger = 14;
  55937. /**
  55938. * On key up
  55939. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55940. */
  55941. ActionManager.OnKeyUpTrigger = 15;
  55942. /** Gets the list of active triggers */
  55943. ActionManager.Triggers = {};
  55944. return ActionManager;
  55945. }());
  55946. BABYLON.ActionManager = ActionManager;
  55947. })(BABYLON || (BABYLON = {}));
  55948. //# sourceMappingURL=babylon.actionManager.js.map
  55949. var BABYLON;
  55950. (function (BABYLON) {
  55951. /**
  55952. * This defines an action responsible to change the value of a property
  55953. * by interpolating between its current value and the newly set one once triggered.
  55954. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55955. */
  55956. var InterpolateValueAction = /** @class */ (function (_super) {
  55957. __extends(InterpolateValueAction, _super);
  55958. /**
  55959. * Instantiate the action
  55960. * @param triggerOptions defines the trigger options
  55961. * @param target defines the object containing the value to interpolate
  55962. * @param propertyPath defines the path to the property in the target object
  55963. * @param value defines the target value at the end of the interpolation
  55964. * @param duration deines the time it will take for the property to interpolate to the value.
  55965. * @param condition defines the trigger related conditions
  55966. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55967. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55968. */
  55969. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55970. if (duration === void 0) { duration = 1000; }
  55971. var _this = _super.call(this, triggerOptions, condition) || this;
  55972. /**
  55973. * Defines the time it will take for the property to interpolate to the value.
  55974. */
  55975. _this.duration = 1000;
  55976. /**
  55977. * Observable triggered once the interpolation animation has been done.
  55978. */
  55979. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55980. _this.propertyPath = propertyPath;
  55981. _this.value = value;
  55982. _this.duration = duration;
  55983. _this.stopOtherAnimations = stopOtherAnimations;
  55984. _this.onInterpolationDone = onInterpolationDone;
  55985. _this._target = _this._effectiveTarget = target;
  55986. return _this;
  55987. }
  55988. /** @hidden */
  55989. InterpolateValueAction.prototype._prepare = function () {
  55990. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55991. this._property = this._getProperty(this.propertyPath);
  55992. };
  55993. /**
  55994. * Execute the action starts the value interpolation.
  55995. */
  55996. InterpolateValueAction.prototype.execute = function () {
  55997. var _this = this;
  55998. var scene = this._actionManager.getScene();
  55999. var keys = [
  56000. {
  56001. frame: 0,
  56002. value: this._effectiveTarget[this._property]
  56003. }, {
  56004. frame: 100,
  56005. value: this.value
  56006. }
  56007. ];
  56008. var dataType;
  56009. if (typeof this.value === "number") {
  56010. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  56011. }
  56012. else if (this.value instanceof BABYLON.Color3) {
  56013. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  56014. }
  56015. else if (this.value instanceof BABYLON.Vector3) {
  56016. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  56017. }
  56018. else if (this.value instanceof BABYLON.Matrix) {
  56019. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  56020. }
  56021. else if (this.value instanceof BABYLON.Quaternion) {
  56022. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  56023. }
  56024. else {
  56025. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  56026. return;
  56027. }
  56028. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  56029. animation.setKeys(keys);
  56030. if (this.stopOtherAnimations) {
  56031. scene.stopAnimation(this._effectiveTarget);
  56032. }
  56033. var wrapper = function () {
  56034. _this.onInterpolationDoneObservable.notifyObservers(_this);
  56035. if (_this.onInterpolationDone) {
  56036. _this.onInterpolationDone();
  56037. }
  56038. };
  56039. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  56040. };
  56041. /**
  56042. * Serializes the actions and its related information.
  56043. * @param parent defines the object to serialize in
  56044. * @returns the serialized object
  56045. */
  56046. InterpolateValueAction.prototype.serialize = function (parent) {
  56047. return _super.prototype._serialize.call(this, {
  56048. name: "InterpolateValueAction",
  56049. properties: [
  56050. BABYLON.Action._GetTargetProperty(this._target),
  56051. { name: "propertyPath", value: this.propertyPath },
  56052. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56053. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  56054. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  56055. ]
  56056. }, parent);
  56057. };
  56058. return InterpolateValueAction;
  56059. }(BABYLON.Action));
  56060. BABYLON.InterpolateValueAction = InterpolateValueAction;
  56061. })(BABYLON || (BABYLON = {}));
  56062. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  56063. var BABYLON;
  56064. (function (BABYLON) {
  56065. /**
  56066. * This defines an action responsible to toggle a boolean once triggered.
  56067. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56068. */
  56069. var SwitchBooleanAction = /** @class */ (function (_super) {
  56070. __extends(SwitchBooleanAction, _super);
  56071. /**
  56072. * Instantiate the action
  56073. * @param triggerOptions defines the trigger options
  56074. * @param target defines the object containing the boolean
  56075. * @param propertyPath defines the path to the boolean property in the target object
  56076. * @param condition defines the trigger related conditions
  56077. */
  56078. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  56079. var _this = _super.call(this, triggerOptions, condition) || this;
  56080. _this.propertyPath = propertyPath;
  56081. _this._target = _this._effectiveTarget = target;
  56082. return _this;
  56083. }
  56084. /** @hidden */
  56085. SwitchBooleanAction.prototype._prepare = function () {
  56086. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56087. this._property = this._getProperty(this.propertyPath);
  56088. };
  56089. /**
  56090. * Execute the action toggle the boolean value.
  56091. */
  56092. SwitchBooleanAction.prototype.execute = function () {
  56093. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  56094. };
  56095. /**
  56096. * Serializes the actions and its related information.
  56097. * @param parent defines the object to serialize in
  56098. * @returns the serialized object
  56099. */
  56100. SwitchBooleanAction.prototype.serialize = function (parent) {
  56101. return _super.prototype._serialize.call(this, {
  56102. name: "SwitchBooleanAction",
  56103. properties: [
  56104. BABYLON.Action._GetTargetProperty(this._target),
  56105. { name: "propertyPath", value: this.propertyPath }
  56106. ]
  56107. }, parent);
  56108. };
  56109. return SwitchBooleanAction;
  56110. }(BABYLON.Action));
  56111. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  56112. /**
  56113. * This defines an action responsible to set a the state field of the target
  56114. * to a desired value once triggered.
  56115. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56116. */
  56117. var SetStateAction = /** @class */ (function (_super) {
  56118. __extends(SetStateAction, _super);
  56119. /**
  56120. * Instantiate the action
  56121. * @param triggerOptions defines the trigger options
  56122. * @param target defines the object containing the state property
  56123. * @param value defines the value to store in the state field
  56124. * @param condition defines the trigger related conditions
  56125. */
  56126. function SetStateAction(triggerOptions, target, value, condition) {
  56127. var _this = _super.call(this, triggerOptions, condition) || this;
  56128. _this.value = value;
  56129. _this._target = target;
  56130. return _this;
  56131. }
  56132. /**
  56133. * Execute the action and store the value on the target state property.
  56134. */
  56135. SetStateAction.prototype.execute = function () {
  56136. this._target.state = this.value;
  56137. };
  56138. /**
  56139. * Serializes the actions and its related information.
  56140. * @param parent defines the object to serialize in
  56141. * @returns the serialized object
  56142. */
  56143. SetStateAction.prototype.serialize = function (parent) {
  56144. return _super.prototype._serialize.call(this, {
  56145. name: "SetStateAction",
  56146. properties: [
  56147. BABYLON.Action._GetTargetProperty(this._target),
  56148. { name: "value", value: this.value }
  56149. ]
  56150. }, parent);
  56151. };
  56152. return SetStateAction;
  56153. }(BABYLON.Action));
  56154. BABYLON.SetStateAction = SetStateAction;
  56155. /**
  56156. * This defines an action responsible to set a property of the target
  56157. * to a desired value once triggered.
  56158. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56159. */
  56160. var SetValueAction = /** @class */ (function (_super) {
  56161. __extends(SetValueAction, _super);
  56162. /**
  56163. * Instantiate the action
  56164. * @param triggerOptions defines the trigger options
  56165. * @param target defines the object containing the property
  56166. * @param propertyPath defines the path of the property to set in the target
  56167. * @param value defines the value to set in the property
  56168. * @param condition defines the trigger related conditions
  56169. */
  56170. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  56171. var _this = _super.call(this, triggerOptions, condition) || this;
  56172. _this.propertyPath = propertyPath;
  56173. _this.value = value;
  56174. _this._target = _this._effectiveTarget = target;
  56175. return _this;
  56176. }
  56177. /** @hidden */
  56178. SetValueAction.prototype._prepare = function () {
  56179. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56180. this._property = this._getProperty(this.propertyPath);
  56181. };
  56182. /**
  56183. * Execute the action and set the targetted property to the desired value.
  56184. */
  56185. SetValueAction.prototype.execute = function () {
  56186. this._effectiveTarget[this._property] = this.value;
  56187. if (this._target.markAsDirty) {
  56188. this._target.markAsDirty(this._property);
  56189. }
  56190. };
  56191. /**
  56192. * Serializes the actions and its related information.
  56193. * @param parent defines the object to serialize in
  56194. * @returns the serialized object
  56195. */
  56196. SetValueAction.prototype.serialize = function (parent) {
  56197. return _super.prototype._serialize.call(this, {
  56198. name: "SetValueAction",
  56199. properties: [
  56200. BABYLON.Action._GetTargetProperty(this._target),
  56201. { name: "propertyPath", value: this.propertyPath },
  56202. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56203. ]
  56204. }, parent);
  56205. };
  56206. return SetValueAction;
  56207. }(BABYLON.Action));
  56208. BABYLON.SetValueAction = SetValueAction;
  56209. /**
  56210. * This defines an action responsible to increment the target value
  56211. * to a desired value once triggered.
  56212. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56213. */
  56214. var IncrementValueAction = /** @class */ (function (_super) {
  56215. __extends(IncrementValueAction, _super);
  56216. /**
  56217. * Instantiate the action
  56218. * @param triggerOptions defines the trigger options
  56219. * @param target defines the object containing the property
  56220. * @param propertyPath defines the path of the property to increment in the target
  56221. * @param value defines the value value we should increment the property by
  56222. * @param condition defines the trigger related conditions
  56223. */
  56224. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  56225. var _this = _super.call(this, triggerOptions, condition) || this;
  56226. _this.propertyPath = propertyPath;
  56227. _this.value = value;
  56228. _this._target = _this._effectiveTarget = target;
  56229. return _this;
  56230. }
  56231. /** @hidden */
  56232. IncrementValueAction.prototype._prepare = function () {
  56233. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56234. this._property = this._getProperty(this.propertyPath);
  56235. if (typeof this._effectiveTarget[this._property] !== "number") {
  56236. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  56237. }
  56238. };
  56239. /**
  56240. * Execute the action and increment the target of the value amount.
  56241. */
  56242. IncrementValueAction.prototype.execute = function () {
  56243. this._effectiveTarget[this._property] += this.value;
  56244. if (this._target.markAsDirty) {
  56245. this._target.markAsDirty(this._property);
  56246. }
  56247. };
  56248. /**
  56249. * Serializes the actions and its related information.
  56250. * @param parent defines the object to serialize in
  56251. * @returns the serialized object
  56252. */
  56253. IncrementValueAction.prototype.serialize = function (parent) {
  56254. return _super.prototype._serialize.call(this, {
  56255. name: "IncrementValueAction",
  56256. properties: [
  56257. BABYLON.Action._GetTargetProperty(this._target),
  56258. { name: "propertyPath", value: this.propertyPath },
  56259. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56260. ]
  56261. }, parent);
  56262. };
  56263. return IncrementValueAction;
  56264. }(BABYLON.Action));
  56265. BABYLON.IncrementValueAction = IncrementValueAction;
  56266. /**
  56267. * This defines an action responsible to start an animation once triggered.
  56268. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56269. */
  56270. var PlayAnimationAction = /** @class */ (function (_super) {
  56271. __extends(PlayAnimationAction, _super);
  56272. /**
  56273. * Instantiate the action
  56274. * @param triggerOptions defines the trigger options
  56275. * @param target defines the target animation or animation name
  56276. * @param from defines from where the animation should start (animation frame)
  56277. * @param end defines where the animation should stop (animation frame)
  56278. * @param loop defines if the animation should loop or stop after the first play
  56279. * @param condition defines the trigger related conditions
  56280. */
  56281. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  56282. var _this = _super.call(this, triggerOptions, condition) || this;
  56283. _this.from = from;
  56284. _this.to = to;
  56285. _this.loop = loop;
  56286. _this._target = target;
  56287. return _this;
  56288. }
  56289. /** @hidden */
  56290. PlayAnimationAction.prototype._prepare = function () {
  56291. };
  56292. /**
  56293. * Execute the action and play the animation.
  56294. */
  56295. PlayAnimationAction.prototype.execute = function () {
  56296. var scene = this._actionManager.getScene();
  56297. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  56298. };
  56299. /**
  56300. * Serializes the actions and its related information.
  56301. * @param parent defines the object to serialize in
  56302. * @returns the serialized object
  56303. */
  56304. PlayAnimationAction.prototype.serialize = function (parent) {
  56305. return _super.prototype._serialize.call(this, {
  56306. name: "PlayAnimationAction",
  56307. properties: [
  56308. BABYLON.Action._GetTargetProperty(this._target),
  56309. { name: "from", value: String(this.from) },
  56310. { name: "to", value: String(this.to) },
  56311. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  56312. ]
  56313. }, parent);
  56314. };
  56315. return PlayAnimationAction;
  56316. }(BABYLON.Action));
  56317. BABYLON.PlayAnimationAction = PlayAnimationAction;
  56318. /**
  56319. * This defines an action responsible to stop an animation once triggered.
  56320. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56321. */
  56322. var StopAnimationAction = /** @class */ (function (_super) {
  56323. __extends(StopAnimationAction, _super);
  56324. /**
  56325. * Instantiate the action
  56326. * @param triggerOptions defines the trigger options
  56327. * @param target defines the target animation or animation name
  56328. * @param condition defines the trigger related conditions
  56329. */
  56330. function StopAnimationAction(triggerOptions, target, condition) {
  56331. var _this = _super.call(this, triggerOptions, condition) || this;
  56332. _this._target = target;
  56333. return _this;
  56334. }
  56335. /** @hidden */
  56336. StopAnimationAction.prototype._prepare = function () {
  56337. };
  56338. /**
  56339. * Execute the action and stop the animation.
  56340. */
  56341. StopAnimationAction.prototype.execute = function () {
  56342. var scene = this._actionManager.getScene();
  56343. scene.stopAnimation(this._target);
  56344. };
  56345. /**
  56346. * Serializes the actions and its related information.
  56347. * @param parent defines the object to serialize in
  56348. * @returns the serialized object
  56349. */
  56350. StopAnimationAction.prototype.serialize = function (parent) {
  56351. return _super.prototype._serialize.call(this, {
  56352. name: "StopAnimationAction",
  56353. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  56354. }, parent);
  56355. };
  56356. return StopAnimationAction;
  56357. }(BABYLON.Action));
  56358. BABYLON.StopAnimationAction = StopAnimationAction;
  56359. /**
  56360. * This defines an action responsible that does nothing once triggered.
  56361. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56362. */
  56363. var DoNothingAction = /** @class */ (function (_super) {
  56364. __extends(DoNothingAction, _super);
  56365. /**
  56366. * Instantiate the action
  56367. * @param triggerOptions defines the trigger options
  56368. * @param condition defines the trigger related conditions
  56369. */
  56370. function DoNothingAction(triggerOptions, condition) {
  56371. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  56372. return _super.call(this, triggerOptions, condition) || this;
  56373. }
  56374. /**
  56375. * Execute the action and do nothing.
  56376. */
  56377. DoNothingAction.prototype.execute = function () {
  56378. };
  56379. /**
  56380. * Serializes the actions and its related information.
  56381. * @param parent defines the object to serialize in
  56382. * @returns the serialized object
  56383. */
  56384. DoNothingAction.prototype.serialize = function (parent) {
  56385. return _super.prototype._serialize.call(this, {
  56386. name: "DoNothingAction",
  56387. properties: []
  56388. }, parent);
  56389. };
  56390. return DoNothingAction;
  56391. }(BABYLON.Action));
  56392. BABYLON.DoNothingAction = DoNothingAction;
  56393. /**
  56394. * This defines an action responsible to trigger several actions once triggered.
  56395. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56396. */
  56397. var CombineAction = /** @class */ (function (_super) {
  56398. __extends(CombineAction, _super);
  56399. /**
  56400. * Instantiate the action
  56401. * @param triggerOptions defines the trigger options
  56402. * @param children defines the list of aggregated animations to run
  56403. * @param condition defines the trigger related conditions
  56404. */
  56405. function CombineAction(triggerOptions, children, condition) {
  56406. var _this = _super.call(this, triggerOptions, condition) || this;
  56407. _this.children = children;
  56408. return _this;
  56409. }
  56410. /** @hidden */
  56411. CombineAction.prototype._prepare = function () {
  56412. for (var index = 0; index < this.children.length; index++) {
  56413. this.children[index]._actionManager = this._actionManager;
  56414. this.children[index]._prepare();
  56415. }
  56416. };
  56417. /**
  56418. * Execute the action and executes all the aggregated actions.
  56419. */
  56420. CombineAction.prototype.execute = function (evt) {
  56421. for (var index = 0; index < this.children.length; index++) {
  56422. this.children[index].execute(evt);
  56423. }
  56424. };
  56425. /**
  56426. * Serializes the actions and its related information.
  56427. * @param parent defines the object to serialize in
  56428. * @returns the serialized object
  56429. */
  56430. CombineAction.prototype.serialize = function (parent) {
  56431. var serializationObject = _super.prototype._serialize.call(this, {
  56432. name: "CombineAction",
  56433. properties: [],
  56434. combine: []
  56435. }, parent);
  56436. for (var i = 0; i < this.children.length; i++) {
  56437. serializationObject.combine.push(this.children[i].serialize(null));
  56438. }
  56439. return serializationObject;
  56440. };
  56441. return CombineAction;
  56442. }(BABYLON.Action));
  56443. BABYLON.CombineAction = CombineAction;
  56444. /**
  56445. * This defines an action responsible to run code (external event) once triggered.
  56446. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56447. */
  56448. var ExecuteCodeAction = /** @class */ (function (_super) {
  56449. __extends(ExecuteCodeAction, _super);
  56450. /**
  56451. * Instantiate the action
  56452. * @param triggerOptions defines the trigger options
  56453. * @param func defines the callback function to run
  56454. * @param condition defines the trigger related conditions
  56455. */
  56456. function ExecuteCodeAction(triggerOptions, func, condition) {
  56457. var _this = _super.call(this, triggerOptions, condition) || this;
  56458. _this.func = func;
  56459. return _this;
  56460. }
  56461. /**
  56462. * Execute the action and run the attached code.
  56463. */
  56464. ExecuteCodeAction.prototype.execute = function (evt) {
  56465. this.func(evt);
  56466. };
  56467. return ExecuteCodeAction;
  56468. }(BABYLON.Action));
  56469. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  56470. /**
  56471. * This defines an action responsible to set the parent property of the target once triggered.
  56472. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56473. */
  56474. var SetParentAction = /** @class */ (function (_super) {
  56475. __extends(SetParentAction, _super);
  56476. /**
  56477. * Instantiate the action
  56478. * @param triggerOptions defines the trigger options
  56479. * @param target defines the target containing the parent property
  56480. * @param parent defines from where the animation should start (animation frame)
  56481. * @param condition defines the trigger related conditions
  56482. */
  56483. function SetParentAction(triggerOptions, target, parent, condition) {
  56484. var _this = _super.call(this, triggerOptions, condition) || this;
  56485. _this._target = target;
  56486. _this._parent = parent;
  56487. return _this;
  56488. }
  56489. /** @hidden */
  56490. SetParentAction.prototype._prepare = function () {
  56491. };
  56492. /**
  56493. * Execute the action and set the parent property.
  56494. */
  56495. SetParentAction.prototype.execute = function () {
  56496. if (this._target.parent === this._parent) {
  56497. return;
  56498. }
  56499. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  56500. invertParentWorldMatrix.invert();
  56501. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  56502. this._target.parent = this._parent;
  56503. };
  56504. /**
  56505. * Serializes the actions and its related information.
  56506. * @param parent defines the object to serialize in
  56507. * @returns the serialized object
  56508. */
  56509. SetParentAction.prototype.serialize = function (parent) {
  56510. return _super.prototype._serialize.call(this, {
  56511. name: "SetParentAction",
  56512. properties: [
  56513. BABYLON.Action._GetTargetProperty(this._target),
  56514. BABYLON.Action._GetTargetProperty(this._parent),
  56515. ]
  56516. }, parent);
  56517. };
  56518. return SetParentAction;
  56519. }(BABYLON.Action));
  56520. BABYLON.SetParentAction = SetParentAction;
  56521. })(BABYLON || (BABYLON = {}));
  56522. //# sourceMappingURL=babylon.directActions.js.map
  56523. var BABYLON;
  56524. (function (BABYLON) {
  56525. /**
  56526. * Class used to manage multiple sprites on the same spritesheet
  56527. * @see http://doc.babylonjs.com/babylon101/sprites
  56528. */
  56529. var SpriteManager = /** @class */ (function () {
  56530. /**
  56531. * Creates a new sprite manager
  56532. * @param name defines the manager's name
  56533. * @param imgUrl defines the sprite sheet url
  56534. * @param capacity defines the maximum allowed number of sprites
  56535. * @param cellSize defines the size of a sprite cell
  56536. * @param scene defines the hosting scene
  56537. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  56538. * @param samplingMode defines the smapling mode to use with spritesheet
  56539. */
  56540. function SpriteManager(
  56541. /** defines the manager's name */
  56542. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  56543. if (epsilon === void 0) { epsilon = 0.01; }
  56544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56545. this.name = name;
  56546. /** Gets the list of sprites */
  56547. this.sprites = new Array();
  56548. /** Gets or sets the rendering group id (0 by default) */
  56549. this.renderingGroupId = 0;
  56550. /** Gets or sets camera layer mask */
  56551. this.layerMask = 0x0FFFFFFF;
  56552. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  56553. this.fogEnabled = true;
  56554. /** Gets or sets a boolean indicating if the sprites are pickable */
  56555. this.isPickable = false;
  56556. /**
  56557. * An event triggered when the manager is disposed.
  56558. */
  56559. this.onDisposeObservable = new BABYLON.Observable();
  56560. this._vertexBuffers = {};
  56561. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  56562. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  56563. }
  56564. this._capacity = capacity;
  56565. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  56566. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56567. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56568. if (cellSize.width && cellSize.height) {
  56569. this.cellWidth = cellSize.width;
  56570. this.cellHeight = cellSize.height;
  56571. }
  56572. else if (cellSize !== undefined) {
  56573. this.cellWidth = cellSize;
  56574. this.cellHeight = cellSize;
  56575. }
  56576. else {
  56577. return;
  56578. }
  56579. this._epsilon = epsilon;
  56580. this._scene = scene;
  56581. this._scene.spriteManagers.push(this);
  56582. var indices = [];
  56583. var index = 0;
  56584. for (var count = 0; count < capacity; count++) {
  56585. indices.push(index);
  56586. indices.push(index + 1);
  56587. indices.push(index + 2);
  56588. indices.push(index);
  56589. indices.push(index + 2);
  56590. indices.push(index + 3);
  56591. index += 4;
  56592. }
  56593. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  56594. // VBO
  56595. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  56596. this._vertexData = new Float32Array(capacity * 16 * 4);
  56597. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  56598. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  56599. var options = this._buffer.createVertexBuffer("options", 4, 4);
  56600. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  56601. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  56602. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56603. this._vertexBuffers["options"] = options;
  56604. this._vertexBuffers["cellInfo"] = cellInfo;
  56605. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56606. // Effects
  56607. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  56608. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  56609. }
  56610. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  56611. /**
  56612. * Callback called when the manager is disposed
  56613. */
  56614. set: function (callback) {
  56615. if (this._onDisposeObserver) {
  56616. this.onDisposeObservable.remove(this._onDisposeObserver);
  56617. }
  56618. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56619. },
  56620. enumerable: true,
  56621. configurable: true
  56622. });
  56623. Object.defineProperty(SpriteManager.prototype, "texture", {
  56624. /**
  56625. * Gets or sets the spritesheet texture
  56626. */
  56627. get: function () {
  56628. return this._spriteTexture;
  56629. },
  56630. set: function (value) {
  56631. this._spriteTexture = value;
  56632. },
  56633. enumerable: true,
  56634. configurable: true
  56635. });
  56636. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  56637. var arrayOffset = index * 16;
  56638. if (offsetX === 0) {
  56639. offsetX = this._epsilon;
  56640. }
  56641. else if (offsetX === 1) {
  56642. offsetX = 1 - this._epsilon;
  56643. }
  56644. if (offsetY === 0) {
  56645. offsetY = this._epsilon;
  56646. }
  56647. else if (offsetY === 1) {
  56648. offsetY = 1 - this._epsilon;
  56649. }
  56650. this._vertexData[arrayOffset] = sprite.position.x;
  56651. this._vertexData[arrayOffset + 1] = sprite.position.y;
  56652. this._vertexData[arrayOffset + 2] = sprite.position.z;
  56653. this._vertexData[arrayOffset + 3] = sprite.angle;
  56654. this._vertexData[arrayOffset + 4] = sprite.width;
  56655. this._vertexData[arrayOffset + 5] = sprite.height;
  56656. this._vertexData[arrayOffset + 6] = offsetX;
  56657. this._vertexData[arrayOffset + 7] = offsetY;
  56658. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  56659. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  56660. var offset = (sprite.cellIndex / rowSize) >> 0;
  56661. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  56662. this._vertexData[arrayOffset + 11] = offset;
  56663. // Color
  56664. this._vertexData[arrayOffset + 12] = sprite.color.r;
  56665. this._vertexData[arrayOffset + 13] = sprite.color.g;
  56666. this._vertexData[arrayOffset + 14] = sprite.color.b;
  56667. this._vertexData[arrayOffset + 15] = sprite.color.a;
  56668. };
  56669. /**
  56670. * Intersects the sprites with a ray
  56671. * @param ray defines the ray to intersect with
  56672. * @param camera defines the current active camera
  56673. * @param predicate defines a predicate used to select candidate sprites
  56674. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  56675. * @returns null if no hit or a PickingInfo
  56676. */
  56677. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  56678. var count = Math.min(this._capacity, this.sprites.length);
  56679. var min = BABYLON.Vector3.Zero();
  56680. var max = BABYLON.Vector3.Zero();
  56681. var distance = Number.MAX_VALUE;
  56682. var currentSprite = null;
  56683. var cameraSpacePosition = BABYLON.Vector3.Zero();
  56684. var cameraView = camera.getViewMatrix();
  56685. for (var index = 0; index < count; index++) {
  56686. var sprite = this.sprites[index];
  56687. if (!sprite) {
  56688. continue;
  56689. }
  56690. if (predicate) {
  56691. if (!predicate(sprite)) {
  56692. continue;
  56693. }
  56694. }
  56695. else if (!sprite.isPickable) {
  56696. continue;
  56697. }
  56698. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  56699. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  56700. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  56701. if (ray.intersectsBoxMinMax(min, max)) {
  56702. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56703. if (distance > currentDistance) {
  56704. distance = currentDistance;
  56705. currentSprite = sprite;
  56706. if (fastCheck) {
  56707. break;
  56708. }
  56709. }
  56710. }
  56711. }
  56712. if (currentSprite) {
  56713. var result = new BABYLON.PickingInfo();
  56714. result.hit = true;
  56715. result.pickedSprite = currentSprite;
  56716. result.distance = distance;
  56717. return result;
  56718. }
  56719. return null;
  56720. };
  56721. /**
  56722. * Render all child sprites
  56723. */
  56724. SpriteManager.prototype.render = function () {
  56725. // Check
  56726. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  56727. return;
  56728. }
  56729. var engine = this._scene.getEngine();
  56730. var baseSize = this._spriteTexture.getBaseSize();
  56731. // Sprites
  56732. var deltaTime = engine.getDeltaTime();
  56733. var max = Math.min(this._capacity, this.sprites.length);
  56734. var rowSize = baseSize.width / this.cellWidth;
  56735. var offset = 0;
  56736. for (var index = 0; index < max; index++) {
  56737. var sprite = this.sprites[index];
  56738. if (!sprite || !sprite.isVisible) {
  56739. continue;
  56740. }
  56741. sprite._animate(deltaTime);
  56742. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56743. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56744. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56745. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56746. }
  56747. this._buffer.update(this._vertexData);
  56748. // Render
  56749. var effect = this._effectBase;
  56750. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56751. effect = this._effectFog;
  56752. }
  56753. engine.enableEffect(effect);
  56754. var viewMatrix = this._scene.getViewMatrix();
  56755. effect.setTexture("diffuseSampler", this._spriteTexture);
  56756. effect.setMatrix("view", viewMatrix);
  56757. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56758. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56759. // Fog
  56760. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56761. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56762. effect.setColor3("vFogColor", this._scene.fogColor);
  56763. }
  56764. // VBOs
  56765. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56766. // Draw order
  56767. engine.setDepthFunctionToLessOrEqual();
  56768. effect.setBool("alphaTest", true);
  56769. engine.setColorWrite(false);
  56770. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56771. engine.setColorWrite(true);
  56772. effect.setBool("alphaTest", false);
  56773. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56774. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56775. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56776. };
  56777. /**
  56778. * Release associated resources
  56779. */
  56780. SpriteManager.prototype.dispose = function () {
  56781. if (this._buffer) {
  56782. this._buffer.dispose();
  56783. this._buffer = null;
  56784. }
  56785. if (this._indexBuffer) {
  56786. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56787. this._indexBuffer = null;
  56788. }
  56789. if (this._spriteTexture) {
  56790. this._spriteTexture.dispose();
  56791. this._spriteTexture = null;
  56792. }
  56793. // Remove from scene
  56794. var index = this._scene.spriteManagers.indexOf(this);
  56795. this._scene.spriteManagers.splice(index, 1);
  56796. // Callback
  56797. this.onDisposeObservable.notifyObservers(this);
  56798. this.onDisposeObservable.clear();
  56799. };
  56800. return SpriteManager;
  56801. }());
  56802. BABYLON.SpriteManager = SpriteManager;
  56803. })(BABYLON || (BABYLON = {}));
  56804. //# sourceMappingURL=babylon.spriteManager.js.map
  56805. var BABYLON;
  56806. (function (BABYLON) {
  56807. /**
  56808. * Class used to represent a sprite
  56809. * @see http://doc.babylonjs.com/babylon101/sprites
  56810. */
  56811. var Sprite = /** @class */ (function () {
  56812. /**
  56813. * Creates a new Sprite
  56814. * @param name defines the name
  56815. * @param manager defines the manager
  56816. */
  56817. function Sprite(
  56818. /** defines the name */
  56819. name, manager) {
  56820. this.name = name;
  56821. /** Gets or sets the main color */
  56822. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56823. /** Gets or sets the width */
  56824. this.width = 1.0;
  56825. /** Gets or sets the height */
  56826. this.height = 1.0;
  56827. /** Gets or sets rotation angle */
  56828. this.angle = 0;
  56829. /** Gets or sets the cell index in the sprite sheet */
  56830. this.cellIndex = 0;
  56831. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  56832. this.invertU = 0;
  56833. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  56834. this.invertV = 0;
  56835. /** Gets the list of attached animations */
  56836. this.animations = new Array();
  56837. /** Gets or sets a boolean indicating if the sprite can be picked */
  56838. this.isPickable = false;
  56839. this._animationStarted = false;
  56840. this._loopAnimation = false;
  56841. this._fromIndex = 0;
  56842. this._toIndex = 0;
  56843. this._delay = 0;
  56844. this._direction = 1;
  56845. this._time = 0;
  56846. /**
  56847. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56848. */
  56849. this.isVisible = true;
  56850. this._manager = manager;
  56851. this._manager.sprites.push(this);
  56852. this.position = BABYLON.Vector3.Zero();
  56853. }
  56854. Object.defineProperty(Sprite.prototype, "size", {
  56855. /**
  56856. * Gets or sets the sprite size
  56857. */
  56858. get: function () {
  56859. return this.width;
  56860. },
  56861. set: function (value) {
  56862. this.width = value;
  56863. this.height = value;
  56864. },
  56865. enumerable: true,
  56866. configurable: true
  56867. });
  56868. /**
  56869. * Starts an animation
  56870. * @param from defines the initial key
  56871. * @param to defines the end key
  56872. * @param loop defines if the animation must loop
  56873. * @param delay defines the start delay (in ms)
  56874. * @param onAnimationEnd defines a callback to call when animation ends
  56875. */
  56876. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56877. this._fromIndex = from;
  56878. this._toIndex = to;
  56879. this._loopAnimation = loop;
  56880. this._delay = delay;
  56881. this._animationStarted = true;
  56882. this._direction = from < to ? 1 : -1;
  56883. this.cellIndex = from;
  56884. this._time = 0;
  56885. this._onAnimationEnd = onAnimationEnd;
  56886. };
  56887. /** Stops current animation (if any) */
  56888. Sprite.prototype.stopAnimation = function () {
  56889. this._animationStarted = false;
  56890. };
  56891. /** @hidden */
  56892. Sprite.prototype._animate = function (deltaTime) {
  56893. if (!this._animationStarted) {
  56894. return;
  56895. }
  56896. this._time += deltaTime;
  56897. if (this._time > this._delay) {
  56898. this._time = this._time % this._delay;
  56899. this.cellIndex += this._direction;
  56900. if (this.cellIndex > this._toIndex) {
  56901. if (this._loopAnimation) {
  56902. this.cellIndex = this._fromIndex;
  56903. }
  56904. else {
  56905. this.cellIndex = this._toIndex;
  56906. this._animationStarted = false;
  56907. if (this._onAnimationEnd) {
  56908. this._onAnimationEnd();
  56909. }
  56910. if (this.disposeWhenFinishedAnimating) {
  56911. this.dispose();
  56912. }
  56913. }
  56914. }
  56915. }
  56916. };
  56917. /** Release associated resources */
  56918. Sprite.prototype.dispose = function () {
  56919. for (var i = 0; i < this._manager.sprites.length; i++) {
  56920. if (this._manager.sprites[i] == this) {
  56921. this._manager.sprites.splice(i, 1);
  56922. }
  56923. }
  56924. };
  56925. return Sprite;
  56926. }());
  56927. BABYLON.Sprite = Sprite;
  56928. })(BABYLON || (BABYLON = {}));
  56929. //# sourceMappingURL=babylon.sprite.js.map
  56930. var BABYLON;
  56931. (function (BABYLON) {
  56932. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56933. if (!BABYLON.PickingInfo) {
  56934. return null;
  56935. }
  56936. var pickingInfo = null;
  56937. if (!camera) {
  56938. if (!this.activeCamera) {
  56939. return null;
  56940. }
  56941. camera = this.activeCamera;
  56942. }
  56943. if (this.spriteManagers.length > 0) {
  56944. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56945. var spriteManager = this.spriteManagers[spriteIndex];
  56946. if (!spriteManager.isPickable) {
  56947. continue;
  56948. }
  56949. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56950. if (!result || !result.hit) {
  56951. continue;
  56952. }
  56953. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  56954. continue;
  56955. }
  56956. pickingInfo = result;
  56957. if (fastCheck) {
  56958. break;
  56959. }
  56960. }
  56961. }
  56962. return pickingInfo || new BABYLON.PickingInfo();
  56963. };
  56964. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56965. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56966. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56967. };
  56968. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56969. if (!this._tempSpritePickingRay) {
  56970. return null;
  56971. }
  56972. if (!camera) {
  56973. if (!this.activeCamera) {
  56974. return null;
  56975. }
  56976. camera = this.activeCamera;
  56977. }
  56978. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56979. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56980. };
  56981. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56982. if (this._pointerOverSprite === sprite) {
  56983. return;
  56984. }
  56985. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56986. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56987. }
  56988. this._pointerOverSprite = sprite;
  56989. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56990. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56991. }
  56992. };
  56993. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56994. return this._pointerOverSprite;
  56995. };
  56996. /**
  56997. * Defines the sprite scene component responsible to manage sprites
  56998. * in a given scene.
  56999. */
  57000. var SpriteSceneComponent = /** @class */ (function () {
  57001. /**
  57002. * Creates a new instance of the component for the given scene
  57003. * @param scene Defines the scene to register the component in
  57004. */
  57005. function SpriteSceneComponent(scene) {
  57006. /**
  57007. * The component name helpfull to identify the component in the list of scene components.
  57008. */
  57009. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  57010. this.scene = scene;
  57011. this.scene.spriteManagers = new Array();
  57012. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  57013. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  57014. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  57015. this._spritePredicate = function (sprite) {
  57016. if (!sprite.actionManager) {
  57017. return false;
  57018. }
  57019. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  57020. };
  57021. }
  57022. /**
  57023. * Registers the component in a given scene
  57024. */
  57025. SpriteSceneComponent.prototype.register = function () {
  57026. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  57027. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  57028. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  57029. };
  57030. /**
  57031. * Rebuilds the elements related to this component in case of
  57032. * context lost for instance.
  57033. */
  57034. SpriteSceneComponent.prototype.rebuild = function () {
  57035. /** Nothing to do for sprites */
  57036. };
  57037. /**
  57038. * Disposes the component and the associated ressources.
  57039. */
  57040. SpriteSceneComponent.prototype.dispose = function () {
  57041. this.scene.onBeforeSpritesRenderingObservable.clear();
  57042. this.scene.onAfterSpritesRenderingObservable.clear();
  57043. var spriteManagers = this.scene.spriteManagers;
  57044. while (spriteManagers.length) {
  57045. spriteManagers[0].dispose();
  57046. }
  57047. };
  57048. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  57049. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  57050. if (result) {
  57051. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  57052. }
  57053. return result;
  57054. };
  57055. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  57056. var scene = this.scene;
  57057. if (isMeshPicked) {
  57058. scene.setPointerOverSprite(null);
  57059. }
  57060. else {
  57061. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  57062. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  57063. scene.setPointerOverSprite(pickResult.pickedSprite);
  57064. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  57065. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  57066. }
  57067. else {
  57068. canvas.style.cursor = scene.hoverCursor;
  57069. }
  57070. }
  57071. else {
  57072. scene.setPointerOverSprite(null);
  57073. }
  57074. }
  57075. return pickResult;
  57076. };
  57077. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  57078. var scene = this.scene;
  57079. scene._pickedDownSprite = null;
  57080. if (scene.spriteManagers.length > 0) {
  57081. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  57082. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  57083. if (pickResult.pickedSprite.actionManager) {
  57084. scene._pickedDownSprite = pickResult.pickedSprite;
  57085. switch (evt.button) {
  57086. case 0:
  57087. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57088. break;
  57089. case 1:
  57090. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57091. break;
  57092. case 2:
  57093. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57094. break;
  57095. }
  57096. if (pickResult.pickedSprite.actionManager) {
  57097. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  57098. }
  57099. }
  57100. }
  57101. }
  57102. return pickResult;
  57103. };
  57104. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  57105. var scene = this.scene;
  57106. if (scene.spriteManagers.length > 0) {
  57107. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  57108. if (spritePickResult) {
  57109. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  57110. if (spritePickResult.pickedSprite.actionManager) {
  57111. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  57112. if (spritePickResult.pickedSprite.actionManager) {
  57113. if (!this.scene._isPointerSwiping()) {
  57114. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  57115. }
  57116. }
  57117. }
  57118. }
  57119. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  57120. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  57121. }
  57122. }
  57123. }
  57124. return pickResult;
  57125. };
  57126. return SpriteSceneComponent;
  57127. }());
  57128. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  57129. })(BABYLON || (BABYLON = {}));
  57130. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  57131. var BABYLON;
  57132. (function (BABYLON) {
  57133. /**
  57134. * @hidden
  57135. */
  57136. var IntersectionInfo = /** @class */ (function () {
  57137. function IntersectionInfo(bu, bv, distance) {
  57138. this.bu = bu;
  57139. this.bv = bv;
  57140. this.distance = distance;
  57141. this.faceId = 0;
  57142. this.subMeshId = 0;
  57143. }
  57144. return IntersectionInfo;
  57145. }());
  57146. BABYLON.IntersectionInfo = IntersectionInfo;
  57147. /**
  57148. * Information about the result of picking within a scene
  57149. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  57150. */
  57151. var PickingInfo = /** @class */ (function () {
  57152. function PickingInfo() {
  57153. /**
  57154. * If the pick collided with an object
  57155. */
  57156. this.hit = false;
  57157. /**
  57158. * Distance away where the pick collided
  57159. */
  57160. this.distance = 0;
  57161. /**
  57162. * The location of pick collision
  57163. */
  57164. this.pickedPoint = null;
  57165. /**
  57166. * The mesh corresponding the the pick collision
  57167. */
  57168. this.pickedMesh = null;
  57169. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  57170. this.bu = 0;
  57171. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  57172. this.bv = 0;
  57173. /** The id of the face on the mesh that was picked */
  57174. this.faceId = -1;
  57175. /** Id of the the submesh that was picked */
  57176. this.subMeshId = 0;
  57177. /** If a sprite was picked, this will be the sprite the pick collided with */
  57178. this.pickedSprite = null;
  57179. /**
  57180. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  57181. */
  57182. this.originMesh = null;
  57183. /**
  57184. * The ray that was used to perform the picking.
  57185. */
  57186. this.ray = null;
  57187. }
  57188. /**
  57189. * Gets the normal correspodning to the face the pick collided with
  57190. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  57191. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  57192. * @returns The normal correspodning to the face the pick collided with
  57193. */
  57194. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  57195. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  57196. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  57197. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  57198. return null;
  57199. }
  57200. var indices = this.pickedMesh.getIndices();
  57201. if (!indices) {
  57202. return null;
  57203. }
  57204. var result;
  57205. if (useVerticesNormals) {
  57206. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57207. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  57208. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  57209. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  57210. normal0 = normal0.scale(this.bu);
  57211. normal1 = normal1.scale(this.bv);
  57212. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  57213. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  57214. }
  57215. else {
  57216. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57217. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  57218. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  57219. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  57220. var p1p2 = vertex1.subtract(vertex2);
  57221. var p3p2 = vertex3.subtract(vertex2);
  57222. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  57223. }
  57224. if (useWorldCoordinates) {
  57225. var wm = this.pickedMesh.getWorldMatrix();
  57226. if (this.pickedMesh.nonUniformScaling) {
  57227. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  57228. wm = BABYLON.Tmp.Matrix[0];
  57229. wm.setTranslationFromFloats(0, 0, 0);
  57230. wm.invert();
  57231. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  57232. wm = BABYLON.Tmp.Matrix[1];
  57233. }
  57234. result = BABYLON.Vector3.TransformNormal(result, wm);
  57235. }
  57236. result.normalize();
  57237. return result;
  57238. };
  57239. /**
  57240. * Gets the texture coordinates of where the pick occured
  57241. * @returns the vector containing the coordnates of the texture
  57242. */
  57243. PickingInfo.prototype.getTextureCoordinates = function () {
  57244. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57245. return null;
  57246. }
  57247. var indices = this.pickedMesh.getIndices();
  57248. if (!indices) {
  57249. return null;
  57250. }
  57251. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57252. if (!uvs) {
  57253. return null;
  57254. }
  57255. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  57256. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  57257. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  57258. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  57259. uv1 = uv1.scale(this.bu);
  57260. uv2 = uv2.scale(this.bv);
  57261. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  57262. };
  57263. return PickingInfo;
  57264. }());
  57265. BABYLON.PickingInfo = PickingInfo;
  57266. })(BABYLON || (BABYLON = {}));
  57267. //# sourceMappingURL=babylon.pickingInfo.js.map
  57268. var BABYLON;
  57269. (function (BABYLON) {
  57270. /**
  57271. * Class representing a ray with position and direction
  57272. */
  57273. var Ray = /** @class */ (function () {
  57274. /**
  57275. * Creates a new ray
  57276. * @param origin origin point
  57277. * @param direction direction
  57278. * @param length length of the ray
  57279. */
  57280. function Ray(
  57281. /** origin point */
  57282. origin,
  57283. /** direction */
  57284. direction,
  57285. /** length of the ray */
  57286. length) {
  57287. if (length === void 0) { length = Number.MAX_VALUE; }
  57288. this.origin = origin;
  57289. this.direction = direction;
  57290. this.length = length;
  57291. }
  57292. // Methods
  57293. /**
  57294. * Checks if the ray intersects a box
  57295. * @param minimum bound of the box
  57296. * @param maximum bound of the box
  57297. * @returns if the box was hit
  57298. */
  57299. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  57300. var d = 0.0;
  57301. var maxValue = Number.MAX_VALUE;
  57302. var inv;
  57303. var min;
  57304. var max;
  57305. var temp;
  57306. if (Math.abs(this.direction.x) < 0.0000001) {
  57307. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  57308. return false;
  57309. }
  57310. }
  57311. else {
  57312. inv = 1.0 / this.direction.x;
  57313. min = (minimum.x - this.origin.x) * inv;
  57314. max = (maximum.x - this.origin.x) * inv;
  57315. if (max === -Infinity) {
  57316. max = Infinity;
  57317. }
  57318. if (min > max) {
  57319. temp = min;
  57320. min = max;
  57321. max = temp;
  57322. }
  57323. d = Math.max(min, d);
  57324. maxValue = Math.min(max, maxValue);
  57325. if (d > maxValue) {
  57326. return false;
  57327. }
  57328. }
  57329. if (Math.abs(this.direction.y) < 0.0000001) {
  57330. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  57331. return false;
  57332. }
  57333. }
  57334. else {
  57335. inv = 1.0 / this.direction.y;
  57336. min = (minimum.y - this.origin.y) * inv;
  57337. max = (maximum.y - this.origin.y) * inv;
  57338. if (max === -Infinity) {
  57339. max = Infinity;
  57340. }
  57341. if (min > max) {
  57342. temp = min;
  57343. min = max;
  57344. max = temp;
  57345. }
  57346. d = Math.max(min, d);
  57347. maxValue = Math.min(max, maxValue);
  57348. if (d > maxValue) {
  57349. return false;
  57350. }
  57351. }
  57352. if (Math.abs(this.direction.z) < 0.0000001) {
  57353. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  57354. return false;
  57355. }
  57356. }
  57357. else {
  57358. inv = 1.0 / this.direction.z;
  57359. min = (minimum.z - this.origin.z) * inv;
  57360. max = (maximum.z - this.origin.z) * inv;
  57361. if (max === -Infinity) {
  57362. max = Infinity;
  57363. }
  57364. if (min > max) {
  57365. temp = min;
  57366. min = max;
  57367. max = temp;
  57368. }
  57369. d = Math.max(min, d);
  57370. maxValue = Math.min(max, maxValue);
  57371. if (d > maxValue) {
  57372. return false;
  57373. }
  57374. }
  57375. return true;
  57376. };
  57377. /**
  57378. * Checks if the ray intersects a box
  57379. * @param box the bounding box to check
  57380. * @returns if the box was hit
  57381. */
  57382. Ray.prototype.intersectsBox = function (box) {
  57383. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  57384. };
  57385. /**
  57386. * If the ray hits a sphere
  57387. * @param sphere the bounding sphere to check
  57388. * @returns true if it hits the sphere
  57389. */
  57390. Ray.prototype.intersectsSphere = function (sphere) {
  57391. var x = sphere.center.x - this.origin.x;
  57392. var y = sphere.center.y - this.origin.y;
  57393. var z = sphere.center.z - this.origin.z;
  57394. var pyth = (x * x) + (y * y) + (z * z);
  57395. var rr = sphere.radius * sphere.radius;
  57396. if (pyth <= rr) {
  57397. return true;
  57398. }
  57399. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  57400. if (dot < 0.0) {
  57401. return false;
  57402. }
  57403. var temp = pyth - (dot * dot);
  57404. return temp <= rr;
  57405. };
  57406. /**
  57407. * If the ray hits a triange
  57408. * @param vertex0 triangle vertex
  57409. * @param vertex1 triangle vertex
  57410. * @param vertex2 triangle vertex
  57411. * @returns intersection information if hit
  57412. */
  57413. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  57414. if (!this._edge1) {
  57415. this._edge1 = BABYLON.Vector3.Zero();
  57416. this._edge2 = BABYLON.Vector3.Zero();
  57417. this._pvec = BABYLON.Vector3.Zero();
  57418. this._tvec = BABYLON.Vector3.Zero();
  57419. this._qvec = BABYLON.Vector3.Zero();
  57420. }
  57421. vertex1.subtractToRef(vertex0, this._edge1);
  57422. vertex2.subtractToRef(vertex0, this._edge2);
  57423. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  57424. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  57425. if (det === 0) {
  57426. return null;
  57427. }
  57428. var invdet = 1 / det;
  57429. this.origin.subtractToRef(vertex0, this._tvec);
  57430. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  57431. if (bu < 0 || bu > 1.0) {
  57432. return null;
  57433. }
  57434. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  57435. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  57436. if (bv < 0 || bu + bv > 1.0) {
  57437. return null;
  57438. }
  57439. //check if the distance is longer than the predefined length.
  57440. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  57441. if (distance > this.length) {
  57442. return null;
  57443. }
  57444. return new BABYLON.IntersectionInfo(bu, bv, distance);
  57445. };
  57446. /**
  57447. * Checks if ray intersects a plane
  57448. * @param plane the plane to check
  57449. * @returns the distance away it was hit
  57450. */
  57451. Ray.prototype.intersectsPlane = function (plane) {
  57452. var distance;
  57453. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  57454. if (Math.abs(result1) < 9.99999997475243E-07) {
  57455. return null;
  57456. }
  57457. else {
  57458. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  57459. distance = (-plane.d - result2) / result1;
  57460. if (distance < 0.0) {
  57461. if (distance < -9.99999997475243E-07) {
  57462. return null;
  57463. }
  57464. else {
  57465. return 0;
  57466. }
  57467. }
  57468. return distance;
  57469. }
  57470. };
  57471. /**
  57472. * Checks if ray intersects a mesh
  57473. * @param mesh the mesh to check
  57474. * @param fastCheck if only the bounding box should checked
  57475. * @returns picking info of the intersecton
  57476. */
  57477. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  57478. var tm = BABYLON.Tmp.Matrix[0];
  57479. mesh.getWorldMatrix().invertToRef(tm);
  57480. if (this._tmpRay) {
  57481. Ray.TransformToRef(this, tm, this._tmpRay);
  57482. }
  57483. else {
  57484. this._tmpRay = Ray.Transform(this, tm);
  57485. }
  57486. return mesh.intersects(this._tmpRay, fastCheck);
  57487. };
  57488. /**
  57489. * Checks if ray intersects a mesh
  57490. * @param meshes the meshes to check
  57491. * @param fastCheck if only the bounding box should checked
  57492. * @param results array to store result in
  57493. * @returns Array of picking infos
  57494. */
  57495. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  57496. if (results) {
  57497. results.length = 0;
  57498. }
  57499. else {
  57500. results = [];
  57501. }
  57502. for (var i = 0; i < meshes.length; i++) {
  57503. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  57504. if (pickInfo.hit) {
  57505. results.push(pickInfo);
  57506. }
  57507. }
  57508. results.sort(this._comparePickingInfo);
  57509. return results;
  57510. };
  57511. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  57512. if (pickingInfoA.distance < pickingInfoB.distance) {
  57513. return -1;
  57514. }
  57515. else if (pickingInfoA.distance > pickingInfoB.distance) {
  57516. return 1;
  57517. }
  57518. else {
  57519. return 0;
  57520. }
  57521. };
  57522. /**
  57523. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  57524. * @param sega the first point of the segment to test the intersection against
  57525. * @param segb the second point of the segment to test the intersection against
  57526. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  57527. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  57528. */
  57529. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  57530. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  57531. var u = segb.subtract(sega);
  57532. var v = rsegb.subtract(this.origin);
  57533. var w = sega.subtract(this.origin);
  57534. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  57535. var b = BABYLON.Vector3.Dot(u, v);
  57536. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  57537. var d = BABYLON.Vector3.Dot(u, w);
  57538. var e = BABYLON.Vector3.Dot(v, w);
  57539. var D = a * c - b * b; // always >= 0
  57540. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  57541. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  57542. // compute the line parameters of the two closest points
  57543. if (D < Ray.smallnum) { // the lines are almost parallel
  57544. sN = 0.0; // force using point P0 on segment S1
  57545. sD = 1.0; // to prevent possible division by 0.0 later
  57546. tN = e;
  57547. tD = c;
  57548. }
  57549. else { // get the closest points on the infinite lines
  57550. sN = (b * e - c * d);
  57551. tN = (a * e - b * d);
  57552. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  57553. sN = 0.0;
  57554. tN = e;
  57555. tD = c;
  57556. }
  57557. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  57558. sN = sD;
  57559. tN = e + b;
  57560. tD = c;
  57561. }
  57562. }
  57563. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  57564. tN = 0.0;
  57565. // recompute sc for this edge
  57566. if (-d < 0.0) {
  57567. sN = 0.0;
  57568. }
  57569. else if (-d > a) {
  57570. sN = sD;
  57571. }
  57572. else {
  57573. sN = -d;
  57574. sD = a;
  57575. }
  57576. }
  57577. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  57578. tN = tD;
  57579. // recompute sc for this edge
  57580. if ((-d + b) < 0.0) {
  57581. sN = 0;
  57582. }
  57583. else if ((-d + b) > a) {
  57584. sN = sD;
  57585. }
  57586. else {
  57587. sN = (-d + b);
  57588. sD = a;
  57589. }
  57590. }
  57591. // finally do the division to get sc and tc
  57592. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  57593. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  57594. // get the difference of the two closest points
  57595. var qtc = v.multiplyByFloats(tc, tc, tc);
  57596. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  57597. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  57598. if (isIntersected) {
  57599. return qtc.length();
  57600. }
  57601. return -1;
  57602. };
  57603. /**
  57604. * Update the ray from viewport position
  57605. * @param x position
  57606. * @param y y position
  57607. * @param viewportWidth viewport width
  57608. * @param viewportHeight viewport height
  57609. * @param world world matrix
  57610. * @param view view matrix
  57611. * @param projection projection matrix
  57612. * @returns this ray updated
  57613. */
  57614. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57615. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  57616. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  57617. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  57618. this.direction.normalize();
  57619. return this;
  57620. };
  57621. // Statics
  57622. /**
  57623. * Creates a ray with origin and direction of 0,0,0
  57624. * @returns the new ray
  57625. */
  57626. Ray.Zero = function () {
  57627. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  57628. };
  57629. /**
  57630. * Creates a new ray from screen space and viewport
  57631. * @param x position
  57632. * @param y y position
  57633. * @param viewportWidth viewport width
  57634. * @param viewportHeight viewport height
  57635. * @param world world matrix
  57636. * @param view view matrix
  57637. * @param projection projection matrix
  57638. * @returns new ray
  57639. */
  57640. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57641. var result = Ray.Zero();
  57642. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  57643. };
  57644. /**
  57645. * 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
  57646. * transformed to the given world matrix.
  57647. * @param origin The origin point
  57648. * @param end The end point
  57649. * @param world a matrix to transform the ray to. Default is the identity matrix.
  57650. * @returns the new ray
  57651. */
  57652. Ray.CreateNewFromTo = function (origin, end, world) {
  57653. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  57654. var direction = end.subtract(origin);
  57655. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  57656. direction.normalize();
  57657. return Ray.Transform(new Ray(origin, direction, length), world);
  57658. };
  57659. /**
  57660. * Transforms a ray by a matrix
  57661. * @param ray ray to transform
  57662. * @param matrix matrix to apply
  57663. * @returns the resulting new ray
  57664. */
  57665. Ray.Transform = function (ray, matrix) {
  57666. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  57667. Ray.TransformToRef(ray, matrix, result);
  57668. return result;
  57669. };
  57670. /**
  57671. * Transforms a ray by a matrix
  57672. * @param ray ray to transform
  57673. * @param matrix matrix to apply
  57674. * @param result ray to store result in
  57675. */
  57676. Ray.TransformToRef = function (ray, matrix, result) {
  57677. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  57678. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  57679. result.length = ray.length;
  57680. var dir = result.direction;
  57681. var len = dir.length();
  57682. if (!(len === 0 || len === 1)) {
  57683. var num = 1.0 / len;
  57684. dir.x *= num;
  57685. dir.y *= num;
  57686. dir.z *= num;
  57687. result.length *= len;
  57688. }
  57689. };
  57690. Ray.smallnum = 0.00000001;
  57691. Ray.rayl = 10e8;
  57692. return Ray;
  57693. }());
  57694. BABYLON.Ray = Ray;
  57695. })(BABYLON || (BABYLON = {}));
  57696. //# sourceMappingURL=babylon.ray.js.map
  57697. var BABYLON;
  57698. (function (BABYLON) {
  57699. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  57700. if (boxMin.x > sphereCenter.x + sphereRadius) {
  57701. return false;
  57702. }
  57703. if (sphereCenter.x - sphereRadius > boxMax.x) {
  57704. return false;
  57705. }
  57706. if (boxMin.y > sphereCenter.y + sphereRadius) {
  57707. return false;
  57708. }
  57709. if (sphereCenter.y - sphereRadius > boxMax.y) {
  57710. return false;
  57711. }
  57712. if (boxMin.z > sphereCenter.z + sphereRadius) {
  57713. return false;
  57714. }
  57715. if (sphereCenter.z - sphereRadius > boxMax.z) {
  57716. return false;
  57717. }
  57718. return true;
  57719. };
  57720. var getLowestRoot = (function () {
  57721. var result = { root: 0, found: false };
  57722. return function (a, b, c, maxR) {
  57723. result.root = 0;
  57724. result.found = false;
  57725. var determinant = b * b - 4.0 * a * c;
  57726. if (determinant < 0) {
  57727. return result;
  57728. }
  57729. var sqrtD = Math.sqrt(determinant);
  57730. var r1 = (-b - sqrtD) / (2.0 * a);
  57731. var r2 = (-b + sqrtD) / (2.0 * a);
  57732. if (r1 > r2) {
  57733. var temp = r2;
  57734. r2 = r1;
  57735. r1 = temp;
  57736. }
  57737. if (r1 > 0 && r1 < maxR) {
  57738. result.root = r1;
  57739. result.found = true;
  57740. return result;
  57741. }
  57742. if (r2 > 0 && r2 < maxR) {
  57743. result.root = r2;
  57744. result.found = true;
  57745. return result;
  57746. }
  57747. return result;
  57748. };
  57749. })();
  57750. /** @hidden */
  57751. var Collider = /** @class */ (function () {
  57752. function Collider() {
  57753. this._collisionPoint = BABYLON.Vector3.Zero();
  57754. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  57755. this._tempVector = BABYLON.Vector3.Zero();
  57756. this._tempVector2 = BABYLON.Vector3.Zero();
  57757. this._tempVector3 = BABYLON.Vector3.Zero();
  57758. this._tempVector4 = BABYLON.Vector3.Zero();
  57759. this._edge = BABYLON.Vector3.Zero();
  57760. this._baseToVertex = BABYLON.Vector3.Zero();
  57761. this._destinationPoint = BABYLON.Vector3.Zero();
  57762. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  57763. this._displacementVector = BABYLON.Vector3.Zero();
  57764. /** @hidden */
  57765. this._radius = BABYLON.Vector3.One();
  57766. /** @hidden */
  57767. this._retry = 0;
  57768. /** @hidden */
  57769. this._basePointWorld = BABYLON.Vector3.Zero();
  57770. this._velocityWorld = BABYLON.Vector3.Zero();
  57771. this._normalizedVelocity = BABYLON.Vector3.Zero();
  57772. this._collisionMask = -1;
  57773. }
  57774. Object.defineProperty(Collider.prototype, "collisionMask", {
  57775. get: function () {
  57776. return this._collisionMask;
  57777. },
  57778. set: function (mask) {
  57779. this._collisionMask = !isNaN(mask) ? mask : -1;
  57780. },
  57781. enumerable: true,
  57782. configurable: true
  57783. });
  57784. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  57785. /**
  57786. * Gets the plane normal used to compute the sliding response (in local space)
  57787. */
  57788. get: function () {
  57789. return this._slidePlaneNormal;
  57790. },
  57791. enumerable: true,
  57792. configurable: true
  57793. });
  57794. // Methods
  57795. /** @hidden */
  57796. Collider.prototype._initialize = function (source, dir, e) {
  57797. this._velocity = dir;
  57798. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  57799. this._basePoint = source;
  57800. source.multiplyToRef(this._radius, this._basePointWorld);
  57801. dir.multiplyToRef(this._radius, this._velocityWorld);
  57802. this._velocityWorldLength = this._velocityWorld.length();
  57803. this._epsilon = e;
  57804. this.collisionFound = false;
  57805. };
  57806. /** @hidden */
  57807. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  57808. pa.subtractToRef(point, this._tempVector);
  57809. pb.subtractToRef(point, this._tempVector2);
  57810. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  57811. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57812. if (d < 0) {
  57813. return false;
  57814. }
  57815. pc.subtractToRef(point, this._tempVector3);
  57816. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  57817. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57818. if (d < 0) {
  57819. return false;
  57820. }
  57821. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  57822. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57823. return d >= 0;
  57824. };
  57825. /** @hidden */
  57826. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  57827. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  57828. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  57829. if (distance > this._velocityWorldLength + max + sphereRadius) {
  57830. return false;
  57831. }
  57832. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  57833. return false;
  57834. }
  57835. return true;
  57836. };
  57837. /** @hidden */
  57838. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  57839. var t0;
  57840. var embeddedInPlane = false;
  57841. //defensive programming, actually not needed.
  57842. if (!trianglePlaneArray) {
  57843. trianglePlaneArray = [];
  57844. }
  57845. if (!trianglePlaneArray[faceIndex]) {
  57846. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  57847. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  57848. }
  57849. var trianglePlane = trianglePlaneArray[faceIndex];
  57850. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  57851. return;
  57852. }
  57853. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  57854. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  57855. if (normalDotVelocity == 0) {
  57856. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  57857. return;
  57858. }
  57859. embeddedInPlane = true;
  57860. t0 = 0;
  57861. }
  57862. else {
  57863. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57864. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57865. if (t0 > t1) {
  57866. var temp = t1;
  57867. t1 = t0;
  57868. t0 = temp;
  57869. }
  57870. if (t0 > 1.0 || t1 < 0.0) {
  57871. return;
  57872. }
  57873. if (t0 < 0) {
  57874. t0 = 0;
  57875. }
  57876. if (t0 > 1.0) {
  57877. t0 = 1.0;
  57878. }
  57879. }
  57880. this._collisionPoint.copyFromFloats(0, 0, 0);
  57881. var found = false;
  57882. var t = 1.0;
  57883. if (!embeddedInPlane) {
  57884. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57885. this._velocity.scaleToRef(t0, this._tempVector);
  57886. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57887. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57888. found = true;
  57889. t = t0;
  57890. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57891. }
  57892. }
  57893. if (!found) {
  57894. var velocitySquaredLength = this._velocity.lengthSquared();
  57895. var a = velocitySquaredLength;
  57896. this._basePoint.subtractToRef(p1, this._tempVector);
  57897. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57898. var c = this._tempVector.lengthSquared() - 1.0;
  57899. var lowestRoot = getLowestRoot(a, b, c, t);
  57900. if (lowestRoot.found) {
  57901. t = lowestRoot.root;
  57902. found = true;
  57903. this._collisionPoint.copyFrom(p1);
  57904. }
  57905. this._basePoint.subtractToRef(p2, this._tempVector);
  57906. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57907. c = this._tempVector.lengthSquared() - 1.0;
  57908. lowestRoot = getLowestRoot(a, b, c, t);
  57909. if (lowestRoot.found) {
  57910. t = lowestRoot.root;
  57911. found = true;
  57912. this._collisionPoint.copyFrom(p2);
  57913. }
  57914. this._basePoint.subtractToRef(p3, this._tempVector);
  57915. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57916. c = this._tempVector.lengthSquared() - 1.0;
  57917. lowestRoot = getLowestRoot(a, b, c, t);
  57918. if (lowestRoot.found) {
  57919. t = lowestRoot.root;
  57920. found = true;
  57921. this._collisionPoint.copyFrom(p3);
  57922. }
  57923. p2.subtractToRef(p1, this._edge);
  57924. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57925. var edgeSquaredLength = this._edge.lengthSquared();
  57926. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57927. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57928. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57929. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57930. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57931. lowestRoot = getLowestRoot(a, b, c, t);
  57932. if (lowestRoot.found) {
  57933. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57934. if (f >= 0.0 && f <= 1.0) {
  57935. t = lowestRoot.root;
  57936. found = true;
  57937. this._edge.scaleInPlace(f);
  57938. p1.addToRef(this._edge, this._collisionPoint);
  57939. }
  57940. }
  57941. p3.subtractToRef(p2, this._edge);
  57942. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57943. edgeSquaredLength = this._edge.lengthSquared();
  57944. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57945. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57946. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57947. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57948. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57949. lowestRoot = getLowestRoot(a, b, c, t);
  57950. if (lowestRoot.found) {
  57951. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57952. if (f >= 0.0 && f <= 1.0) {
  57953. t = lowestRoot.root;
  57954. found = true;
  57955. this._edge.scaleInPlace(f);
  57956. p2.addToRef(this._edge, this._collisionPoint);
  57957. }
  57958. }
  57959. p1.subtractToRef(p3, this._edge);
  57960. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57961. edgeSquaredLength = this._edge.lengthSquared();
  57962. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57963. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57964. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57965. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57966. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57967. lowestRoot = getLowestRoot(a, b, c, t);
  57968. if (lowestRoot.found) {
  57969. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57970. if (f >= 0.0 && f <= 1.0) {
  57971. t = lowestRoot.root;
  57972. found = true;
  57973. this._edge.scaleInPlace(f);
  57974. p3.addToRef(this._edge, this._collisionPoint);
  57975. }
  57976. }
  57977. }
  57978. if (found) {
  57979. var distToCollision = t * this._velocity.length();
  57980. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57981. if (!this.intersectionPoint) {
  57982. this.intersectionPoint = this._collisionPoint.clone();
  57983. }
  57984. else {
  57985. this.intersectionPoint.copyFrom(this._collisionPoint);
  57986. }
  57987. this._nearestDistance = distToCollision;
  57988. this.collisionFound = true;
  57989. }
  57990. }
  57991. };
  57992. /** @hidden */
  57993. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57994. for (var i = indexStart; i < indexEnd; i += 3) {
  57995. var p1 = pts[indices[i] - decal];
  57996. var p2 = pts[indices[i + 1] - decal];
  57997. var p3 = pts[indices[i + 2] - decal];
  57998. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57999. }
  58000. };
  58001. /** @hidden */
  58002. Collider.prototype._getResponse = function (pos, vel) {
  58003. pos.addToRef(vel, this._destinationPoint);
  58004. vel.scaleInPlace((this._nearestDistance / vel.length()));
  58005. this._basePoint.addToRef(vel, pos);
  58006. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  58007. this._slidePlaneNormal.normalize();
  58008. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  58009. pos.addInPlace(this._displacementVector);
  58010. this.intersectionPoint.addInPlace(this._displacementVector);
  58011. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  58012. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  58013. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  58014. };
  58015. return Collider;
  58016. }());
  58017. BABYLON.Collider = Collider;
  58018. })(BABYLON || (BABYLON = {}));
  58019. //# sourceMappingURL=babylon.collider.js.map
  58020. var BABYLON;
  58021. (function (BABYLON) {
  58022. //WebWorker code will be inserted to this variable.
  58023. /** @hidden */
  58024. BABYLON.CollisionWorker = "";
  58025. /** Defines supported task for worker process */
  58026. var WorkerTaskType;
  58027. (function (WorkerTaskType) {
  58028. /** Initialization */
  58029. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  58030. /** Update of geometry */
  58031. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  58032. /** Evaluate collision */
  58033. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  58034. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  58035. /** Defines kind of replies returned by worker */
  58036. var WorkerReplyType;
  58037. (function (WorkerReplyType) {
  58038. /** Success */
  58039. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  58040. /** Unkown error */
  58041. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  58042. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  58043. /** @hidden */
  58044. var CollisionCoordinatorWorker = /** @class */ (function () {
  58045. function CollisionCoordinatorWorker() {
  58046. var _this = this;
  58047. this._scaledPosition = BABYLON.Vector3.Zero();
  58048. this._scaledVelocity = BABYLON.Vector3.Zero();
  58049. this.onMeshUpdated = function (transformNode) {
  58050. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  58051. };
  58052. this.onGeometryUpdated = function (geometry) {
  58053. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  58054. };
  58055. this._afterRender = function () {
  58056. if (!_this._init) {
  58057. return;
  58058. }
  58059. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  58060. return;
  58061. }
  58062. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  58063. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  58064. if (_this._runningUpdated > 4) {
  58065. return;
  58066. }
  58067. ++_this._runningUpdated;
  58068. var payload = {
  58069. updatedMeshes: _this._addUpdateMeshesList,
  58070. updatedGeometries: _this._addUpdateGeometriesList,
  58071. removedGeometries: _this._toRemoveGeometryArray,
  58072. removedMeshes: _this._toRemoveMeshesArray
  58073. };
  58074. var message = {
  58075. payload: payload,
  58076. taskType: WorkerTaskType.UPDATE
  58077. };
  58078. var serializable = [];
  58079. for (var id in payload.updatedGeometries) {
  58080. if (payload.updatedGeometries.hasOwnProperty(id)) {
  58081. //prepare transferables
  58082. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  58083. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  58084. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  58085. }
  58086. }
  58087. _this._worker.postMessage(message, serializable);
  58088. _this._addUpdateMeshesList = {};
  58089. _this._addUpdateGeometriesList = {};
  58090. _this._toRemoveGeometryArray = [];
  58091. _this._toRemoveMeshesArray = [];
  58092. };
  58093. this._onMessageFromWorker = function (e) {
  58094. var returnData = e.data;
  58095. if (returnData.error != WorkerReplyType.SUCCESS) {
  58096. //TODO what errors can be returned from the worker?
  58097. BABYLON.Tools.Warn("error returned from worker!");
  58098. return;
  58099. }
  58100. switch (returnData.taskType) {
  58101. case WorkerTaskType.INIT:
  58102. _this._init = true;
  58103. //Update the worked with ALL of the scene's current state
  58104. _this._scene.meshes.forEach(function (mesh) {
  58105. _this.onMeshAdded(mesh);
  58106. });
  58107. _this._scene.getGeometries().forEach(function (geometry) {
  58108. _this.onGeometryAdded(geometry);
  58109. });
  58110. break;
  58111. case WorkerTaskType.UPDATE:
  58112. _this._runningUpdated--;
  58113. break;
  58114. case WorkerTaskType.COLLIDE:
  58115. var returnPayload = returnData.payload;
  58116. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  58117. return;
  58118. }
  58119. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  58120. if (callback) {
  58121. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  58122. if (mesh) {
  58123. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  58124. }
  58125. }
  58126. //cleanup
  58127. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  58128. break;
  58129. }
  58130. };
  58131. this._collisionsCallbackArray = [];
  58132. this._init = false;
  58133. this._runningUpdated = 0;
  58134. this._addUpdateMeshesList = {};
  58135. this._addUpdateGeometriesList = {};
  58136. this._toRemoveGeometryArray = [];
  58137. this._toRemoveMeshesArray = [];
  58138. }
  58139. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58140. if (!this._init) {
  58141. return;
  58142. }
  58143. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  58144. return;
  58145. }
  58146. position.divideToRef(collider._radius, this._scaledPosition);
  58147. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58148. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  58149. var payload = {
  58150. collider: {
  58151. position: this._scaledPosition.asArray(),
  58152. velocity: this._scaledVelocity.asArray(),
  58153. radius: collider._radius.asArray()
  58154. },
  58155. collisionId: collisionIndex,
  58156. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  58157. maximumRetry: maximumRetry
  58158. };
  58159. var message = {
  58160. payload: payload,
  58161. taskType: WorkerTaskType.COLLIDE
  58162. };
  58163. this._worker.postMessage(message);
  58164. };
  58165. CollisionCoordinatorWorker.prototype.init = function (scene) {
  58166. this._scene = scene;
  58167. this._scene.registerAfterRender(this._afterRender);
  58168. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  58169. this._worker = new Worker(workerUrl);
  58170. this._worker.onmessage = this._onMessageFromWorker;
  58171. var message = {
  58172. payload: {},
  58173. taskType: WorkerTaskType.INIT
  58174. };
  58175. this._worker.postMessage(message);
  58176. };
  58177. CollisionCoordinatorWorker.prototype.destroy = function () {
  58178. this._scene.unregisterAfterRender(this._afterRender);
  58179. this._worker.terminate();
  58180. };
  58181. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  58182. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  58183. this.onMeshUpdated(mesh);
  58184. };
  58185. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  58186. this._toRemoveMeshesArray.push(mesh.uniqueId);
  58187. };
  58188. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  58189. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  58190. geometry.onGeometryUpdated = this.onGeometryUpdated;
  58191. this.onGeometryUpdated(geometry);
  58192. };
  58193. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  58194. this._toRemoveGeometryArray.push(geometry.id);
  58195. };
  58196. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  58197. var submeshes = [];
  58198. if (mesh.subMeshes) {
  58199. submeshes = mesh.subMeshes.map(function (sm, idx) {
  58200. var boundingInfo = sm.getBoundingInfo();
  58201. return {
  58202. position: idx,
  58203. verticesStart: sm.verticesStart,
  58204. verticesCount: sm.verticesCount,
  58205. indexStart: sm.indexStart,
  58206. indexCount: sm.indexCount,
  58207. hasMaterial: !!sm.getMaterial(),
  58208. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  58209. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  58210. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  58211. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  58212. };
  58213. });
  58214. }
  58215. var geometryId = null;
  58216. if (mesh instanceof BABYLON.Mesh) {
  58217. var geometry = mesh.geometry;
  58218. geometryId = geometry ? geometry.id : null;
  58219. }
  58220. else if (mesh instanceof BABYLON.InstancedMesh) {
  58221. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  58222. geometryId = geometry ? geometry.id : null;
  58223. }
  58224. var boundingInfo = mesh.getBoundingInfo();
  58225. return {
  58226. uniqueId: mesh.uniqueId,
  58227. id: mesh.id,
  58228. name: mesh.name,
  58229. geometryId: geometryId,
  58230. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  58231. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  58232. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  58233. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  58234. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  58235. subMeshes: submeshes,
  58236. checkCollisions: mesh.checkCollisions
  58237. };
  58238. };
  58239. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  58240. return {
  58241. id: geometry.id,
  58242. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  58243. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  58244. indices: new Uint32Array(geometry.getIndices() || []),
  58245. };
  58246. };
  58247. return CollisionCoordinatorWorker;
  58248. }());
  58249. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  58250. /** @hidden */
  58251. var CollisionCoordinatorLegacy = /** @class */ (function () {
  58252. function CollisionCoordinatorLegacy() {
  58253. this._scaledPosition = BABYLON.Vector3.Zero();
  58254. this._scaledVelocity = BABYLON.Vector3.Zero();
  58255. this._finalPosition = BABYLON.Vector3.Zero();
  58256. }
  58257. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58258. position.divideToRef(collider._radius, this._scaledPosition);
  58259. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58260. collider.collidedMesh = null;
  58261. collider._retry = 0;
  58262. collider._initialVelocity = this._scaledVelocity;
  58263. collider._initialPosition = this._scaledPosition;
  58264. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  58265. this._finalPosition.multiplyInPlace(collider._radius);
  58266. //run the callback
  58267. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  58268. };
  58269. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  58270. this._scene = scene;
  58271. };
  58272. CollisionCoordinatorLegacy.prototype.destroy = function () {
  58273. //Legacy need no destruction method.
  58274. };
  58275. //No update in legacy mode
  58276. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  58277. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  58278. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  58279. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  58280. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  58281. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  58282. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  58283. if (excludedMesh === void 0) { excludedMesh = null; }
  58284. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  58285. if (collider._retry >= maximumRetry) {
  58286. finalPosition.copyFrom(position);
  58287. return;
  58288. }
  58289. // Check if this is a mesh else camera or -1
  58290. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  58291. collider._initialize(position, velocity, closeDistance);
  58292. // Check all meshes
  58293. for (var index = 0; index < this._scene.meshes.length; index++) {
  58294. var mesh = this._scene.meshes[index];
  58295. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  58296. mesh._checkCollision(collider);
  58297. }
  58298. }
  58299. if (!collider.collisionFound) {
  58300. position.addToRef(velocity, finalPosition);
  58301. return;
  58302. }
  58303. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  58304. collider._getResponse(position, velocity);
  58305. }
  58306. if (velocity.length() <= closeDistance) {
  58307. finalPosition.copyFrom(position);
  58308. return;
  58309. }
  58310. collider._retry++;
  58311. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  58312. };
  58313. return CollisionCoordinatorLegacy;
  58314. }());
  58315. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  58316. })(BABYLON || (BABYLON = {}));
  58317. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  58318. var BABYLON;
  58319. (function (BABYLON) {
  58320. /**
  58321. * A particle represents one of the element emitted by a particle system.
  58322. * This is mainly define by its coordinates, direction, velocity and age.
  58323. */
  58324. var Particle = /** @class */ (function () {
  58325. /**
  58326. * Creates a new instance Particle
  58327. * @param particleSystem the particle system the particle belongs to
  58328. */
  58329. function Particle(
  58330. /**
  58331. * The particle system the particle belongs to.
  58332. */
  58333. particleSystem) {
  58334. this.particleSystem = particleSystem;
  58335. /**
  58336. * The world position of the particle in the scene.
  58337. */
  58338. this.position = BABYLON.Vector3.Zero();
  58339. /**
  58340. * The world direction of the particle in the scene.
  58341. */
  58342. this.direction = BABYLON.Vector3.Zero();
  58343. /**
  58344. * The color of the particle.
  58345. */
  58346. this.color = new BABYLON.Color4(0, 0, 0, 0);
  58347. /**
  58348. * The color change of the particle per step.
  58349. */
  58350. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  58351. /**
  58352. * Defines how long will the life of the particle be.
  58353. */
  58354. this.lifeTime = 1.0;
  58355. /**
  58356. * The current age of the particle.
  58357. */
  58358. this.age = 0;
  58359. /**
  58360. * The current size of the particle.
  58361. */
  58362. this.size = 0;
  58363. /**
  58364. * The current scale of the particle.
  58365. */
  58366. this.scale = new BABYLON.Vector2(1, 1);
  58367. /**
  58368. * The current angle of the particle.
  58369. */
  58370. this.angle = 0;
  58371. /**
  58372. * Defines how fast is the angle changing.
  58373. */
  58374. this.angularSpeed = 0;
  58375. /**
  58376. * Defines the cell index used by the particle to be rendered from a sprite.
  58377. */
  58378. this.cellIndex = 0;
  58379. /** @hidden */
  58380. this._attachedSubEmitters = null;
  58381. /** @hidden */
  58382. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  58383. /** @hidden */
  58384. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  58385. /** @hidden */
  58386. this._currentSize1 = 0;
  58387. /** @hidden */
  58388. this._currentSize2 = 0;
  58389. /** @hidden */
  58390. this._currentAngularSpeed1 = 0;
  58391. /** @hidden */
  58392. this._currentAngularSpeed2 = 0;
  58393. /** @hidden */
  58394. this._currentVelocity1 = 0;
  58395. /** @hidden */
  58396. this._currentVelocity2 = 0;
  58397. /** @hidden */
  58398. this._currentLimitVelocity1 = 0;
  58399. /** @hidden */
  58400. this._currentLimitVelocity2 = 0;
  58401. /** @hidden */
  58402. this._currentDrag1 = 0;
  58403. /** @hidden */
  58404. this._currentDrag2 = 0;
  58405. this.id = Particle._Count++;
  58406. if (!this.particleSystem.isAnimationSheetEnabled) {
  58407. return;
  58408. }
  58409. this.updateCellInfoFromSystem();
  58410. }
  58411. Particle.prototype.updateCellInfoFromSystem = function () {
  58412. this.cellIndex = this.particleSystem.startSpriteCellID;
  58413. };
  58414. /**
  58415. * Defines how the sprite cell index is updated for the particle
  58416. */
  58417. Particle.prototype.updateCellIndex = function () {
  58418. var offsetAge = this.age;
  58419. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  58420. if (this.particleSystem.spriteRandomStartCell) {
  58421. if (this._randomCellOffset === undefined) {
  58422. this._randomCellOffset = Math.random() * this.lifeTime;
  58423. }
  58424. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  58425. changeSpeed = 1;
  58426. offsetAge = this._randomCellOffset;
  58427. }
  58428. else {
  58429. offsetAge += this._randomCellOffset;
  58430. }
  58431. }
  58432. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  58433. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  58434. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  58435. };
  58436. /** @hidden */
  58437. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  58438. if (subEmitter.particleSystem.emitter.position) {
  58439. var emitterMesh = subEmitter.particleSystem.emitter;
  58440. emitterMesh.position.copyFrom(this.position);
  58441. if (subEmitter.inheritDirection) {
  58442. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  58443. // Look at using Y as forward
  58444. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  58445. }
  58446. }
  58447. else {
  58448. var emitterPosition = subEmitter.particleSystem.emitter;
  58449. emitterPosition.copyFrom(this.position);
  58450. }
  58451. // Set inheritedVelocityOffset to be used when new particles are created
  58452. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  58453. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  58454. };
  58455. /** @hidden */
  58456. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  58457. var _this = this;
  58458. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  58459. this._attachedSubEmitters.forEach(function (subEmitter) {
  58460. _this._inheritParticleInfoToSubEmitter(subEmitter);
  58461. });
  58462. }
  58463. };
  58464. /** @hidden */
  58465. Particle.prototype._reset = function () {
  58466. this.age = 0;
  58467. this._currentColorGradient = null;
  58468. this._currentSizeGradient = null;
  58469. this._currentAngularSpeedGradient = null;
  58470. this._currentVelocityGradient = null;
  58471. this._currentLimitVelocityGradient = null;
  58472. this._currentDragGradient = null;
  58473. this.cellIndex = this.particleSystem.startSpriteCellID;
  58474. this._randomCellOffset = undefined;
  58475. };
  58476. /**
  58477. * Copy the properties of particle to another one.
  58478. * @param other the particle to copy the information to.
  58479. */
  58480. Particle.prototype.copyTo = function (other) {
  58481. other.position.copyFrom(this.position);
  58482. if (this._initialDirection) {
  58483. if (other._initialDirection) {
  58484. other._initialDirection.copyFrom(this._initialDirection);
  58485. }
  58486. else {
  58487. other._initialDirection = this._initialDirection.clone();
  58488. }
  58489. }
  58490. else {
  58491. other._initialDirection = null;
  58492. }
  58493. other.direction.copyFrom(this.direction);
  58494. other.color.copyFrom(this.color);
  58495. other.colorStep.copyFrom(this.colorStep);
  58496. other.lifeTime = this.lifeTime;
  58497. other.age = this.age;
  58498. other._randomCellOffset = this._randomCellOffset;
  58499. other.size = this.size;
  58500. other.scale.copyFrom(this.scale);
  58501. other.angle = this.angle;
  58502. other.angularSpeed = this.angularSpeed;
  58503. other.particleSystem = this.particleSystem;
  58504. other.cellIndex = this.cellIndex;
  58505. other.id = this.id;
  58506. other._attachedSubEmitters = this._attachedSubEmitters;
  58507. if (this._currentColorGradient) {
  58508. other._currentColorGradient = this._currentColorGradient;
  58509. other._currentColor1.copyFrom(this._currentColor1);
  58510. other._currentColor2.copyFrom(this._currentColor2);
  58511. }
  58512. if (this._currentSizeGradient) {
  58513. other._currentSizeGradient = this._currentSizeGradient;
  58514. other._currentSize1 = this._currentSize1;
  58515. other._currentSize2 = this._currentSize2;
  58516. }
  58517. if (this._currentAngularSpeedGradient) {
  58518. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  58519. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  58520. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  58521. }
  58522. if (this._currentVelocityGradient) {
  58523. other._currentVelocityGradient = this._currentVelocityGradient;
  58524. other._currentVelocity1 = this._currentVelocity1;
  58525. other._currentVelocity2 = this._currentVelocity2;
  58526. }
  58527. if (this._currentLimitVelocityGradient) {
  58528. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  58529. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  58530. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  58531. }
  58532. if (this._currentDragGradient) {
  58533. other._currentDragGradient = this._currentDragGradient;
  58534. other._currentDrag1 = this._currentDrag1;
  58535. other._currentDrag2 = this._currentDrag2;
  58536. }
  58537. if (this.particleSystem.isAnimationSheetEnabled) {
  58538. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  58539. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  58540. }
  58541. if (this.particleSystem.useRampGradients) {
  58542. other.remapData.copyFrom(this.remapData);
  58543. }
  58544. if (this._randomNoiseCoordinates1) {
  58545. if (other._randomNoiseCoordinates1) {
  58546. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  58547. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  58548. }
  58549. else {
  58550. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  58551. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  58552. }
  58553. }
  58554. };
  58555. Particle._Count = 0;
  58556. return Particle;
  58557. }());
  58558. BABYLON.Particle = Particle;
  58559. })(BABYLON || (BABYLON = {}));
  58560. //# sourceMappingURL=babylon.particle.js.map
  58561. var BABYLON;
  58562. (function (BABYLON) {
  58563. /**
  58564. * This represents the base class for particle system in Babylon.
  58565. * 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.
  58566. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58567. * @example https://doc.babylonjs.com/babylon101/particles
  58568. */
  58569. var BaseParticleSystem = /** @class */ (function () {
  58570. /**
  58571. * Instantiates a particle system.
  58572. * 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.
  58573. * @param name The name of the particle system
  58574. */
  58575. function BaseParticleSystem(name) {
  58576. /**
  58577. * List of animations used by the particle system.
  58578. */
  58579. this.animations = [];
  58580. /**
  58581. * The rendering group used by the Particle system to chose when to render.
  58582. */
  58583. this.renderingGroupId = 0;
  58584. /**
  58585. * The emitter represents the Mesh or position we are attaching the particle system to.
  58586. */
  58587. this.emitter = null;
  58588. /**
  58589. * The maximum number of particles to emit per frame
  58590. */
  58591. this.emitRate = 10;
  58592. /**
  58593. * If you want to launch only a few particles at once, that can be done, as well.
  58594. */
  58595. this.manualEmitCount = -1;
  58596. /**
  58597. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  58598. */
  58599. this.updateSpeed = 0.01;
  58600. /**
  58601. * The amount of time the particle system is running (depends of the overall update speed).
  58602. */
  58603. this.targetStopDuration = 0;
  58604. /**
  58605. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  58606. */
  58607. this.disposeOnStop = false;
  58608. /**
  58609. * Minimum power of emitting particles.
  58610. */
  58611. this.minEmitPower = 1;
  58612. /**
  58613. * Maximum power of emitting particles.
  58614. */
  58615. this.maxEmitPower = 1;
  58616. /**
  58617. * Minimum life time of emitting particles.
  58618. */
  58619. this.minLifeTime = 1;
  58620. /**
  58621. * Maximum life time of emitting particles.
  58622. */
  58623. this.maxLifeTime = 1;
  58624. /**
  58625. * Minimum Size of emitting particles.
  58626. */
  58627. this.minSize = 1;
  58628. /**
  58629. * Maximum Size of emitting particles.
  58630. */
  58631. this.maxSize = 1;
  58632. /**
  58633. * Minimum scale of emitting particles on X axis.
  58634. */
  58635. this.minScaleX = 1;
  58636. /**
  58637. * Maximum scale of emitting particles on X axis.
  58638. */
  58639. this.maxScaleX = 1;
  58640. /**
  58641. * Minimum scale of emitting particles on Y axis.
  58642. */
  58643. this.minScaleY = 1;
  58644. /**
  58645. * Maximum scale of emitting particles on Y axis.
  58646. */
  58647. this.maxScaleY = 1;
  58648. /**
  58649. * Gets or sets the minimal initial rotation in radians.
  58650. */
  58651. this.minInitialRotation = 0;
  58652. /**
  58653. * Gets or sets the maximal initial rotation in radians.
  58654. */
  58655. this.maxInitialRotation = 0;
  58656. /**
  58657. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  58658. */
  58659. this.minAngularSpeed = 0;
  58660. /**
  58661. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  58662. */
  58663. this.maxAngularSpeed = 0;
  58664. /**
  58665. * The layer mask we are rendering the particles through.
  58666. */
  58667. this.layerMask = 0x0FFFFFFF;
  58668. /**
  58669. * This can help using your own shader to render the particle system.
  58670. * The according effect will be created
  58671. */
  58672. this.customShader = null;
  58673. /**
  58674. * By default particle system starts as soon as they are created. This prevents the
  58675. * automatic start to happen and let you decide when to start emitting particles.
  58676. */
  58677. this.preventAutoStart = false;
  58678. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  58679. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  58680. /**
  58681. * Callback triggered when the particle animation is ending.
  58682. */
  58683. this.onAnimationEnd = null;
  58684. /**
  58685. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  58686. */
  58687. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  58688. /**
  58689. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  58690. * to override the particles.
  58691. */
  58692. this.forceDepthWrite = false;
  58693. /** 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 */
  58694. this.preWarmCycles = 0;
  58695. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  58696. this.preWarmStepOffset = 1;
  58697. /**
  58698. * 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)
  58699. */
  58700. this.spriteCellChangeSpeed = 1;
  58701. /**
  58702. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  58703. */
  58704. this.startSpriteCellID = 0;
  58705. /**
  58706. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  58707. */
  58708. this.endSpriteCellID = 0;
  58709. /**
  58710. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  58711. */
  58712. this.spriteCellWidth = 0;
  58713. /**
  58714. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  58715. */
  58716. this.spriteCellHeight = 0;
  58717. /**
  58718. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  58719. */
  58720. this.spriteRandomStartCell = false;
  58721. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  58722. this.translationPivot = new BABYLON.Vector2(0, 0);
  58723. /**
  58724. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  58725. */
  58726. this.beginAnimationOnStart = false;
  58727. /**
  58728. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  58729. */
  58730. this.beginAnimationFrom = 0;
  58731. /**
  58732. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  58733. */
  58734. this.beginAnimationTo = 60;
  58735. /**
  58736. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  58737. */
  58738. this.beginAnimationLoop = false;
  58739. /**
  58740. * You can use gravity if you want to give an orientation to your particles.
  58741. */
  58742. this.gravity = BABYLON.Vector3.Zero();
  58743. this._colorGradients = null;
  58744. this._sizeGradients = null;
  58745. this._lifeTimeGradients = null;
  58746. this._angularSpeedGradients = null;
  58747. this._velocityGradients = null;
  58748. this._limitVelocityGradients = null;
  58749. this._dragGradients = null;
  58750. this._emitRateGradients = null;
  58751. this._startSizeGradients = null;
  58752. this._rampGradients = null;
  58753. this._colorRemapGradients = null;
  58754. this._alphaRemapGradients = null;
  58755. /**
  58756. * Defines the delay in milliseconds before starting the system (0 by default)
  58757. */
  58758. this.startDelay = 0;
  58759. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  58760. this.limitVelocityDamping = 0.4;
  58761. /**
  58762. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58763. */
  58764. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58765. /**
  58766. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58767. */
  58768. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58769. /**
  58770. * Color the particle will have at the end of its lifetime
  58771. */
  58772. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  58773. /**
  58774. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  58775. */
  58776. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58777. /** @hidden */
  58778. this._isSubEmitter = false;
  58779. /**
  58780. * Gets or sets the billboard mode to use when isBillboardBased = true.
  58781. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  58782. */
  58783. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  58784. this._isBillboardBased = true;
  58785. /**
  58786. * Local cache of defines for image processing.
  58787. */
  58788. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  58789. this.id = name;
  58790. this.name = name;
  58791. }
  58792. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  58793. /**
  58794. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  58795. */
  58796. get: function () {
  58797. return this._isAnimationSheetEnabled;
  58798. },
  58799. set: function (value) {
  58800. if (this._isAnimationSheetEnabled == value) {
  58801. return;
  58802. }
  58803. this._isAnimationSheetEnabled = value;
  58804. this._reset();
  58805. },
  58806. enumerable: true,
  58807. configurable: true
  58808. });
  58809. /**
  58810. * Get hosting scene
  58811. * @returns the scene
  58812. */
  58813. BaseParticleSystem.prototype.getScene = function () {
  58814. return this._scene;
  58815. };
  58816. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  58817. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  58818. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  58819. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  58820. };
  58821. /**
  58822. * Gets the current list of drag gradients.
  58823. * You must use addDragGradient and removeDragGradient to udpate this list
  58824. * @returns the list of drag gradients
  58825. */
  58826. BaseParticleSystem.prototype.getDragGradients = function () {
  58827. return this._dragGradients;
  58828. };
  58829. /**
  58830. * Gets the current list of limit velocity gradients.
  58831. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  58832. * @returns the list of limit velocity gradients
  58833. */
  58834. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  58835. return this._limitVelocityGradients;
  58836. };
  58837. /**
  58838. * Gets the current list of color gradients.
  58839. * You must use addColorGradient and removeColorGradient to udpate this list
  58840. * @returns the list of color gradients
  58841. */
  58842. BaseParticleSystem.prototype.getColorGradients = function () {
  58843. return this._colorGradients;
  58844. };
  58845. /**
  58846. * Gets the current list of size gradients.
  58847. * You must use addSizeGradient and removeSizeGradient to udpate this list
  58848. * @returns the list of size gradients
  58849. */
  58850. BaseParticleSystem.prototype.getSizeGradients = function () {
  58851. return this._sizeGradients;
  58852. };
  58853. /**
  58854. * Gets the current list of color remap gradients.
  58855. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  58856. * @returns the list of color remap gradients
  58857. */
  58858. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  58859. return this._colorRemapGradients;
  58860. };
  58861. /**
  58862. * Gets the current list of alpha remap gradients.
  58863. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58864. * @returns the list of alpha remap gradients
  58865. */
  58866. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58867. return this._alphaRemapGradients;
  58868. };
  58869. /**
  58870. * Gets the current list of life time gradients.
  58871. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58872. * @returns the list of life time gradients
  58873. */
  58874. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58875. return this._lifeTimeGradients;
  58876. };
  58877. /**
  58878. * Gets the current list of angular speed gradients.
  58879. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58880. * @returns the list of angular speed gradients
  58881. */
  58882. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58883. return this._angularSpeedGradients;
  58884. };
  58885. /**
  58886. * Gets the current list of velocity gradients.
  58887. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58888. * @returns the list of velocity gradients
  58889. */
  58890. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58891. return this._velocityGradients;
  58892. };
  58893. /**
  58894. * Gets the current list of start size gradients.
  58895. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58896. * @returns the list of start size gradients
  58897. */
  58898. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58899. return this._startSizeGradients;
  58900. };
  58901. /**
  58902. * Gets the current list of emit rate gradients.
  58903. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58904. * @returns the list of emit rate gradients
  58905. */
  58906. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58907. return this._emitRateGradients;
  58908. };
  58909. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58910. /**
  58911. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58912. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58913. */
  58914. get: function () {
  58915. if (this.particleEmitterType.direction1) {
  58916. return this.particleEmitterType.direction1;
  58917. }
  58918. return BABYLON.Vector3.Zero();
  58919. },
  58920. set: function (value) {
  58921. if (this.particleEmitterType.direction1) {
  58922. this.particleEmitterType.direction1 = value;
  58923. }
  58924. },
  58925. enumerable: true,
  58926. configurable: true
  58927. });
  58928. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58929. /**
  58930. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58931. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58932. */
  58933. get: function () {
  58934. if (this.particleEmitterType.direction2) {
  58935. return this.particleEmitterType.direction2;
  58936. }
  58937. return BABYLON.Vector3.Zero();
  58938. },
  58939. set: function (value) {
  58940. if (this.particleEmitterType.direction2) {
  58941. this.particleEmitterType.direction2 = value;
  58942. }
  58943. },
  58944. enumerable: true,
  58945. configurable: true
  58946. });
  58947. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58948. /**
  58949. * 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.
  58950. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58951. */
  58952. get: function () {
  58953. if (this.particleEmitterType.minEmitBox) {
  58954. return this.particleEmitterType.minEmitBox;
  58955. }
  58956. return BABYLON.Vector3.Zero();
  58957. },
  58958. set: function (value) {
  58959. if (this.particleEmitterType.minEmitBox) {
  58960. this.particleEmitterType.minEmitBox = value;
  58961. }
  58962. },
  58963. enumerable: true,
  58964. configurable: true
  58965. });
  58966. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58967. /**
  58968. * 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.
  58969. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58970. */
  58971. get: function () {
  58972. if (this.particleEmitterType.maxEmitBox) {
  58973. return this.particleEmitterType.maxEmitBox;
  58974. }
  58975. return BABYLON.Vector3.Zero();
  58976. },
  58977. set: function (value) {
  58978. if (this.particleEmitterType.maxEmitBox) {
  58979. this.particleEmitterType.maxEmitBox = value;
  58980. }
  58981. },
  58982. enumerable: true,
  58983. configurable: true
  58984. });
  58985. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58986. /**
  58987. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58988. */
  58989. get: function () {
  58990. return this._isBillboardBased;
  58991. },
  58992. set: function (value) {
  58993. if (this._isBillboardBased === value) {
  58994. return;
  58995. }
  58996. this._isBillboardBased = value;
  58997. this._reset();
  58998. },
  58999. enumerable: true,
  59000. configurable: true
  59001. });
  59002. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  59003. /**
  59004. * Gets the image processing configuration used either in this material.
  59005. */
  59006. get: function () {
  59007. return this._imageProcessingConfiguration;
  59008. },
  59009. /**
  59010. * Sets the Default image processing configuration used either in the this material.
  59011. *
  59012. * If sets to null, the scene one is in use.
  59013. */
  59014. set: function (value) {
  59015. this._attachImageProcessingConfiguration(value);
  59016. },
  59017. enumerable: true,
  59018. configurable: true
  59019. });
  59020. /**
  59021. * Attaches a new image processing configuration to the Standard Material.
  59022. * @param configuration
  59023. */
  59024. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  59025. if (configuration === this._imageProcessingConfiguration) {
  59026. return;
  59027. }
  59028. // Pick the scene configuration if needed.
  59029. if (!configuration) {
  59030. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  59031. }
  59032. else {
  59033. this._imageProcessingConfiguration = configuration;
  59034. }
  59035. };
  59036. /** @hidden */
  59037. BaseParticleSystem.prototype._reset = function () {
  59038. };
  59039. /** @hidden */
  59040. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  59041. if (!gradients) {
  59042. return this;
  59043. }
  59044. var index = 0;
  59045. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59046. var valueGradient = gradients_1[_i];
  59047. if (valueGradient.gradient === gradient) {
  59048. gradients.splice(index, 1);
  59049. break;
  59050. }
  59051. index++;
  59052. }
  59053. if (texture) {
  59054. texture.dispose();
  59055. }
  59056. return this;
  59057. };
  59058. /**
  59059. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  59060. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  59061. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  59062. * @returns the emitter
  59063. */
  59064. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  59065. var particleEmitter = new BABYLON.PointParticleEmitter();
  59066. particleEmitter.direction1 = direction1;
  59067. particleEmitter.direction2 = direction2;
  59068. this.particleEmitterType = particleEmitter;
  59069. return particleEmitter;
  59070. };
  59071. /**
  59072. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  59073. * @param radius The radius of the hemisphere to emit from
  59074. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  59075. * @returns the emitter
  59076. */
  59077. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  59078. if (radius === void 0) { radius = 1; }
  59079. if (radiusRange === void 0) { radiusRange = 1; }
  59080. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  59081. this.particleEmitterType = particleEmitter;
  59082. return particleEmitter;
  59083. };
  59084. /**
  59085. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  59086. * @param radius The radius of the sphere to emit from
  59087. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  59088. * @returns the emitter
  59089. */
  59090. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  59091. if (radius === void 0) { radius = 1; }
  59092. if (radiusRange === void 0) { radiusRange = 1; }
  59093. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  59094. this.particleEmitterType = particleEmitter;
  59095. return particleEmitter;
  59096. };
  59097. /**
  59098. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  59099. * @param radius The radius of the sphere to emit from
  59100. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  59101. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  59102. * @returns the emitter
  59103. */
  59104. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  59105. if (radius === void 0) { radius = 1; }
  59106. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  59107. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  59108. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  59109. this.particleEmitterType = particleEmitter;
  59110. return particleEmitter;
  59111. };
  59112. /**
  59113. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  59114. * @param radius The radius of the emission cylinder
  59115. * @param height The height of the emission cylinder
  59116. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  59117. * @param directionRandomizer How much to randomize the particle direction [0-1]
  59118. * @returns the emitter
  59119. */
  59120. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  59121. if (radius === void 0) { radius = 1; }
  59122. if (height === void 0) { height = 1; }
  59123. if (radiusRange === void 0) { radiusRange = 1; }
  59124. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59125. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  59126. this.particleEmitterType = particleEmitter;
  59127. return particleEmitter;
  59128. };
  59129. /**
  59130. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  59131. * @param radius The radius of the cylinder to emit from
  59132. * @param height The height of the emission cylinder
  59133. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59134. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  59135. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  59136. * @returns the emitter
  59137. */
  59138. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  59139. if (radius === void 0) { radius = 1; }
  59140. if (height === void 0) { height = 1; }
  59141. if (radiusRange === void 0) { radiusRange = 1; }
  59142. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  59143. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  59144. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  59145. this.particleEmitterType = particleEmitter;
  59146. return particleEmitter;
  59147. };
  59148. /**
  59149. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  59150. * @param radius The radius of the cone to emit from
  59151. * @param angle The base angle of the cone
  59152. * @returns the emitter
  59153. */
  59154. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  59155. if (radius === void 0) { radius = 1; }
  59156. if (angle === void 0) { angle = Math.PI / 4; }
  59157. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  59158. this.particleEmitterType = particleEmitter;
  59159. return particleEmitter;
  59160. };
  59161. /**
  59162. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  59163. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  59164. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  59165. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  59166. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  59167. * @returns the emitter
  59168. */
  59169. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  59170. var particleEmitter = new BABYLON.BoxParticleEmitter();
  59171. this.particleEmitterType = particleEmitter;
  59172. this.direction1 = direction1;
  59173. this.direction2 = direction2;
  59174. this.minEmitBox = minEmitBox;
  59175. this.maxEmitBox = maxEmitBox;
  59176. return particleEmitter;
  59177. };
  59178. /**
  59179. * Source color is added to the destination color without alpha affecting the result
  59180. */
  59181. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  59182. /**
  59183. * Blend current color and particle color using particle’s alpha
  59184. */
  59185. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  59186. /**
  59187. * Add current color and particle color multiplied by particle’s alpha
  59188. */
  59189. BaseParticleSystem.BLENDMODE_ADD = 2;
  59190. /**
  59191. * Multiply current color with particle color
  59192. */
  59193. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  59194. /**
  59195. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  59196. */
  59197. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  59198. return BaseParticleSystem;
  59199. }());
  59200. BABYLON.BaseParticleSystem = BaseParticleSystem;
  59201. })(BABYLON || (BABYLON = {}));
  59202. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  59203. var BABYLON;
  59204. (function (BABYLON) {
  59205. /**
  59206. * This represents a particle system in Babylon.
  59207. * 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.
  59208. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59209. * @example https://doc.babylonjs.com/babylon101/particles
  59210. */
  59211. var ParticleSystem = /** @class */ (function (_super) {
  59212. __extends(ParticleSystem, _super);
  59213. /**
  59214. * Instantiates a particle system.
  59215. * 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.
  59216. * @param name The name of the particle system
  59217. * @param capacity The max number of particles alive at the same time
  59218. * @param scene The scene the particle system belongs to
  59219. * @param customEffect a custom effect used to change the way particles are rendered by default
  59220. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59221. * @param epsilon Offset used to render the particles
  59222. */
  59223. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  59224. if (customEffect === void 0) { customEffect = null; }
  59225. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59226. if (epsilon === void 0) { epsilon = 0.01; }
  59227. var _this = _super.call(this, name) || this;
  59228. /**
  59229. * @hidden
  59230. */
  59231. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  59232. /**
  59233. * An event triggered when the system is disposed
  59234. */
  59235. _this.onDisposeObservable = new BABYLON.Observable();
  59236. _this._particles = new Array();
  59237. _this._stockParticles = new Array();
  59238. _this._newPartsExcess = 0;
  59239. _this._vertexBuffers = {};
  59240. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  59241. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  59242. _this._scaledDirection = BABYLON.Vector3.Zero();
  59243. _this._scaledGravity = BABYLON.Vector3.Zero();
  59244. _this._currentRenderId = -1;
  59245. _this._useInstancing = false;
  59246. _this._started = false;
  59247. _this._stopped = false;
  59248. _this._actualFrame = 0;
  59249. /** @hidden */
  59250. _this._currentEmitRate1 = 0;
  59251. /** @hidden */
  59252. _this._currentEmitRate2 = 0;
  59253. /** @hidden */
  59254. _this._currentStartSize1 = 0;
  59255. /** @hidden */
  59256. _this._currentStartSize2 = 0;
  59257. _this._rawTextureWidth = 256;
  59258. _this._useRampGradients = false;
  59259. /**
  59260. * @hidden
  59261. * If the particle systems emitter should be disposed when the particle system is disposed
  59262. */
  59263. _this._disposeEmitterOnDispose = false;
  59264. // start of sub system methods
  59265. /**
  59266. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  59267. * Its lifetime will start back at 0.
  59268. */
  59269. _this.recycleParticle = function (particle) {
  59270. // move particle from activeParticle list to stock particles
  59271. var lastParticle = _this._particles.pop();
  59272. if (lastParticle !== particle) {
  59273. lastParticle.copyTo(particle);
  59274. }
  59275. _this._stockParticles.push(lastParticle);
  59276. };
  59277. _this._createParticle = function () {
  59278. var particle;
  59279. if (_this._stockParticles.length !== 0) {
  59280. particle = _this._stockParticles.pop();
  59281. particle._reset();
  59282. }
  59283. else {
  59284. particle = new BABYLON.Particle(_this);
  59285. }
  59286. // Attach emitters
  59287. if (_this._subEmitters && _this._subEmitters.length > 0) {
  59288. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  59289. particle._attachedSubEmitters = [];
  59290. subEmitters.forEach(function (subEmitter) {
  59291. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  59292. var newEmitter = subEmitter.clone();
  59293. particle._attachedSubEmitters.push(newEmitter);
  59294. newEmitter.particleSystem.start();
  59295. }
  59296. });
  59297. }
  59298. return particle;
  59299. };
  59300. _this._emitFromParticle = function (particle) {
  59301. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  59302. return;
  59303. }
  59304. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  59305. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  59306. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  59307. var subSystem = subEmitter.clone();
  59308. particle._inheritParticleInfoToSubEmitter(subSystem);
  59309. subSystem.particleSystem._rootParticleSystem = _this;
  59310. _this.activeSubSystems.push(subSystem.particleSystem);
  59311. subSystem.particleSystem.start();
  59312. }
  59313. });
  59314. };
  59315. _this._capacity = capacity;
  59316. _this._epsilon = epsilon;
  59317. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59318. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59319. // Setup the default processing configuration to the scene.
  59320. _this._attachImageProcessingConfiguration(null);
  59321. _this._customEffect = customEffect;
  59322. _this._scene.particleSystems.push(_this);
  59323. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  59324. _this._createIndexBuffer();
  59325. _this._createVertexBuffers();
  59326. // Default emitter type
  59327. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59328. // Update
  59329. _this.updateFunction = function (particles) {
  59330. var noiseTextureSize = null;
  59331. var noiseTextureData = null;
  59332. if (_this.noiseTexture) { // We need to get texture data back to CPU
  59333. noiseTextureSize = _this.noiseTexture.getSize();
  59334. noiseTextureData = (_this.noiseTexture.getContent());
  59335. }
  59336. var _loop_1 = function () {
  59337. particle = particles[index];
  59338. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  59339. var previousAge = particle.age;
  59340. particle.age += scaledUpdateSpeed;
  59341. // Evaluate step to death
  59342. if (particle.age > particle.lifeTime) {
  59343. var diff = particle.age - previousAge;
  59344. var oldDiff = particle.lifeTime - previousAge;
  59345. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  59346. particle.age = particle.lifeTime;
  59347. }
  59348. var ratio = particle.age / particle.lifeTime;
  59349. // Color
  59350. if (_this._colorGradients && _this._colorGradients.length > 0) {
  59351. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  59352. if (currentGradient !== particle._currentColorGradient) {
  59353. particle._currentColor1.copyFrom(particle._currentColor2);
  59354. nextGradient.getColorToRef(particle._currentColor2);
  59355. particle._currentColorGradient = currentGradient;
  59356. }
  59357. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  59358. });
  59359. }
  59360. else {
  59361. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  59362. particle.color.addInPlace(_this._scaledColorStep);
  59363. if (particle.color.a < 0) {
  59364. particle.color.a = 0;
  59365. }
  59366. }
  59367. // Angular speed
  59368. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  59369. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  59370. if (currentGradient !== particle._currentAngularSpeedGradient) {
  59371. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  59372. particle._currentAngularSpeed2 = nextGradient.getFactor();
  59373. particle._currentAngularSpeedGradient = currentGradient;
  59374. }
  59375. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  59376. });
  59377. }
  59378. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  59379. // Direction
  59380. var directionScale = scaledUpdateSpeed;
  59381. /// Velocity
  59382. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  59383. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  59384. if (currentGradient !== particle._currentVelocityGradient) {
  59385. particle._currentVelocity1 = particle._currentVelocity2;
  59386. particle._currentVelocity2 = nextGradient.getFactor();
  59387. particle._currentVelocityGradient = currentGradient;
  59388. }
  59389. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  59390. });
  59391. }
  59392. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  59393. /// Limit velocity
  59394. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  59395. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  59396. if (currentGradient !== particle._currentLimitVelocityGradient) {
  59397. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  59398. particle._currentLimitVelocity2 = nextGradient.getFactor();
  59399. particle._currentLimitVelocityGradient = currentGradient;
  59400. }
  59401. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  59402. var currentVelocity = particle.direction.length();
  59403. if (currentVelocity > limitVelocity) {
  59404. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  59405. }
  59406. });
  59407. }
  59408. /// Drag
  59409. if (_this._dragGradients && _this._dragGradients.length > 0) {
  59410. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  59411. if (currentGradient !== particle._currentDragGradient) {
  59412. particle._currentDrag1 = particle._currentDrag2;
  59413. particle._currentDrag2 = nextGradient.getFactor();
  59414. particle._currentDragGradient = currentGradient;
  59415. }
  59416. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  59417. _this._scaledDirection.scaleInPlace(1.0 - drag);
  59418. });
  59419. }
  59420. particle.position.addInPlace(_this._scaledDirection);
  59421. // Noise
  59422. if (noiseTextureData && noiseTextureSize) {
  59423. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59424. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59425. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59426. var force = BABYLON.Tmp.Vector3[0];
  59427. var scaledForce = BABYLON.Tmp.Vector3[1];
  59428. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  59429. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  59430. particle.direction.addInPlace(scaledForce);
  59431. }
  59432. // Gravity
  59433. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  59434. particle.direction.addInPlace(_this._scaledGravity);
  59435. // Size
  59436. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  59437. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  59438. if (currentGradient !== particle._currentSizeGradient) {
  59439. particle._currentSize1 = particle._currentSize2;
  59440. particle._currentSize2 = nextGradient.getFactor();
  59441. particle._currentSizeGradient = currentGradient;
  59442. }
  59443. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  59444. });
  59445. }
  59446. // Remap data
  59447. if (_this._useRampGradients) {
  59448. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  59449. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  59450. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59451. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59452. particle.remapData.x = min;
  59453. particle.remapData.y = max - min;
  59454. });
  59455. }
  59456. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  59457. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  59458. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59459. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59460. particle.remapData.z = min;
  59461. particle.remapData.w = max - min;
  59462. });
  59463. }
  59464. }
  59465. if (_this._isAnimationSheetEnabled) {
  59466. particle.updateCellIndex();
  59467. }
  59468. // Update the position of the attached sub-emitters to match their attached particle
  59469. particle._inheritParticleInfoToSubEmitters();
  59470. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  59471. _this._emitFromParticle(particle);
  59472. if (particle._attachedSubEmitters) {
  59473. particle._attachedSubEmitters.forEach(function (subEmitter) {
  59474. subEmitter.particleSystem.disposeOnStop = true;
  59475. subEmitter.particleSystem.stop();
  59476. });
  59477. particle._attachedSubEmitters = null;
  59478. }
  59479. _this.recycleParticle(particle);
  59480. index--;
  59481. return "continue";
  59482. }
  59483. };
  59484. var particle;
  59485. for (var index = 0; index < particles.length; index++) {
  59486. _loop_1();
  59487. }
  59488. };
  59489. return _this;
  59490. }
  59491. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  59492. /**
  59493. * Sets a callback that will be triggered when the system is disposed
  59494. */
  59495. set: function (callback) {
  59496. if (this._onDisposeObserver) {
  59497. this.onDisposeObservable.remove(this._onDisposeObserver);
  59498. }
  59499. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  59500. },
  59501. enumerable: true,
  59502. configurable: true
  59503. });
  59504. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  59505. /** Gets or sets a boolean indicating that ramp gradients must be used
  59506. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  59507. */
  59508. get: function () {
  59509. return this._useRampGradients;
  59510. },
  59511. set: function (value) {
  59512. if (this._useRampGradients === value) {
  59513. return;
  59514. }
  59515. this._useRampGradients = value;
  59516. this._resetEffect();
  59517. },
  59518. enumerable: true,
  59519. configurable: true
  59520. });
  59521. Object.defineProperty(ParticleSystem.prototype, "particles", {
  59522. //end of Sub-emitter
  59523. /**
  59524. * Gets the current list of active particles
  59525. */
  59526. get: function () {
  59527. return this._particles;
  59528. },
  59529. enumerable: true,
  59530. configurable: true
  59531. });
  59532. /**
  59533. * Returns the string "ParticleSystem"
  59534. * @returns a string containing the class name
  59535. */
  59536. ParticleSystem.prototype.getClassName = function () {
  59537. return "ParticleSystem";
  59538. };
  59539. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  59540. var newGradient = new BABYLON.FactorGradient();
  59541. newGradient.gradient = gradient;
  59542. newGradient.factor1 = factor;
  59543. newGradient.factor2 = factor2;
  59544. factorGradients.push(newGradient);
  59545. factorGradients.sort(function (a, b) {
  59546. if (a.gradient < b.gradient) {
  59547. return -1;
  59548. }
  59549. else if (a.gradient > b.gradient) {
  59550. return 1;
  59551. }
  59552. return 0;
  59553. });
  59554. };
  59555. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  59556. if (!factorGradients) {
  59557. return;
  59558. }
  59559. var index = 0;
  59560. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  59561. var factorGradient = factorGradients_1[_i];
  59562. if (factorGradient.gradient === gradient) {
  59563. factorGradients.splice(index, 1);
  59564. break;
  59565. }
  59566. index++;
  59567. }
  59568. };
  59569. /**
  59570. * Adds a new life time gradient
  59571. * @param gradient defines the gradient to use (between 0 and 1)
  59572. * @param factor defines the life time factor to affect to the specified gradient
  59573. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59574. * @returns the current particle system
  59575. */
  59576. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  59577. if (!this._lifeTimeGradients) {
  59578. this._lifeTimeGradients = [];
  59579. }
  59580. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  59581. return this;
  59582. };
  59583. /**
  59584. * Remove a specific life time gradient
  59585. * @param gradient defines the gradient to remove
  59586. * @returns the current particle system
  59587. */
  59588. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  59589. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  59590. return this;
  59591. };
  59592. /**
  59593. * Adds a new size gradient
  59594. * @param gradient defines the gradient to use (between 0 and 1)
  59595. * @param factor defines the size factor to affect to the specified gradient
  59596. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59597. * @returns the current particle system
  59598. */
  59599. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  59600. if (!this._sizeGradients) {
  59601. this._sizeGradients = [];
  59602. }
  59603. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  59604. return this;
  59605. };
  59606. /**
  59607. * Remove a specific size gradient
  59608. * @param gradient defines the gradient to remove
  59609. * @returns the current particle system
  59610. */
  59611. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59612. this._removeFactorGradient(this._sizeGradients, gradient);
  59613. return this;
  59614. };
  59615. /**
  59616. * Adds a new color remap gradient
  59617. * @param gradient defines the gradient to use (between 0 and 1)
  59618. * @param min defines the color remap minimal range
  59619. * @param max defines the color remap maximal range
  59620. * @returns the current particle system
  59621. */
  59622. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  59623. if (!this._colorRemapGradients) {
  59624. this._colorRemapGradients = [];
  59625. }
  59626. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  59627. return this;
  59628. };
  59629. /**
  59630. * Remove a specific color remap gradient
  59631. * @param gradient defines the gradient to remove
  59632. * @returns the current particle system
  59633. */
  59634. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  59635. this._removeFactorGradient(this._colorRemapGradients, gradient);
  59636. return this;
  59637. };
  59638. /**
  59639. * Adds a new alpha remap gradient
  59640. * @param gradient defines the gradient to use (between 0 and 1)
  59641. * @param min defines the alpha remap minimal range
  59642. * @param max defines the alpha remap maximal range
  59643. * @returns the current particle system
  59644. */
  59645. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  59646. if (!this._alphaRemapGradients) {
  59647. this._alphaRemapGradients = [];
  59648. }
  59649. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  59650. return this;
  59651. };
  59652. /**
  59653. * Remove a specific alpha remap gradient
  59654. * @param gradient defines the gradient to remove
  59655. * @returns the current particle system
  59656. */
  59657. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  59658. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  59659. return this;
  59660. };
  59661. /**
  59662. * Adds a new angular speed gradient
  59663. * @param gradient defines the gradient to use (between 0 and 1)
  59664. * @param factor defines the angular speed to affect to the specified gradient
  59665. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59666. * @returns the current particle system
  59667. */
  59668. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  59669. if (!this._angularSpeedGradients) {
  59670. this._angularSpeedGradients = [];
  59671. }
  59672. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  59673. return this;
  59674. };
  59675. /**
  59676. * Remove a specific angular speed gradient
  59677. * @param gradient defines the gradient to remove
  59678. * @returns the current particle system
  59679. */
  59680. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59681. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  59682. return this;
  59683. };
  59684. /**
  59685. * Adds a new velocity gradient
  59686. * @param gradient defines the gradient to use (between 0 and 1)
  59687. * @param factor defines the velocity to affect to the specified gradient
  59688. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59689. * @returns the current particle system
  59690. */
  59691. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  59692. if (!this._velocityGradients) {
  59693. this._velocityGradients = [];
  59694. }
  59695. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  59696. return this;
  59697. };
  59698. /**
  59699. * Remove a specific velocity gradient
  59700. * @param gradient defines the gradient to remove
  59701. * @returns the current particle system
  59702. */
  59703. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59704. this._removeFactorGradient(this._velocityGradients, gradient);
  59705. return this;
  59706. };
  59707. /**
  59708. * Adds a new limit velocity gradient
  59709. * @param gradient defines the gradient to use (between 0 and 1)
  59710. * @param factor defines the limit velocity value to affect to the specified gradient
  59711. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59712. * @returns the current particle system
  59713. */
  59714. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  59715. if (!this._limitVelocityGradients) {
  59716. this._limitVelocityGradients = [];
  59717. }
  59718. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  59719. return this;
  59720. };
  59721. /**
  59722. * Remove a specific limit velocity gradient
  59723. * @param gradient defines the gradient to remove
  59724. * @returns the current particle system
  59725. */
  59726. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  59727. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  59728. return this;
  59729. };
  59730. /**
  59731. * Adds a new drag gradient
  59732. * @param gradient defines the gradient to use (between 0 and 1)
  59733. * @param factor defines the drag value to affect to the specified gradient
  59734. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59735. * @returns the current particle system
  59736. */
  59737. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  59738. if (!this._dragGradients) {
  59739. this._dragGradients = [];
  59740. }
  59741. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  59742. return this;
  59743. };
  59744. /**
  59745. * Remove a specific drag gradient
  59746. * @param gradient defines the gradient to remove
  59747. * @returns the current particle system
  59748. */
  59749. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  59750. this._removeFactorGradient(this._dragGradients, gradient);
  59751. return this;
  59752. };
  59753. /**
  59754. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  59755. * @param gradient defines the gradient to use (between 0 and 1)
  59756. * @param factor defines the emit rate value to affect to the specified gradient
  59757. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59758. * @returns the current particle system
  59759. */
  59760. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  59761. if (!this._emitRateGradients) {
  59762. this._emitRateGradients = [];
  59763. }
  59764. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  59765. return this;
  59766. };
  59767. /**
  59768. * Remove a specific emit rate gradient
  59769. * @param gradient defines the gradient to remove
  59770. * @returns the current particle system
  59771. */
  59772. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  59773. this._removeFactorGradient(this._emitRateGradients, gradient);
  59774. return this;
  59775. };
  59776. /**
  59777. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  59778. * @param gradient defines the gradient to use (between 0 and 1)
  59779. * @param factor defines the start size value to affect to the specified gradient
  59780. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59781. * @returns the current particle system
  59782. */
  59783. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  59784. if (!this._startSizeGradients) {
  59785. this._startSizeGradients = [];
  59786. }
  59787. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  59788. return this;
  59789. };
  59790. /**
  59791. * Remove a specific start size gradient
  59792. * @param gradient defines the gradient to remove
  59793. * @returns the current particle system
  59794. */
  59795. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  59796. this._removeFactorGradient(this._emitRateGradients, gradient);
  59797. return this;
  59798. };
  59799. ParticleSystem.prototype._createRampGradientTexture = function () {
  59800. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  59801. return;
  59802. }
  59803. var data = new Uint8Array(this._rawTextureWidth * 4);
  59804. var tmpColor = BABYLON.Tmp.Color3[0];
  59805. for (var x = 0; x < this._rawTextureWidth; x++) {
  59806. var ratio = x / this._rawTextureWidth;
  59807. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  59808. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  59809. data[x * 4] = tmpColor.r * 255;
  59810. data[x * 4 + 1] = tmpColor.g * 255;
  59811. data[x * 4 + 2] = tmpColor.b * 255;
  59812. data[x * 4 + 3] = 255;
  59813. });
  59814. }
  59815. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59816. };
  59817. /**
  59818. * Gets the current list of ramp gradients.
  59819. * You must use addRampGradient and removeRampGradient to udpate this list
  59820. * @returns the list of ramp gradients
  59821. */
  59822. ParticleSystem.prototype.getRampGradients = function () {
  59823. return this._rampGradients;
  59824. };
  59825. /**
  59826. * Adds a new ramp gradient used to remap particle colors
  59827. * @param gradient defines the gradient to use (between 0 and 1)
  59828. * @param color defines the color to affect to the specified gradient
  59829. * @returns the current particle system
  59830. */
  59831. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  59832. if (!this._rampGradients) {
  59833. this._rampGradients = [];
  59834. }
  59835. var rampGradient = new BABYLON.Color3Gradient();
  59836. rampGradient.gradient = gradient;
  59837. rampGradient.color = color;
  59838. this._rampGradients.push(rampGradient);
  59839. this._rampGradients.sort(function (a, b) {
  59840. if (a.gradient < b.gradient) {
  59841. return -1;
  59842. }
  59843. else if (a.gradient > b.gradient) {
  59844. return 1;
  59845. }
  59846. return 0;
  59847. });
  59848. if (this._rampGradientsTexture) {
  59849. this._rampGradientsTexture.dispose();
  59850. this._rampGradientsTexture = null;
  59851. }
  59852. this._createRampGradientTexture();
  59853. return this;
  59854. };
  59855. /**
  59856. * Remove a specific ramp gradient
  59857. * @param gradient defines the gradient to remove
  59858. * @returns the current particle system
  59859. */
  59860. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59861. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59862. this._rampGradientsTexture = null;
  59863. if (this._rampGradients && this._rampGradients.length > 0) {
  59864. this._createRampGradientTexture();
  59865. }
  59866. return this;
  59867. };
  59868. /**
  59869. * Adds a new color gradient
  59870. * @param gradient defines the gradient to use (between 0 and 1)
  59871. * @param color1 defines the color to affect to the specified gradient
  59872. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59873. * @returns this particle system
  59874. */
  59875. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59876. if (!this._colorGradients) {
  59877. this._colorGradients = [];
  59878. }
  59879. var colorGradient = new BABYLON.ColorGradient();
  59880. colorGradient.gradient = gradient;
  59881. colorGradient.color1 = color1;
  59882. colorGradient.color2 = color2;
  59883. this._colorGradients.push(colorGradient);
  59884. this._colorGradients.sort(function (a, b) {
  59885. if (a.gradient < b.gradient) {
  59886. return -1;
  59887. }
  59888. else if (a.gradient > b.gradient) {
  59889. return 1;
  59890. }
  59891. return 0;
  59892. });
  59893. return this;
  59894. };
  59895. /**
  59896. * Remove a specific color gradient
  59897. * @param gradient defines the gradient to remove
  59898. * @returns this particle system
  59899. */
  59900. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59901. if (!this._colorGradients) {
  59902. return this;
  59903. }
  59904. var index = 0;
  59905. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59906. var colorGradient = _a[_i];
  59907. if (colorGradient.gradient === gradient) {
  59908. this._colorGradients.splice(index, 1);
  59909. break;
  59910. }
  59911. index++;
  59912. }
  59913. return this;
  59914. };
  59915. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59916. u = Math.abs(u) * 0.5 + 0.5;
  59917. v = Math.abs(v) * 0.5 + 0.5;
  59918. var wrappedU = ((u * width) % width) | 0;
  59919. var wrappedV = ((v * height) % height) | 0;
  59920. var position = (wrappedU + wrappedV * width) * 4;
  59921. return pixels[position] / 255;
  59922. };
  59923. ParticleSystem.prototype._reset = function () {
  59924. this._resetEffect();
  59925. };
  59926. ParticleSystem.prototype._resetEffect = function () {
  59927. if (this._vertexBuffer) {
  59928. this._vertexBuffer.dispose();
  59929. this._vertexBuffer = null;
  59930. }
  59931. if (this._spriteBuffer) {
  59932. this._spriteBuffer.dispose();
  59933. this._spriteBuffer = null;
  59934. }
  59935. this._createVertexBuffers();
  59936. };
  59937. ParticleSystem.prototype._createVertexBuffers = function () {
  59938. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59939. if (this._isAnimationSheetEnabled) {
  59940. this._vertexBufferSize += 1;
  59941. }
  59942. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59943. this._vertexBufferSize += 3;
  59944. }
  59945. if (this._useRampGradients) {
  59946. this._vertexBufferSize += 4;
  59947. }
  59948. var engine = this._scene.getEngine();
  59949. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59950. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59951. var dataOffset = 0;
  59952. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59953. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59954. dataOffset += 3;
  59955. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59956. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59957. dataOffset += 4;
  59958. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59959. this._vertexBuffers["angle"] = options;
  59960. dataOffset += 1;
  59961. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59962. this._vertexBuffers["size"] = size;
  59963. dataOffset += 2;
  59964. if (this._isAnimationSheetEnabled) {
  59965. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59966. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59967. dataOffset += 1;
  59968. }
  59969. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59970. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59971. this._vertexBuffers["direction"] = directionBuffer;
  59972. dataOffset += 3;
  59973. }
  59974. if (this._useRampGradients) {
  59975. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59976. this._vertexBuffers["remapData"] = rampDataBuffer;
  59977. dataOffset += 4;
  59978. }
  59979. var offsets;
  59980. if (this._useInstancing) {
  59981. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59982. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59983. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59984. }
  59985. else {
  59986. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59987. dataOffset += 2;
  59988. }
  59989. this._vertexBuffers["offset"] = offsets;
  59990. };
  59991. ParticleSystem.prototype._createIndexBuffer = function () {
  59992. if (this._useInstancing) {
  59993. return;
  59994. }
  59995. var indices = [];
  59996. var index = 0;
  59997. for (var count = 0; count < this._capacity; count++) {
  59998. indices.push(index);
  59999. indices.push(index + 1);
  60000. indices.push(index + 2);
  60001. indices.push(index);
  60002. indices.push(index + 2);
  60003. indices.push(index + 3);
  60004. index += 4;
  60005. }
  60006. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  60007. };
  60008. /**
  60009. * Gets the maximum number of particles active at the same time.
  60010. * @returns The max number of active particles.
  60011. */
  60012. ParticleSystem.prototype.getCapacity = function () {
  60013. return this._capacity;
  60014. };
  60015. /**
  60016. * Gets whether there are still active particles in the system.
  60017. * @returns True if it is alive, otherwise false.
  60018. */
  60019. ParticleSystem.prototype.isAlive = function () {
  60020. return this._alive;
  60021. };
  60022. /**
  60023. * Gets if the system has been started. (Note: this will still be true after stop is called)
  60024. * @returns True if it has been started, otherwise false.
  60025. */
  60026. ParticleSystem.prototype.isStarted = function () {
  60027. return this._started;
  60028. };
  60029. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  60030. var _this = this;
  60031. this._subEmitters = new Array();
  60032. if (this.subEmitters) {
  60033. this.subEmitters.forEach(function (subEmitter) {
  60034. if (subEmitter instanceof ParticleSystem) {
  60035. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  60036. }
  60037. else if (subEmitter instanceof BABYLON.SubEmitter) {
  60038. _this._subEmitters.push([subEmitter]);
  60039. }
  60040. else if (subEmitter instanceof Array) {
  60041. _this._subEmitters.push(subEmitter);
  60042. }
  60043. });
  60044. }
  60045. };
  60046. /**
  60047. * Starts the particle system and begins to emit
  60048. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  60049. */
  60050. ParticleSystem.prototype.start = function (delay) {
  60051. var _this = this;
  60052. if (delay === void 0) { delay = this.startDelay; }
  60053. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  60054. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  60055. }
  60056. if (delay) {
  60057. setTimeout(function () {
  60058. _this.start(0);
  60059. }, delay);
  60060. return;
  60061. }
  60062. // Convert the subEmitters field to the constant type field _subEmitters
  60063. this._prepareSubEmitterInternalArray();
  60064. this._started = true;
  60065. this._stopped = false;
  60066. this._actualFrame = 0;
  60067. if (this._subEmitters && this._subEmitters.length != 0) {
  60068. this.activeSubSystems = new Array();
  60069. }
  60070. // Reset emit gradient so it acts the same on every start
  60071. if (this._emitRateGradients) {
  60072. if (this._emitRateGradients.length > 0) {
  60073. this._currentEmitRateGradient = this._emitRateGradients[0];
  60074. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  60075. this._currentEmitRate2 = this._currentEmitRate1;
  60076. }
  60077. if (this._emitRateGradients.length > 1) {
  60078. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  60079. }
  60080. }
  60081. // Reset start size gradient so it acts the same on every start
  60082. if (this._startSizeGradients) {
  60083. if (this._startSizeGradients.length > 0) {
  60084. this._currentStartSizeGradient = this._startSizeGradients[0];
  60085. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  60086. this._currentStartSize2 = this._currentStartSize1;
  60087. }
  60088. if (this._startSizeGradients.length > 1) {
  60089. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  60090. }
  60091. }
  60092. if (this.preWarmCycles) {
  60093. if (this.emitter instanceof BABYLON.AbstractMesh) {
  60094. this.emitter.computeWorldMatrix(true);
  60095. }
  60096. var noiseTextureAsProcedural_1 = this.noiseTexture;
  60097. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  60098. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  60099. setTimeout(function () {
  60100. for (var index = 0; index < _this.preWarmCycles; index++) {
  60101. _this.animate(true);
  60102. noiseTextureAsProcedural_1.render();
  60103. }
  60104. });
  60105. });
  60106. }
  60107. else {
  60108. for (var index = 0; index < this.preWarmCycles; index++) {
  60109. this.animate(true);
  60110. }
  60111. }
  60112. }
  60113. // Animations
  60114. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  60115. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  60116. }
  60117. };
  60118. /**
  60119. * Stops the particle system.
  60120. * @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.
  60121. */
  60122. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  60123. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  60124. this._stopped = true;
  60125. if (stopSubEmitters) {
  60126. this._stopSubEmitters();
  60127. }
  60128. };
  60129. // animation sheet
  60130. /**
  60131. * Remove all active particles
  60132. */
  60133. ParticleSystem.prototype.reset = function () {
  60134. this._stockParticles = [];
  60135. this._particles = [];
  60136. };
  60137. /**
  60138. * @hidden (for internal use only)
  60139. */
  60140. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  60141. var offset = index * this._vertexBufferSize;
  60142. this._vertexData[offset++] = particle.position.x;
  60143. this._vertexData[offset++] = particle.position.y;
  60144. this._vertexData[offset++] = particle.position.z;
  60145. this._vertexData[offset++] = particle.color.r;
  60146. this._vertexData[offset++] = particle.color.g;
  60147. this._vertexData[offset++] = particle.color.b;
  60148. this._vertexData[offset++] = particle.color.a;
  60149. this._vertexData[offset++] = particle.angle;
  60150. this._vertexData[offset++] = particle.scale.x * particle.size;
  60151. this._vertexData[offset++] = particle.scale.y * particle.size;
  60152. if (this._isAnimationSheetEnabled) {
  60153. this._vertexData[offset++] = particle.cellIndex;
  60154. }
  60155. if (!this._isBillboardBased) {
  60156. if (particle._initialDirection) {
  60157. this._vertexData[offset++] = particle._initialDirection.x;
  60158. this._vertexData[offset++] = particle._initialDirection.y;
  60159. this._vertexData[offset++] = particle._initialDirection.z;
  60160. }
  60161. else {
  60162. this._vertexData[offset++] = particle.direction.x;
  60163. this._vertexData[offset++] = particle.direction.y;
  60164. this._vertexData[offset++] = particle.direction.z;
  60165. }
  60166. }
  60167. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  60168. this._vertexData[offset++] = particle.direction.x;
  60169. this._vertexData[offset++] = particle.direction.y;
  60170. this._vertexData[offset++] = particle.direction.z;
  60171. }
  60172. if (this._useRampGradients) {
  60173. this._vertexData[offset++] = particle.remapData.x;
  60174. this._vertexData[offset++] = particle.remapData.y;
  60175. this._vertexData[offset++] = particle.remapData.z;
  60176. this._vertexData[offset++] = particle.remapData.w;
  60177. }
  60178. if (!this._useInstancing) {
  60179. if (this._isAnimationSheetEnabled) {
  60180. if (offsetX === 0) {
  60181. offsetX = this._epsilon;
  60182. }
  60183. else if (offsetX === 1) {
  60184. offsetX = 1 - this._epsilon;
  60185. }
  60186. if (offsetY === 0) {
  60187. offsetY = this._epsilon;
  60188. }
  60189. else if (offsetY === 1) {
  60190. offsetY = 1 - this._epsilon;
  60191. }
  60192. }
  60193. this._vertexData[offset++] = offsetX;
  60194. this._vertexData[offset++] = offsetY;
  60195. }
  60196. };
  60197. ParticleSystem.prototype._stopSubEmitters = function () {
  60198. if (!this.activeSubSystems) {
  60199. return;
  60200. }
  60201. this.activeSubSystems.forEach(function (subSystem) {
  60202. subSystem.stop(true);
  60203. });
  60204. this.activeSubSystems = new Array();
  60205. };
  60206. ParticleSystem.prototype._removeFromRoot = function () {
  60207. if (!this._rootParticleSystem) {
  60208. return;
  60209. }
  60210. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  60211. if (index !== -1) {
  60212. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  60213. }
  60214. this._rootParticleSystem = null;
  60215. };
  60216. // End of sub system methods
  60217. ParticleSystem.prototype._update = function (newParticles) {
  60218. var _this = this;
  60219. // Update current
  60220. this._alive = this._particles.length > 0;
  60221. if (this.emitter.position) {
  60222. var emitterMesh = this.emitter;
  60223. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  60224. }
  60225. else {
  60226. var emitterPosition = this.emitter;
  60227. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60228. }
  60229. this.updateFunction(this._particles);
  60230. // Add new ones
  60231. var particle;
  60232. var _loop_2 = function () {
  60233. if (this_1._particles.length === this_1._capacity) {
  60234. return "break";
  60235. }
  60236. particle = this_1._createParticle();
  60237. this_1._particles.push(particle);
  60238. // Emitter
  60239. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  60240. if (this_1.startPositionFunction) {
  60241. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  60242. }
  60243. else {
  60244. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  60245. }
  60246. if (this_1.startDirectionFunction) {
  60247. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60248. }
  60249. else {
  60250. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60251. }
  60252. if (emitPower === 0) {
  60253. if (!particle._initialDirection) {
  60254. particle._initialDirection = particle.direction.clone();
  60255. }
  60256. else {
  60257. particle._initialDirection.copyFrom(particle.direction);
  60258. }
  60259. }
  60260. else {
  60261. particle._initialDirection = null;
  60262. }
  60263. particle.direction.scaleInPlace(emitPower);
  60264. // Life time
  60265. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  60266. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  60267. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  60268. var factorGradient1 = currentGradient;
  60269. var factorGradient2 = nextGradient;
  60270. var lifeTime1 = factorGradient1.getFactor();
  60271. var lifeTime2 = factorGradient2.getFactor();
  60272. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  60273. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  60274. });
  60275. }
  60276. else {
  60277. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  60278. }
  60279. // Size
  60280. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  60281. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  60282. }
  60283. else {
  60284. particle._currentSizeGradient = this_1._sizeGradients[0];
  60285. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  60286. particle.size = particle._currentSize1;
  60287. if (this_1._sizeGradients.length > 1) {
  60288. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  60289. }
  60290. else {
  60291. particle._currentSize2 = particle._currentSize1;
  60292. }
  60293. }
  60294. // Size and scale
  60295. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  60296. // Adjust scale by start size
  60297. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  60298. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  60299. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  60300. if (currentGradient !== _this._currentStartSizeGradient) {
  60301. _this._currentStartSize1 = _this._currentStartSize2;
  60302. _this._currentStartSize2 = nextGradient.getFactor();
  60303. _this._currentStartSizeGradient = currentGradient;
  60304. }
  60305. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  60306. particle.scale.scaleInPlace(value);
  60307. });
  60308. }
  60309. // Angle
  60310. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  60311. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  60312. }
  60313. else {
  60314. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  60315. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  60316. particle._currentAngularSpeed1 = particle.angularSpeed;
  60317. if (this_1._angularSpeedGradients.length > 1) {
  60318. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  60319. }
  60320. else {
  60321. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  60322. }
  60323. }
  60324. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  60325. // Velocity
  60326. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  60327. particle._currentVelocityGradient = this_1._velocityGradients[0];
  60328. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  60329. if (this_1._velocityGradients.length > 1) {
  60330. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  60331. }
  60332. else {
  60333. particle._currentVelocity2 = particle._currentVelocity1;
  60334. }
  60335. }
  60336. // Limit velocity
  60337. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  60338. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  60339. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  60340. if (this_1._limitVelocityGradients.length > 1) {
  60341. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  60342. }
  60343. else {
  60344. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  60345. }
  60346. }
  60347. // Drag
  60348. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  60349. particle._currentDragGradient = this_1._dragGradients[0];
  60350. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  60351. if (this_1._dragGradients.length > 1) {
  60352. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  60353. }
  60354. else {
  60355. particle._currentDrag2 = particle._currentDrag1;
  60356. }
  60357. }
  60358. // Color
  60359. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  60360. step = BABYLON.Scalar.RandomRange(0, 1.0);
  60361. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  60362. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  60363. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  60364. }
  60365. else {
  60366. particle._currentColorGradient = this_1._colorGradients[0];
  60367. particle._currentColorGradient.getColorToRef(particle.color);
  60368. particle._currentColor1.copyFrom(particle.color);
  60369. if (this_1._colorGradients.length > 1) {
  60370. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  60371. }
  60372. else {
  60373. particle._currentColor2.copyFrom(particle.color);
  60374. }
  60375. }
  60376. // Sheet
  60377. if (this_1._isAnimationSheetEnabled) {
  60378. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  60379. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  60380. }
  60381. // Inherited Velocity
  60382. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  60383. // Ramp
  60384. if (this_1._useRampGradients) {
  60385. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  60386. }
  60387. // Noise texture coordinates
  60388. if (this_1.noiseTexture) {
  60389. if (particle._randomNoiseCoordinates1) {
  60390. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  60391. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  60392. }
  60393. else {
  60394. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60395. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60396. }
  60397. }
  60398. // Update the position of the attached sub-emitters to match their attached particle
  60399. particle._inheritParticleInfoToSubEmitters();
  60400. };
  60401. var this_1 = this, step;
  60402. for (var index = 0; index < newParticles; index++) {
  60403. var state_1 = _loop_2();
  60404. if (state_1 === "break")
  60405. break;
  60406. }
  60407. };
  60408. /** @hidden */
  60409. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  60410. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60411. if (isBillboardBased === void 0) { isBillboardBased = false; }
  60412. if (useRampGradients === void 0) { useRampGradients = false; }
  60413. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  60414. if (isAnimationSheetEnabled) {
  60415. attributeNamesOrOptions.push("cellIndex");
  60416. }
  60417. if (!isBillboardBased) {
  60418. attributeNamesOrOptions.push("direction");
  60419. }
  60420. if (useRampGradients) {
  60421. attributeNamesOrOptions.push("remapData");
  60422. }
  60423. return attributeNamesOrOptions;
  60424. };
  60425. /** @hidden */
  60426. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  60427. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60428. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  60429. if (isAnimationSheetEnabled) {
  60430. effectCreationOption.push("particlesInfos");
  60431. }
  60432. return effectCreationOption;
  60433. };
  60434. /** @hidden */
  60435. ParticleSystem.prototype._getEffect = function (blendMode) {
  60436. if (this._customEffect) {
  60437. return this._customEffect;
  60438. }
  60439. var defines = [];
  60440. if (this._scene.clipPlane) {
  60441. defines.push("#define CLIPPLANE");
  60442. }
  60443. if (this._scene.clipPlane2) {
  60444. defines.push("#define CLIPPLANE2");
  60445. }
  60446. if (this._scene.clipPlane3) {
  60447. defines.push("#define CLIPPLANE3");
  60448. }
  60449. if (this._scene.clipPlane4) {
  60450. defines.push("#define CLIPPLANE4");
  60451. }
  60452. if (this._isAnimationSheetEnabled) {
  60453. defines.push("#define ANIMATESHEET");
  60454. }
  60455. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  60456. defines.push("#define BLENDMULTIPLYMODE");
  60457. }
  60458. if (this._useRampGradients) {
  60459. defines.push("#define RAMPGRADIENT");
  60460. }
  60461. if (this._isBillboardBased) {
  60462. defines.push("#define BILLBOARD");
  60463. switch (this.billboardMode) {
  60464. case ParticleSystem.BILLBOARDMODE_Y:
  60465. defines.push("#define BILLBOARDY");
  60466. break;
  60467. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  60468. defines.push("#define BILLBOARDSTRETCHED");
  60469. break;
  60470. case ParticleSystem.BILLBOARDMODE_ALL:
  60471. default:
  60472. break;
  60473. }
  60474. }
  60475. if (this._imageProcessingConfiguration) {
  60476. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  60477. defines.push(this._imageProcessingConfigurationDefines.toString());
  60478. }
  60479. // Effect
  60480. var join = defines.join("\n");
  60481. if (this._cachedDefines !== join) {
  60482. this._cachedDefines = join;
  60483. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  60484. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  60485. var samplers = ["diffuseSampler", "rampSampler"];
  60486. if (BABYLON.ImageProcessingConfiguration) {
  60487. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  60488. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  60489. }
  60490. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  60491. }
  60492. return this._effect;
  60493. };
  60494. /**
  60495. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60496. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  60497. */
  60498. ParticleSystem.prototype.animate = function (preWarmOnly) {
  60499. var _this = this;
  60500. if (preWarmOnly === void 0) { preWarmOnly = false; }
  60501. if (!this._started) {
  60502. return;
  60503. }
  60504. if (!preWarmOnly) {
  60505. // Check
  60506. if (!this.isReady()) {
  60507. return;
  60508. }
  60509. if (this._currentRenderId === this._scene.getRenderId()) {
  60510. return;
  60511. }
  60512. this._currentRenderId = this._scene.getRenderId();
  60513. }
  60514. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60515. // Determine the number of particles we need to create
  60516. var newParticles;
  60517. if (this.manualEmitCount > -1) {
  60518. newParticles = this.manualEmitCount;
  60519. this._newPartsExcess = 0;
  60520. this.manualEmitCount = 0;
  60521. }
  60522. else {
  60523. var rate_1 = this.emitRate;
  60524. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  60525. var ratio = this._actualFrame / this.targetStopDuration;
  60526. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  60527. if (currentGradient !== _this._currentEmitRateGradient) {
  60528. _this._currentEmitRate1 = _this._currentEmitRate2;
  60529. _this._currentEmitRate2 = nextGradient.getFactor();
  60530. _this._currentEmitRateGradient = currentGradient;
  60531. }
  60532. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  60533. });
  60534. }
  60535. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  60536. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  60537. }
  60538. if (this._newPartsExcess > 1.0) {
  60539. newParticles += this._newPartsExcess >> 0;
  60540. this._newPartsExcess -= this._newPartsExcess >> 0;
  60541. }
  60542. this._alive = false;
  60543. if (!this._stopped) {
  60544. this._actualFrame += this._scaledUpdateSpeed;
  60545. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60546. this.stop();
  60547. }
  60548. }
  60549. else {
  60550. newParticles = 0;
  60551. }
  60552. this._update(newParticles);
  60553. // Stopped?
  60554. if (this._stopped) {
  60555. if (!this._alive) {
  60556. this._started = false;
  60557. if (this.onAnimationEnd) {
  60558. this.onAnimationEnd();
  60559. }
  60560. if (this.disposeOnStop) {
  60561. this._scene._toBeDisposed.push(this);
  60562. }
  60563. }
  60564. }
  60565. if (!preWarmOnly) {
  60566. // Update VBO
  60567. var offset = 0;
  60568. for (var index = 0; index < this._particles.length; index++) {
  60569. var particle = this._particles[index];
  60570. this._appendParticleVertices(offset, particle);
  60571. offset += this._useInstancing ? 1 : 4;
  60572. }
  60573. if (this._vertexBuffer) {
  60574. this._vertexBuffer.update(this._vertexData);
  60575. }
  60576. }
  60577. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  60578. this.stop();
  60579. }
  60580. };
  60581. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  60582. this._appendParticleVertex(offset++, particle, 0, 0);
  60583. if (!this._useInstancing) {
  60584. this._appendParticleVertex(offset++, particle, 1, 0);
  60585. this._appendParticleVertex(offset++, particle, 1, 1);
  60586. this._appendParticleVertex(offset++, particle, 0, 1);
  60587. }
  60588. };
  60589. /**
  60590. * Rebuilds the particle system.
  60591. */
  60592. ParticleSystem.prototype.rebuild = function () {
  60593. this._createIndexBuffer();
  60594. if (this._vertexBuffer) {
  60595. this._vertexBuffer._rebuild();
  60596. }
  60597. };
  60598. /**
  60599. * Is this system ready to be used/rendered
  60600. * @return true if the system is ready
  60601. */
  60602. ParticleSystem.prototype.isReady = function () {
  60603. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60604. return false;
  60605. }
  60606. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60607. if (!this._getEffect(this.blendMode).isReady()) {
  60608. return false;
  60609. }
  60610. }
  60611. else {
  60612. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  60613. return false;
  60614. }
  60615. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  60616. return false;
  60617. }
  60618. }
  60619. return true;
  60620. };
  60621. ParticleSystem.prototype._render = function (blendMode) {
  60622. var effect = this._getEffect(blendMode);
  60623. var engine = this._scene.getEngine();
  60624. // Render
  60625. engine.enableEffect(effect);
  60626. var viewMatrix = this._scene.getViewMatrix();
  60627. effect.setTexture("diffuseSampler", this.particleTexture);
  60628. effect.setMatrix("view", viewMatrix);
  60629. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  60630. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60631. var baseSize = this.particleTexture.getBaseSize();
  60632. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60633. }
  60634. effect.setVector2("translationPivot", this.translationPivot);
  60635. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  60636. if (this._isBillboardBased) {
  60637. var camera = this._scene.activeCamera;
  60638. effect.setVector3("eyePosition", camera.globalPosition);
  60639. }
  60640. if (this._rampGradientsTexture) {
  60641. effect.setTexture("rampSampler", this._rampGradientsTexture);
  60642. }
  60643. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  60644. var invView = viewMatrix.clone();
  60645. invView.invert();
  60646. effect.setMatrix("invView", invView);
  60647. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  60648. }
  60649. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  60650. // image processing
  60651. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  60652. this._imageProcessingConfiguration.bind(effect);
  60653. }
  60654. // Draw order
  60655. switch (blendMode) {
  60656. case ParticleSystem.BLENDMODE_ADD:
  60657. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60658. break;
  60659. case ParticleSystem.BLENDMODE_ONEONE:
  60660. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60661. break;
  60662. case ParticleSystem.BLENDMODE_STANDARD:
  60663. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60664. break;
  60665. case ParticleSystem.BLENDMODE_MULTIPLY:
  60666. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  60667. break;
  60668. }
  60669. if (this._useInstancing) {
  60670. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  60671. }
  60672. else {
  60673. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  60674. }
  60675. return this._particles.length;
  60676. };
  60677. /**
  60678. * Renders the particle system in its current state.
  60679. * @returns the current number of particles
  60680. */
  60681. ParticleSystem.prototype.render = function () {
  60682. // Check
  60683. if (!this.isReady() || !this._particles.length) {
  60684. return 0;
  60685. }
  60686. var engine = this._scene.getEngine();
  60687. engine.setState(false);
  60688. if (this.forceDepthWrite) {
  60689. engine.setDepthWrite(true);
  60690. }
  60691. var outparticles = 0;
  60692. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60693. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  60694. }
  60695. outparticles = this._render(this.blendMode);
  60696. engine.unbindInstanceAttributes();
  60697. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60698. return outparticles;
  60699. };
  60700. /**
  60701. * Disposes the particle system and free the associated resources
  60702. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60703. */
  60704. ParticleSystem.prototype.dispose = function (disposeTexture) {
  60705. if (disposeTexture === void 0) { disposeTexture = true; }
  60706. if (this._vertexBuffer) {
  60707. this._vertexBuffer.dispose();
  60708. this._vertexBuffer = null;
  60709. }
  60710. if (this._spriteBuffer) {
  60711. this._spriteBuffer.dispose();
  60712. this._spriteBuffer = null;
  60713. }
  60714. if (this._indexBuffer) {
  60715. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60716. this._indexBuffer = null;
  60717. }
  60718. if (disposeTexture && this.particleTexture) {
  60719. this.particleTexture.dispose();
  60720. this.particleTexture = null;
  60721. }
  60722. if (disposeTexture && this.noiseTexture) {
  60723. this.noiseTexture.dispose();
  60724. this.noiseTexture = null;
  60725. }
  60726. if (this._rampGradientsTexture) {
  60727. this._rampGradientsTexture.dispose();
  60728. this._rampGradientsTexture = null;
  60729. }
  60730. this._removeFromRoot();
  60731. if (this._subEmitters && this._subEmitters.length) {
  60732. for (var index = 0; index < this._subEmitters.length; index++) {
  60733. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  60734. var subEmitter = _a[_i];
  60735. subEmitter.dispose();
  60736. }
  60737. }
  60738. this._subEmitters = [];
  60739. this.subEmitters = [];
  60740. }
  60741. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  60742. this.emitter.dispose(true);
  60743. }
  60744. // Remove from scene
  60745. var index = this._scene.particleSystems.indexOf(this);
  60746. if (index > -1) {
  60747. this._scene.particleSystems.splice(index, 1);
  60748. }
  60749. this._scene._activeParticleSystems.dispose();
  60750. // Callback
  60751. this.onDisposeObservable.notifyObservers(this);
  60752. this.onDisposeObservable.clear();
  60753. this.reset();
  60754. };
  60755. // Clone
  60756. /**
  60757. * Clones the particle system.
  60758. * @param name The name of the cloned object
  60759. * @param newEmitter The new emitter to use
  60760. * @returns the cloned particle system
  60761. */
  60762. ParticleSystem.prototype.clone = function (name, newEmitter) {
  60763. var custom = null;
  60764. var program = null;
  60765. if (this.customShader != null) {
  60766. program = this.customShader;
  60767. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60768. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60769. }
  60770. else if (this._customEffect) {
  60771. custom = this._customEffect;
  60772. }
  60773. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  60774. result.customShader = program;
  60775. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  60776. if (newEmitter === undefined) {
  60777. newEmitter = this.emitter;
  60778. }
  60779. result.noiseTexture = this.noiseTexture;
  60780. result.emitter = newEmitter;
  60781. if (this.particleTexture) {
  60782. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60783. }
  60784. // Clone gradients
  60785. if (this._colorGradients) {
  60786. this._colorGradients.forEach(function (v) {
  60787. result.addColorGradient(v.gradient, v.color1, v.color2);
  60788. });
  60789. }
  60790. if (this._dragGradients) {
  60791. this._dragGradients.forEach(function (v) {
  60792. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  60793. });
  60794. }
  60795. if (this._angularSpeedGradients) {
  60796. this._angularSpeedGradients.forEach(function (v) {
  60797. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  60798. });
  60799. }
  60800. if (this._emitRateGradients) {
  60801. this._emitRateGradients.forEach(function (v) {
  60802. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  60803. });
  60804. }
  60805. if (this._lifeTimeGradients) {
  60806. this._lifeTimeGradients.forEach(function (v) {
  60807. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  60808. });
  60809. }
  60810. if (this._limitVelocityGradients) {
  60811. this._limitVelocityGradients.forEach(function (v) {
  60812. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  60813. });
  60814. }
  60815. if (this._sizeGradients) {
  60816. this._sizeGradients.forEach(function (v) {
  60817. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  60818. });
  60819. }
  60820. if (this._startSizeGradients) {
  60821. this._startSizeGradients.forEach(function (v) {
  60822. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  60823. });
  60824. }
  60825. if (this._velocityGradients) {
  60826. this._velocityGradients.forEach(function (v) {
  60827. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  60828. });
  60829. }
  60830. if (this._rampGradients) {
  60831. this._rampGradients.forEach(function (v) {
  60832. result.addRampGradient(v.gradient, v.color);
  60833. });
  60834. }
  60835. if (this._colorRemapGradients) {
  60836. this._colorRemapGradients.forEach(function (v) {
  60837. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  60838. });
  60839. }
  60840. if (this._alphaRemapGradients) {
  60841. this._alphaRemapGradients.forEach(function (v) {
  60842. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  60843. });
  60844. }
  60845. if (!this.preventAutoStart) {
  60846. result.start();
  60847. }
  60848. return result;
  60849. };
  60850. /**
  60851. * Serializes the particle system to a JSON object.
  60852. * @returns the JSON object
  60853. */
  60854. ParticleSystem.prototype.serialize = function () {
  60855. var serializationObject = {};
  60856. ParticleSystem._Serialize(serializationObject, this);
  60857. serializationObject.textureMask = this.textureMask.asArray();
  60858. serializationObject.customShader = this.customShader;
  60859. serializationObject.preventAutoStart = this.preventAutoStart;
  60860. // SubEmitters
  60861. if (this.subEmitters) {
  60862. serializationObject.subEmitters = [];
  60863. if (!this._subEmitters) {
  60864. this._prepareSubEmitterInternalArray();
  60865. }
  60866. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  60867. var subs = _a[_i];
  60868. var cell = [];
  60869. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  60870. var sub = subs_1[_b];
  60871. cell.push(sub.serialize());
  60872. }
  60873. serializationObject.subEmitters.push(cell);
  60874. }
  60875. }
  60876. return serializationObject;
  60877. };
  60878. /** @hidden */
  60879. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60880. serializationObject.name = particleSystem.name;
  60881. serializationObject.id = particleSystem.id;
  60882. serializationObject.capacity = particleSystem.getCapacity();
  60883. // Emitter
  60884. if (particleSystem.emitter.position) {
  60885. var emitterMesh = particleSystem.emitter;
  60886. serializationObject.emitterId = emitterMesh.id;
  60887. }
  60888. else {
  60889. var emitterPosition = particleSystem.emitter;
  60890. serializationObject.emitter = emitterPosition.asArray();
  60891. }
  60892. // Emitter
  60893. if (particleSystem.particleEmitterType) {
  60894. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60895. }
  60896. if (particleSystem.particleTexture) {
  60897. serializationObject.textureName = particleSystem.particleTexture.name;
  60898. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60899. }
  60900. // Animations
  60901. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60902. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60903. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60904. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60905. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60906. // Particle system
  60907. serializationObject.startDelay = particleSystem.startDelay;
  60908. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60909. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60910. serializationObject.billboardMode = particleSystem.billboardMode;
  60911. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60912. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60913. serializationObject.minSize = particleSystem.minSize;
  60914. serializationObject.maxSize = particleSystem.maxSize;
  60915. serializationObject.minScaleX = particleSystem.minScaleX;
  60916. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60917. serializationObject.minScaleY = particleSystem.minScaleY;
  60918. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60919. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60920. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60921. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60922. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60923. serializationObject.emitRate = particleSystem.emitRate;
  60924. serializationObject.gravity = particleSystem.gravity.asArray();
  60925. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60926. serializationObject.color1 = particleSystem.color1.asArray();
  60927. serializationObject.color2 = particleSystem.color2.asArray();
  60928. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60929. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60930. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60931. serializationObject.blendMode = particleSystem.blendMode;
  60932. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60933. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60934. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60935. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60936. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60937. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60938. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60939. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60940. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60941. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60942. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60943. var colorGradients = particleSystem.getColorGradients();
  60944. if (colorGradients) {
  60945. serializationObject.colorGradients = [];
  60946. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60947. var colorGradient = colorGradients_1[_i];
  60948. var serializedGradient = {
  60949. gradient: colorGradient.gradient,
  60950. color1: colorGradient.color1.asArray()
  60951. };
  60952. if (colorGradient.color2) {
  60953. serializedGradient.color2 = colorGradient.color2.asArray();
  60954. }
  60955. serializationObject.colorGradients.push(serializedGradient);
  60956. }
  60957. }
  60958. var rampGradients = particleSystem.getRampGradients();
  60959. if (rampGradients) {
  60960. serializationObject.rampGradients = [];
  60961. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60962. var rampGradient = rampGradients_1[_a];
  60963. var serializedGradient = {
  60964. gradient: rampGradient.gradient,
  60965. color: rampGradient.color.asArray()
  60966. };
  60967. serializationObject.rampGradients.push(serializedGradient);
  60968. }
  60969. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60970. }
  60971. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60972. if (colorRemapGradients) {
  60973. serializationObject.colorRemapGradients = [];
  60974. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60975. var colorRemapGradient = colorRemapGradients_1[_b];
  60976. var serializedGradient = {
  60977. gradient: colorRemapGradient.gradient,
  60978. factor1: colorRemapGradient.factor1
  60979. };
  60980. if (colorRemapGradient.factor2 !== undefined) {
  60981. serializedGradient.factor2 = colorRemapGradient.factor2;
  60982. }
  60983. serializationObject.colorRemapGradients.push(serializedGradient);
  60984. }
  60985. }
  60986. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60987. if (alphaRemapGradients) {
  60988. serializationObject.alphaRemapGradients = [];
  60989. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60990. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60991. var serializedGradient = {
  60992. gradient: alphaRemapGradient.gradient,
  60993. factor1: alphaRemapGradient.factor1
  60994. };
  60995. if (alphaRemapGradient.factor2 !== undefined) {
  60996. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60997. }
  60998. serializationObject.alphaRemapGradients.push(serializedGradient);
  60999. }
  61000. }
  61001. var sizeGradients = particleSystem.getSizeGradients();
  61002. if (sizeGradients) {
  61003. serializationObject.sizeGradients = [];
  61004. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  61005. var sizeGradient = sizeGradients_1[_d];
  61006. var serializedGradient = {
  61007. gradient: sizeGradient.gradient,
  61008. factor1: sizeGradient.factor1
  61009. };
  61010. if (sizeGradient.factor2 !== undefined) {
  61011. serializedGradient.factor2 = sizeGradient.factor2;
  61012. }
  61013. serializationObject.sizeGradients.push(serializedGradient);
  61014. }
  61015. }
  61016. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  61017. if (angularSpeedGradients) {
  61018. serializationObject.angularSpeedGradients = [];
  61019. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  61020. var angularSpeedGradient = angularSpeedGradients_1[_e];
  61021. var serializedGradient = {
  61022. gradient: angularSpeedGradient.gradient,
  61023. factor1: angularSpeedGradient.factor1
  61024. };
  61025. if (angularSpeedGradient.factor2 !== undefined) {
  61026. serializedGradient.factor2 = angularSpeedGradient.factor2;
  61027. }
  61028. serializationObject.angularSpeedGradients.push(serializedGradient);
  61029. }
  61030. }
  61031. var velocityGradients = particleSystem.getVelocityGradients();
  61032. if (velocityGradients) {
  61033. serializationObject.velocityGradients = [];
  61034. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  61035. var velocityGradient = velocityGradients_1[_f];
  61036. var serializedGradient = {
  61037. gradient: velocityGradient.gradient,
  61038. factor1: velocityGradient.factor1
  61039. };
  61040. if (velocityGradient.factor2 !== undefined) {
  61041. serializedGradient.factor2 = velocityGradient.factor2;
  61042. }
  61043. serializationObject.velocityGradients.push(serializedGradient);
  61044. }
  61045. }
  61046. var dragGradients = particleSystem.getDragGradients();
  61047. if (dragGradients) {
  61048. serializationObject.dragyGradients = [];
  61049. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  61050. var dragGradient = dragGradients_1[_g];
  61051. var serializedGradient = {
  61052. gradient: dragGradient.gradient,
  61053. factor1: dragGradient.factor1
  61054. };
  61055. if (dragGradient.factor2 !== undefined) {
  61056. serializedGradient.factor2 = dragGradient.factor2;
  61057. }
  61058. serializationObject.dragGradients.push(serializedGradient);
  61059. }
  61060. }
  61061. var emitRateGradients = particleSystem.getEmitRateGradients();
  61062. if (emitRateGradients) {
  61063. serializationObject.emitRateGradients = [];
  61064. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  61065. var emitRateGradient = emitRateGradients_1[_h];
  61066. var serializedGradient = {
  61067. gradient: emitRateGradient.gradient,
  61068. factor1: emitRateGradient.factor1
  61069. };
  61070. if (emitRateGradient.factor2 !== undefined) {
  61071. serializedGradient.factor2 = emitRateGradient.factor2;
  61072. }
  61073. serializationObject.emitRateGradients.push(serializedGradient);
  61074. }
  61075. }
  61076. var startSizeGradients = particleSystem.getStartSizeGradients();
  61077. if (startSizeGradients) {
  61078. serializationObject.startSizeGradients = [];
  61079. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  61080. var startSizeGradient = startSizeGradients_1[_j];
  61081. var serializedGradient = {
  61082. gradient: startSizeGradient.gradient,
  61083. factor1: startSizeGradient.factor1
  61084. };
  61085. if (startSizeGradient.factor2 !== undefined) {
  61086. serializedGradient.factor2 = startSizeGradient.factor2;
  61087. }
  61088. serializationObject.startSizeGradients.push(serializedGradient);
  61089. }
  61090. }
  61091. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  61092. if (lifeTimeGradients) {
  61093. serializationObject.lifeTimeGradients = [];
  61094. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  61095. var lifeTimeGradient = lifeTimeGradients_1[_k];
  61096. var serializedGradient = {
  61097. gradient: lifeTimeGradient.gradient,
  61098. factor1: lifeTimeGradient.factor1
  61099. };
  61100. if (lifeTimeGradient.factor2 !== undefined) {
  61101. serializedGradient.factor2 = lifeTimeGradient.factor2;
  61102. }
  61103. serializationObject.lifeTimeGradients.push(serializedGradient);
  61104. }
  61105. }
  61106. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  61107. if (limitVelocityGradients) {
  61108. serializationObject.limitVelocityGradients = [];
  61109. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  61110. var limitVelocityGradient = limitVelocityGradients_1[_l];
  61111. var serializedGradient = {
  61112. gradient: limitVelocityGradient.gradient,
  61113. factor1: limitVelocityGradient.factor1
  61114. };
  61115. if (limitVelocityGradient.factor2 !== undefined) {
  61116. serializedGradient.factor2 = limitVelocityGradient.factor2;
  61117. }
  61118. serializationObject.limitVelocityGradients.push(serializedGradient);
  61119. }
  61120. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  61121. }
  61122. if (particleSystem.noiseTexture) {
  61123. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  61124. }
  61125. };
  61126. /** @hidden */
  61127. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  61128. // Texture
  61129. if (parsedParticleSystem.textureName) {
  61130. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  61131. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  61132. }
  61133. // Emitter
  61134. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  61135. particleSystem.emitter = BABYLON.Vector3.Zero();
  61136. }
  61137. else if (parsedParticleSystem.emitterId) {
  61138. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  61139. }
  61140. else {
  61141. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  61142. }
  61143. // Misc.
  61144. if (parsedParticleSystem.renderingGroupId !== undefined) {
  61145. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  61146. }
  61147. if (parsedParticleSystem.isBillboardBased !== undefined) {
  61148. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  61149. }
  61150. if (parsedParticleSystem.billboardMode !== undefined) {
  61151. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  61152. }
  61153. // Animations
  61154. if (parsedParticleSystem.animations) {
  61155. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  61156. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  61157. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61158. }
  61159. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  61160. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  61161. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  61162. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  61163. }
  61164. if (parsedParticleSystem.autoAnimate) {
  61165. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  61166. }
  61167. // Particle system
  61168. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  61169. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  61170. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  61171. particleSystem.minSize = parsedParticleSystem.minSize;
  61172. particleSystem.maxSize = parsedParticleSystem.maxSize;
  61173. if (parsedParticleSystem.minScaleX) {
  61174. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  61175. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  61176. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  61177. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  61178. }
  61179. if (parsedParticleSystem.preWarmCycles !== undefined) {
  61180. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  61181. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  61182. }
  61183. if (parsedParticleSystem.minInitialRotation !== undefined) {
  61184. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  61185. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  61186. }
  61187. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  61188. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  61189. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  61190. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  61191. particleSystem.emitRate = parsedParticleSystem.emitRate;
  61192. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  61193. if (parsedParticleSystem.noiseStrength) {
  61194. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  61195. }
  61196. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  61197. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  61198. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  61199. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  61200. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  61201. particleSystem.blendMode = parsedParticleSystem.blendMode;
  61202. if (parsedParticleSystem.colorGradients) {
  61203. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  61204. var colorGradient = _a[_i];
  61205. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  61206. }
  61207. }
  61208. if (parsedParticleSystem.rampGradients) {
  61209. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  61210. var rampGradient = _c[_b];
  61211. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  61212. }
  61213. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  61214. }
  61215. if (parsedParticleSystem.colorRemapGradients) {
  61216. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  61217. var colorRemapGradient = _e[_d];
  61218. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  61219. }
  61220. }
  61221. if (parsedParticleSystem.alphaRemapGradients) {
  61222. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  61223. var alphaRemapGradient = _g[_f];
  61224. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  61225. }
  61226. }
  61227. if (parsedParticleSystem.sizeGradients) {
  61228. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  61229. var sizeGradient = _j[_h];
  61230. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  61231. }
  61232. }
  61233. if (parsedParticleSystem.sizeGradients) {
  61234. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  61235. var sizeGradient = _l[_k];
  61236. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  61237. }
  61238. }
  61239. if (parsedParticleSystem.angularSpeedGradients) {
  61240. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  61241. var angularSpeedGradient = _o[_m];
  61242. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  61243. }
  61244. }
  61245. if (parsedParticleSystem.velocityGradients) {
  61246. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  61247. var velocityGradient = _q[_p];
  61248. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  61249. }
  61250. }
  61251. if (parsedParticleSystem.dragGradients) {
  61252. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  61253. var dragGradient = _s[_r];
  61254. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  61255. }
  61256. }
  61257. if (parsedParticleSystem.emitRateGradients) {
  61258. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  61259. var emitRateGradient = _u[_t];
  61260. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  61261. }
  61262. }
  61263. if (parsedParticleSystem.startSizeGradients) {
  61264. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  61265. var startSizeGradient = _w[_v];
  61266. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  61267. }
  61268. }
  61269. if (parsedParticleSystem.lifeTimeGradients) {
  61270. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  61271. var lifeTimeGradient = _y[_x];
  61272. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  61273. }
  61274. }
  61275. if (parsedParticleSystem.limitVelocityGradients) {
  61276. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  61277. var limitVelocityGradient = _0[_z];
  61278. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  61279. }
  61280. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  61281. }
  61282. if (parsedParticleSystem.noiseTexture) {
  61283. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  61284. }
  61285. // Emitter
  61286. var emitterType;
  61287. if (parsedParticleSystem.particleEmitterType) {
  61288. switch (parsedParticleSystem.particleEmitterType.type) {
  61289. case "SphereParticleEmitter":
  61290. emitterType = new BABYLON.SphereParticleEmitter();
  61291. break;
  61292. case "SphereDirectedParticleEmitter":
  61293. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  61294. break;
  61295. case "ConeEmitter":
  61296. case "ConeParticleEmitter":
  61297. emitterType = new BABYLON.ConeParticleEmitter();
  61298. break;
  61299. case "CylinderParticleEmitter":
  61300. emitterType = new BABYLON.CylinderParticleEmitter();
  61301. break;
  61302. case "HemisphericParticleEmitter":
  61303. emitterType = new BABYLON.HemisphericParticleEmitter();
  61304. break;
  61305. case "BoxEmitter":
  61306. case "BoxParticleEmitter":
  61307. default:
  61308. emitterType = new BABYLON.BoxParticleEmitter();
  61309. break;
  61310. }
  61311. emitterType.parse(parsedParticleSystem.particleEmitterType);
  61312. }
  61313. else {
  61314. emitterType = new BABYLON.BoxParticleEmitter();
  61315. emitterType.parse(parsedParticleSystem);
  61316. }
  61317. particleSystem.particleEmitterType = emitterType;
  61318. // Animation sheet
  61319. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  61320. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  61321. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  61322. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  61323. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  61324. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  61325. };
  61326. /**
  61327. * Parses a JSON object to create a particle system.
  61328. * @param parsedParticleSystem The JSON object to parse
  61329. * @param scene The scene to create the particle system in
  61330. * @param rootUrl The root url to use to load external dependencies like texture
  61331. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  61332. * @returns the Parsed particle system
  61333. */
  61334. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  61335. if (doNotStart === void 0) { doNotStart = false; }
  61336. var name = parsedParticleSystem.name;
  61337. var custom = null;
  61338. var program = null;
  61339. if (parsedParticleSystem.customShader) {
  61340. program = parsedParticleSystem.customShader;
  61341. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61342. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61343. }
  61344. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  61345. particleSystem.customShader = program;
  61346. if (parsedParticleSystem.id) {
  61347. particleSystem.id = parsedParticleSystem.id;
  61348. }
  61349. // SubEmitters
  61350. if (parsedParticleSystem.subEmitters) {
  61351. particleSystem.subEmitters = [];
  61352. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  61353. var cell = _a[_i];
  61354. var cellArray = [];
  61355. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  61356. var sub = cell_1[_b];
  61357. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  61358. }
  61359. particleSystem.subEmitters.push(cellArray);
  61360. }
  61361. }
  61362. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61363. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  61364. // Auto start
  61365. if (parsedParticleSystem.preventAutoStart) {
  61366. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  61367. }
  61368. if (!doNotStart && !particleSystem.preventAutoStart) {
  61369. particleSystem.start();
  61370. }
  61371. return particleSystem;
  61372. };
  61373. /**
  61374. * Billboard mode will only apply to Y axis
  61375. */
  61376. ParticleSystem.BILLBOARDMODE_Y = 2;
  61377. /**
  61378. * Billboard mode will apply to all axes
  61379. */
  61380. ParticleSystem.BILLBOARDMODE_ALL = 7;
  61381. /**
  61382. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  61383. */
  61384. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  61385. return ParticleSystem;
  61386. }(BABYLON.BaseParticleSystem));
  61387. BABYLON.ParticleSystem = ParticleSystem;
  61388. })(BABYLON || (BABYLON = {}));
  61389. //# sourceMappingURL=babylon.particleSystem.js.map
  61390. var BABYLON;
  61391. (function (BABYLON) {
  61392. /**
  61393. * Particle emitter emitting particles from the inside of a box.
  61394. * It emits the particles randomly between 2 given directions.
  61395. */
  61396. var BoxParticleEmitter = /** @class */ (function () {
  61397. /**
  61398. * Creates a new instance BoxParticleEmitter
  61399. */
  61400. function BoxParticleEmitter() {
  61401. /**
  61402. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61403. */
  61404. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61405. /**
  61406. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61407. */
  61408. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61409. /**
  61410. * 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.
  61411. */
  61412. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  61413. /**
  61414. * 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.
  61415. */
  61416. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  61417. }
  61418. /**
  61419. * Called by the particle System when the direction is computed for the created particle.
  61420. * @param worldMatrix is the world matrix of the particle system
  61421. * @param directionToUpdate is the direction vector to update with the result
  61422. * @param particle is the particle we are computed the direction for
  61423. */
  61424. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61425. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61426. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61427. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61428. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61429. };
  61430. /**
  61431. * Called by the particle System when the position is computed for the created particle.
  61432. * @param worldMatrix is the world matrix of the particle system
  61433. * @param positionToUpdate is the position vector to update with the result
  61434. * @param particle is the particle we are computed the position for
  61435. */
  61436. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61437. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  61438. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  61439. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  61440. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61441. };
  61442. /**
  61443. * Clones the current emitter and returns a copy of it
  61444. * @returns the new emitter
  61445. */
  61446. BoxParticleEmitter.prototype.clone = function () {
  61447. var newOne = new BoxParticleEmitter();
  61448. BABYLON.Tools.DeepCopy(this, newOne);
  61449. return newOne;
  61450. };
  61451. /**
  61452. * Called by the GPUParticleSystem to setup the update shader
  61453. * @param effect defines the update shader
  61454. */
  61455. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  61456. effect.setVector3("direction1", this.direction1);
  61457. effect.setVector3("direction2", this.direction2);
  61458. effect.setVector3("minEmitBox", this.minEmitBox);
  61459. effect.setVector3("maxEmitBox", this.maxEmitBox);
  61460. };
  61461. /**
  61462. * Returns a string to use to update the GPU particles update shader
  61463. * @returns a string containng the defines string
  61464. */
  61465. BoxParticleEmitter.prototype.getEffectDefines = function () {
  61466. return "#define BOXEMITTER";
  61467. };
  61468. /**
  61469. * Returns the string "BoxParticleEmitter"
  61470. * @returns a string containing the class name
  61471. */
  61472. BoxParticleEmitter.prototype.getClassName = function () {
  61473. return "BoxParticleEmitter";
  61474. };
  61475. /**
  61476. * Serializes the particle system to a JSON object.
  61477. * @returns the JSON object
  61478. */
  61479. BoxParticleEmitter.prototype.serialize = function () {
  61480. var serializationObject = {};
  61481. serializationObject.type = this.getClassName();
  61482. serializationObject.direction1 = this.direction1.asArray();
  61483. serializationObject.direction2 = this.direction2.asArray();
  61484. serializationObject.minEmitBox = this.minEmitBox.asArray();
  61485. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  61486. return serializationObject;
  61487. };
  61488. /**
  61489. * Parse properties from a JSON object
  61490. * @param serializationObject defines the JSON object
  61491. */
  61492. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  61493. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61494. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61495. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  61496. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  61497. };
  61498. return BoxParticleEmitter;
  61499. }());
  61500. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  61501. })(BABYLON || (BABYLON = {}));
  61502. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  61503. var BABYLON;
  61504. (function (BABYLON) {
  61505. /**
  61506. * Particle emitter emitting particles from the inside of a cylinder.
  61507. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  61508. */
  61509. var CylinderParticleEmitter = /** @class */ (function () {
  61510. /**
  61511. * Creates a new instance CylinderParticleEmitter
  61512. * @param radius the radius of the emission cylinder (1 by default)
  61513. * @param height the height of the emission cylinder (1 by default)
  61514. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61515. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61516. */
  61517. function CylinderParticleEmitter(
  61518. /**
  61519. * The radius of the emission cylinder.
  61520. */
  61521. radius,
  61522. /**
  61523. * The height of the emission cylinder.
  61524. */
  61525. height,
  61526. /**
  61527. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61528. */
  61529. radiusRange,
  61530. /**
  61531. * How much to randomize the particle direction [0-1].
  61532. */
  61533. directionRandomizer) {
  61534. if (radius === void 0) { radius = 1; }
  61535. if (height === void 0) { height = 1; }
  61536. if (radiusRange === void 0) { radiusRange = 1; }
  61537. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61538. this.radius = radius;
  61539. this.height = height;
  61540. this.radiusRange = radiusRange;
  61541. this.directionRandomizer = directionRandomizer;
  61542. }
  61543. /**
  61544. * Called by the particle System when the direction is computed for the created particle.
  61545. * @param worldMatrix is the world matrix of the particle system
  61546. * @param directionToUpdate is the direction vector to update with the result
  61547. * @param particle is the particle we are computed the direction for
  61548. */
  61549. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61550. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61551. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  61552. var angle = Math.atan2(direction.x, direction.z);
  61553. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  61554. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  61555. direction.x = Math.sin(angle);
  61556. direction.z = Math.cos(angle);
  61557. direction.normalize();
  61558. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61559. };
  61560. /**
  61561. * Called by the particle System when the position is computed for the created particle.
  61562. * @param worldMatrix is the world matrix of the particle system
  61563. * @param positionToUpdate is the position vector to update with the result
  61564. * @param particle is the particle we are computed the position for
  61565. */
  61566. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61567. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  61568. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61569. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  61570. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  61571. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  61572. var xPos = positionRadius * Math.cos(angle);
  61573. var zPos = positionRadius * Math.sin(angle);
  61574. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  61575. };
  61576. /**
  61577. * Clones the current emitter and returns a copy of it
  61578. * @returns the new emitter
  61579. */
  61580. CylinderParticleEmitter.prototype.clone = function () {
  61581. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  61582. BABYLON.Tools.DeepCopy(this, newOne);
  61583. return newOne;
  61584. };
  61585. /**
  61586. * Called by the GPUParticleSystem to setup the update shader
  61587. * @param effect defines the update shader
  61588. */
  61589. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  61590. effect.setFloat("radius", this.radius);
  61591. effect.setFloat("height", this.height);
  61592. effect.setFloat("radiusRange", this.radiusRange);
  61593. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61594. };
  61595. /**
  61596. * Returns a string to use to update the GPU particles update shader
  61597. * @returns a string containng the defines string
  61598. */
  61599. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  61600. return "#define CYLINDEREMITTER";
  61601. };
  61602. /**
  61603. * Returns the string "CylinderParticleEmitter"
  61604. * @returns a string containing the class name
  61605. */
  61606. CylinderParticleEmitter.prototype.getClassName = function () {
  61607. return "CylinderParticleEmitter";
  61608. };
  61609. /**
  61610. * Serializes the particle system to a JSON object.
  61611. * @returns the JSON object
  61612. */
  61613. CylinderParticleEmitter.prototype.serialize = function () {
  61614. var serializationObject = {};
  61615. serializationObject.type = this.getClassName();
  61616. serializationObject.radius = this.radius;
  61617. serializationObject.height = this.height;
  61618. serializationObject.radiusRange = this.radiusRange;
  61619. serializationObject.directionRandomizer = this.directionRandomizer;
  61620. return serializationObject;
  61621. };
  61622. /**
  61623. * Parse properties from a JSON object
  61624. * @param serializationObject defines the JSON object
  61625. */
  61626. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  61627. this.radius = serializationObject.radius;
  61628. this.height = serializationObject.height;
  61629. this.radiusRange = serializationObject.radiusRange;
  61630. this.directionRandomizer = serializationObject.directionRandomizer;
  61631. };
  61632. return CylinderParticleEmitter;
  61633. }());
  61634. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  61635. /**
  61636. * Particle emitter emitting particles from the inside of a cylinder.
  61637. * It emits the particles randomly between two vectors.
  61638. */
  61639. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  61640. __extends(CylinderDirectedParticleEmitter, _super);
  61641. /**
  61642. * Creates a new instance CylinderDirectedParticleEmitter
  61643. * @param radius the radius of the emission cylinder (1 by default)
  61644. * @param height the height of the emission cylinder (1 by default)
  61645. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61646. * @param direction1 the min limit of the emission direction (up vector by default)
  61647. * @param direction2 the max limit of the emission direction (up vector by default)
  61648. */
  61649. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  61650. /**
  61651. * The min limit of the emission direction.
  61652. */
  61653. direction1,
  61654. /**
  61655. * The max limit of the emission direction.
  61656. */
  61657. direction2) {
  61658. if (radius === void 0) { radius = 1; }
  61659. if (height === void 0) { height = 1; }
  61660. if (radiusRange === void 0) { radiusRange = 1; }
  61661. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61662. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61663. var _this = _super.call(this, radius, height, radiusRange) || this;
  61664. _this.direction1 = direction1;
  61665. _this.direction2 = direction2;
  61666. return _this;
  61667. }
  61668. /**
  61669. * Called by the particle System when the direction is computed for the created particle.
  61670. * @param worldMatrix is the world matrix of the particle system
  61671. * @param directionToUpdate is the direction vector to update with the result
  61672. * @param particle is the particle we are computed the direction for
  61673. */
  61674. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61675. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61676. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61677. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61678. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61679. };
  61680. /**
  61681. * Clones the current emitter and returns a copy of it
  61682. * @returns the new emitter
  61683. */
  61684. CylinderDirectedParticleEmitter.prototype.clone = function () {
  61685. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  61686. BABYLON.Tools.DeepCopy(this, newOne);
  61687. return newOne;
  61688. };
  61689. /**
  61690. * Called by the GPUParticleSystem to setup the update shader
  61691. * @param effect defines the update shader
  61692. */
  61693. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61694. effect.setFloat("radius", this.radius);
  61695. effect.setFloat("height", this.height);
  61696. effect.setFloat("radiusRange", this.radiusRange);
  61697. effect.setVector3("direction1", this.direction1);
  61698. effect.setVector3("direction2", this.direction2);
  61699. };
  61700. /**
  61701. * Returns a string to use to update the GPU particles update shader
  61702. * @returns a string containng the defines string
  61703. */
  61704. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61705. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  61706. };
  61707. /**
  61708. * Returns the string "CylinderDirectedParticleEmitter"
  61709. * @returns a string containing the class name
  61710. */
  61711. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  61712. return "CylinderDirectedParticleEmitter";
  61713. };
  61714. /**
  61715. * Serializes the particle system to a JSON object.
  61716. * @returns the JSON object
  61717. */
  61718. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  61719. var serializationObject = _super.prototype.serialize.call(this);
  61720. serializationObject.direction1 = this.direction1.asArray();
  61721. serializationObject.direction2 = this.direction2.asArray();
  61722. return serializationObject;
  61723. };
  61724. /**
  61725. * Parse properties from a JSON object
  61726. * @param serializationObject defines the JSON object
  61727. */
  61728. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61729. _super.prototype.parse.call(this, serializationObject);
  61730. this.direction1.copyFrom(serializationObject.direction1);
  61731. this.direction2.copyFrom(serializationObject.direction2);
  61732. };
  61733. return CylinderDirectedParticleEmitter;
  61734. }(CylinderParticleEmitter));
  61735. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  61736. })(BABYLON || (BABYLON = {}));
  61737. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  61738. var BABYLON;
  61739. (function (BABYLON) {
  61740. /**
  61741. * Particle emitter emitting particles from the inside of a cone.
  61742. * It emits the particles alongside the cone volume from the base to the particle.
  61743. * The emission direction might be randomized.
  61744. */
  61745. var ConeParticleEmitter = /** @class */ (function () {
  61746. /**
  61747. * Creates a new instance ConeParticleEmitter
  61748. * @param radius the radius of the emission cone (1 by default)
  61749. * @param angles the cone base angle (PI by default)
  61750. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  61751. */
  61752. function ConeParticleEmitter(radius, angle,
  61753. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  61754. directionRandomizer) {
  61755. if (radius === void 0) { radius = 1; }
  61756. if (angle === void 0) { angle = Math.PI; }
  61757. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61758. this.directionRandomizer = directionRandomizer;
  61759. /**
  61760. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  61761. */
  61762. this.radiusRange = 1;
  61763. /**
  61764. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  61765. */
  61766. this.heightRange = 1;
  61767. /**
  61768. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  61769. */
  61770. this.emitFromSpawnPointOnly = false;
  61771. this.angle = angle;
  61772. this.radius = radius;
  61773. }
  61774. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  61775. /**
  61776. * Gets or sets the radius of the emission cone
  61777. */
  61778. get: function () {
  61779. return this._radius;
  61780. },
  61781. set: function (value) {
  61782. this._radius = value;
  61783. this._buildHeight();
  61784. },
  61785. enumerable: true,
  61786. configurable: true
  61787. });
  61788. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  61789. /**
  61790. * Gets or sets the angle of the emission cone
  61791. */
  61792. get: function () {
  61793. return this._angle;
  61794. },
  61795. set: function (value) {
  61796. this._angle = value;
  61797. this._buildHeight();
  61798. },
  61799. enumerable: true,
  61800. configurable: true
  61801. });
  61802. ConeParticleEmitter.prototype._buildHeight = function () {
  61803. if (this._angle !== 0) {
  61804. this._height = this._radius / Math.tan(this._angle / 2);
  61805. }
  61806. else {
  61807. this._height = 1;
  61808. }
  61809. };
  61810. /**
  61811. * Called by the particle System when the direction is computed for the created particle.
  61812. * @param worldMatrix is the world matrix of the particle system
  61813. * @param directionToUpdate is the direction vector to update with the result
  61814. * @param particle is the particle we are computed the direction for
  61815. */
  61816. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61817. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  61818. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  61819. }
  61820. else {
  61821. // measure the direction Vector from the emitter to the particle.
  61822. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61823. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61824. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61825. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61826. direction.x += randX;
  61827. direction.y += randY;
  61828. direction.z += randZ;
  61829. direction.normalize();
  61830. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61831. }
  61832. };
  61833. /**
  61834. * Called by the particle System when the position is computed for the created particle.
  61835. * @param worldMatrix is the world matrix of the particle system
  61836. * @param positionToUpdate is the position vector to update with the result
  61837. * @param particle is the particle we are computed the position for
  61838. */
  61839. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61840. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  61841. var h;
  61842. if (!this.emitFromSpawnPointOnly) {
  61843. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  61844. // Better distribution in a cone at normal angles.
  61845. h = 1 - h * h;
  61846. }
  61847. else {
  61848. h = 0.0001;
  61849. }
  61850. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  61851. radius = radius * h;
  61852. var randX = radius * Math.sin(s);
  61853. var randZ = radius * Math.cos(s);
  61854. var randY = h * this._height;
  61855. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61856. };
  61857. /**
  61858. * Clones the current emitter and returns a copy of it
  61859. * @returns the new emitter
  61860. */
  61861. ConeParticleEmitter.prototype.clone = function () {
  61862. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  61863. BABYLON.Tools.DeepCopy(this, newOne);
  61864. return newOne;
  61865. };
  61866. /**
  61867. * Called by the GPUParticleSystem to setup the update shader
  61868. * @param effect defines the update shader
  61869. */
  61870. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  61871. effect.setFloat2("radius", this._radius, this.radiusRange);
  61872. effect.setFloat("coneAngle", this._angle);
  61873. effect.setFloat2("height", this._height, this.heightRange);
  61874. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61875. };
  61876. /**
  61877. * Returns a string to use to update the GPU particles update shader
  61878. * @returns a string containng the defines string
  61879. */
  61880. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61881. var defines = "#define CONEEMITTER";
  61882. if (this.emitFromSpawnPointOnly) {
  61883. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61884. }
  61885. return defines;
  61886. };
  61887. /**
  61888. * Returns the string "ConeParticleEmitter"
  61889. * @returns a string containing the class name
  61890. */
  61891. ConeParticleEmitter.prototype.getClassName = function () {
  61892. return "ConeParticleEmitter";
  61893. };
  61894. /**
  61895. * Serializes the particle system to a JSON object.
  61896. * @returns the JSON object
  61897. */
  61898. ConeParticleEmitter.prototype.serialize = function () {
  61899. var serializationObject = {};
  61900. serializationObject.type = this.getClassName();
  61901. serializationObject.radius = this._radius;
  61902. serializationObject.angle = this._angle;
  61903. serializationObject.directionRandomizer = this.directionRandomizer;
  61904. return serializationObject;
  61905. };
  61906. /**
  61907. * Parse properties from a JSON object
  61908. * @param serializationObject defines the JSON object
  61909. */
  61910. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61911. this.radius = serializationObject.radius;
  61912. this.angle = serializationObject.angle;
  61913. this.directionRandomizer = serializationObject.directionRandomizer;
  61914. };
  61915. return ConeParticleEmitter;
  61916. }());
  61917. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61918. })(BABYLON || (BABYLON = {}));
  61919. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61920. var BABYLON;
  61921. (function (BABYLON) {
  61922. /**
  61923. * Particle emitter emitting particles from the inside of a sphere.
  61924. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61925. */
  61926. var SphereParticleEmitter = /** @class */ (function () {
  61927. /**
  61928. * Creates a new instance SphereParticleEmitter
  61929. * @param radius the radius of the emission sphere (1 by default)
  61930. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61931. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61932. */
  61933. function SphereParticleEmitter(
  61934. /**
  61935. * The radius of the emission sphere.
  61936. */
  61937. radius,
  61938. /**
  61939. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61940. */
  61941. radiusRange,
  61942. /**
  61943. * How much to randomize the particle direction [0-1].
  61944. */
  61945. directionRandomizer) {
  61946. if (radius === void 0) { radius = 1; }
  61947. if (radiusRange === void 0) { radiusRange = 1; }
  61948. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61949. this.radius = radius;
  61950. this.radiusRange = radiusRange;
  61951. this.directionRandomizer = directionRandomizer;
  61952. }
  61953. /**
  61954. * Called by the particle System when the direction is computed for the created particle.
  61955. * @param worldMatrix is the world matrix of the particle system
  61956. * @param directionToUpdate is the direction vector to update with the result
  61957. * @param particle is the particle we are computed the direction for
  61958. */
  61959. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61960. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61961. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61962. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61963. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61964. direction.x += randX;
  61965. direction.y += randY;
  61966. direction.z += randZ;
  61967. direction.normalize();
  61968. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61969. };
  61970. /**
  61971. * Called by the particle System when the position is computed for the created particle.
  61972. * @param worldMatrix is the world matrix of the particle system
  61973. * @param positionToUpdate is the position vector to update with the result
  61974. * @param particle is the particle we are computed the position for
  61975. */
  61976. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61977. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61978. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61979. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61980. var theta = Math.acos(2 * v - 1);
  61981. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61982. var randY = randRadius * Math.cos(theta);
  61983. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61984. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61985. };
  61986. /**
  61987. * Clones the current emitter and returns a copy of it
  61988. * @returns the new emitter
  61989. */
  61990. SphereParticleEmitter.prototype.clone = function () {
  61991. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61992. BABYLON.Tools.DeepCopy(this, newOne);
  61993. return newOne;
  61994. };
  61995. /**
  61996. * Called by the GPUParticleSystem to setup the update shader
  61997. * @param effect defines the update shader
  61998. */
  61999. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  62000. effect.setFloat("radius", this.radius);
  62001. effect.setFloat("radiusRange", this.radiusRange);
  62002. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62003. };
  62004. /**
  62005. * Returns a string to use to update the GPU particles update shader
  62006. * @returns a string containng the defines string
  62007. */
  62008. SphereParticleEmitter.prototype.getEffectDefines = function () {
  62009. return "#define SPHEREEMITTER";
  62010. };
  62011. /**
  62012. * Returns the string "SphereParticleEmitter"
  62013. * @returns a string containing the class name
  62014. */
  62015. SphereParticleEmitter.prototype.getClassName = function () {
  62016. return "SphereParticleEmitter";
  62017. };
  62018. /**
  62019. * Serializes the particle system to a JSON object.
  62020. * @returns the JSON object
  62021. */
  62022. SphereParticleEmitter.prototype.serialize = function () {
  62023. var serializationObject = {};
  62024. serializationObject.type = this.getClassName();
  62025. serializationObject.radius = this.radius;
  62026. serializationObject.radiusRange = this.radiusRange;
  62027. serializationObject.directionRandomizer = this.directionRandomizer;
  62028. return serializationObject;
  62029. };
  62030. /**
  62031. * Parse properties from a JSON object
  62032. * @param serializationObject defines the JSON object
  62033. */
  62034. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  62035. this.radius = serializationObject.radius;
  62036. this.radiusRange = serializationObject.radiusRange;
  62037. this.directionRandomizer = serializationObject.directionRandomizer;
  62038. };
  62039. return SphereParticleEmitter;
  62040. }());
  62041. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  62042. /**
  62043. * Particle emitter emitting particles from the inside of a sphere.
  62044. * It emits the particles randomly between two vectors.
  62045. */
  62046. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  62047. __extends(SphereDirectedParticleEmitter, _super);
  62048. /**
  62049. * Creates a new instance SphereDirectedParticleEmitter
  62050. * @param radius the radius of the emission sphere (1 by default)
  62051. * @param direction1 the min limit of the emission direction (up vector by default)
  62052. * @param direction2 the max limit of the emission direction (up vector by default)
  62053. */
  62054. function SphereDirectedParticleEmitter(radius,
  62055. /**
  62056. * The min limit of the emission direction.
  62057. */
  62058. direction1,
  62059. /**
  62060. * The max limit of the emission direction.
  62061. */
  62062. direction2) {
  62063. if (radius === void 0) { radius = 1; }
  62064. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62065. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62066. var _this = _super.call(this, radius) || this;
  62067. _this.direction1 = direction1;
  62068. _this.direction2 = direction2;
  62069. return _this;
  62070. }
  62071. /**
  62072. * Called by the particle System when the direction is computed for the created particle.
  62073. * @param worldMatrix is the world matrix of the particle system
  62074. * @param directionToUpdate is the direction vector to update with the result
  62075. * @param particle is the particle we are computed the direction for
  62076. */
  62077. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62078. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62079. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62080. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62081. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62082. };
  62083. /**
  62084. * Clones the current emitter and returns a copy of it
  62085. * @returns the new emitter
  62086. */
  62087. SphereDirectedParticleEmitter.prototype.clone = function () {
  62088. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  62089. BABYLON.Tools.DeepCopy(this, newOne);
  62090. return newOne;
  62091. };
  62092. /**
  62093. * Called by the GPUParticleSystem to setup the update shader
  62094. * @param effect defines the update shader
  62095. */
  62096. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62097. effect.setFloat("radius", this.radius);
  62098. effect.setFloat("radiusRange", this.radiusRange);
  62099. effect.setVector3("direction1", this.direction1);
  62100. effect.setVector3("direction2", this.direction2);
  62101. };
  62102. /**
  62103. * Returns a string to use to update the GPU particles update shader
  62104. * @returns a string containng the defines string
  62105. */
  62106. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62107. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  62108. };
  62109. /**
  62110. * Returns the string "SphereDirectedParticleEmitter"
  62111. * @returns a string containing the class name
  62112. */
  62113. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  62114. return "SphereDirectedParticleEmitter";
  62115. };
  62116. /**
  62117. * Serializes the particle system to a JSON object.
  62118. * @returns the JSON object
  62119. */
  62120. SphereDirectedParticleEmitter.prototype.serialize = function () {
  62121. var serializationObject = _super.prototype.serialize.call(this);
  62122. serializationObject.direction1 = this.direction1.asArray();
  62123. serializationObject.direction2 = this.direction2.asArray();
  62124. return serializationObject;
  62125. };
  62126. /**
  62127. * Parse properties from a JSON object
  62128. * @param serializationObject defines the JSON object
  62129. */
  62130. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  62131. _super.prototype.parse.call(this, serializationObject);
  62132. this.direction1.copyFrom(serializationObject.direction1);
  62133. this.direction2.copyFrom(serializationObject.direction2);
  62134. };
  62135. return SphereDirectedParticleEmitter;
  62136. }(SphereParticleEmitter));
  62137. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  62138. })(BABYLON || (BABYLON = {}));
  62139. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  62140. var BABYLON;
  62141. (function (BABYLON) {
  62142. /**
  62143. * Particle emitter emitting particles from the inside of a hemisphere.
  62144. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  62145. */
  62146. var HemisphericParticleEmitter = /** @class */ (function () {
  62147. /**
  62148. * Creates a new instance HemisphericParticleEmitter
  62149. * @param radius the radius of the emission hemisphere (1 by default)
  62150. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62151. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62152. */
  62153. function HemisphericParticleEmitter(
  62154. /**
  62155. * The radius of the emission hemisphere.
  62156. */
  62157. radius,
  62158. /**
  62159. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62160. */
  62161. radiusRange,
  62162. /**
  62163. * How much to randomize the particle direction [0-1].
  62164. */
  62165. directionRandomizer) {
  62166. if (radius === void 0) { radius = 1; }
  62167. if (radiusRange === void 0) { radiusRange = 1; }
  62168. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62169. this.radius = radius;
  62170. this.radiusRange = radiusRange;
  62171. this.directionRandomizer = directionRandomizer;
  62172. }
  62173. /**
  62174. * Called by the particle System when the direction is computed for the created particle.
  62175. * @param worldMatrix is the world matrix of the particle system
  62176. * @param directionToUpdate is the direction vector to update with the result
  62177. * @param particle is the particle we are computed the direction for
  62178. */
  62179. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62180. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62181. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62182. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62183. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  62184. direction.x += randX;
  62185. direction.y += randY;
  62186. direction.z += randZ;
  62187. direction.normalize();
  62188. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62189. };
  62190. /**
  62191. * Called by the particle System when the position is computed for the created particle.
  62192. * @param worldMatrix is the world matrix of the particle system
  62193. * @param positionToUpdate is the position vector to update with the result
  62194. * @param particle is the particle we are computed the position for
  62195. */
  62196. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62197. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  62198. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  62199. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62200. var theta = Math.acos(2 * v - 1);
  62201. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  62202. var randY = randRadius * Math.cos(theta);
  62203. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  62204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  62205. };
  62206. /**
  62207. * Clones the current emitter and returns a copy of it
  62208. * @returns the new emitter
  62209. */
  62210. HemisphericParticleEmitter.prototype.clone = function () {
  62211. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  62212. BABYLON.Tools.DeepCopy(this, newOne);
  62213. return newOne;
  62214. };
  62215. /**
  62216. * Called by the GPUParticleSystem to setup the update shader
  62217. * @param effect defines the update shader
  62218. */
  62219. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  62220. effect.setFloat("radius", this.radius);
  62221. effect.setFloat("radiusRange", this.radiusRange);
  62222. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62223. };
  62224. /**
  62225. * Returns a string to use to update the GPU particles update shader
  62226. * @returns a string containng the defines string
  62227. */
  62228. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  62229. return "#define HEMISPHERICEMITTER";
  62230. };
  62231. /**
  62232. * Returns the string "HemisphericParticleEmitter"
  62233. * @returns a string containing the class name
  62234. */
  62235. HemisphericParticleEmitter.prototype.getClassName = function () {
  62236. return "HemisphericParticleEmitter";
  62237. };
  62238. /**
  62239. * Serializes the particle system to a JSON object.
  62240. * @returns the JSON object
  62241. */
  62242. HemisphericParticleEmitter.prototype.serialize = function () {
  62243. var serializationObject = {};
  62244. serializationObject.type = this.getClassName();
  62245. serializationObject.radius = this.radius;
  62246. serializationObject.radiusRange = this.radiusRange;
  62247. serializationObject.directionRandomizer = this.directionRandomizer;
  62248. return serializationObject;
  62249. };
  62250. /**
  62251. * Parse properties from a JSON object
  62252. * @param serializationObject defines the JSON object
  62253. */
  62254. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  62255. this.radius = serializationObject.radius;
  62256. this.radiusRange = serializationObject.radiusRange;
  62257. this.directionRandomizer = serializationObject.directionRandomizer;
  62258. };
  62259. return HemisphericParticleEmitter;
  62260. }());
  62261. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  62262. })(BABYLON || (BABYLON = {}));
  62263. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  62264. var BABYLON;
  62265. (function (BABYLON) {
  62266. /**
  62267. * Particle emitter emitting particles from a point.
  62268. * It emits the particles randomly between 2 given directions.
  62269. */
  62270. var PointParticleEmitter = /** @class */ (function () {
  62271. /**
  62272. * Creates a new instance PointParticleEmitter
  62273. */
  62274. function PointParticleEmitter() {
  62275. /**
  62276. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62277. */
  62278. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62279. /**
  62280. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62281. */
  62282. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62283. }
  62284. /**
  62285. * Called by the particle System when the direction is computed for the created particle.
  62286. * @param worldMatrix is the world matrix of the particle system
  62287. * @param directionToUpdate is the direction vector to update with the result
  62288. * @param particle is the particle we are computed the direction for
  62289. */
  62290. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62291. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62292. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62293. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62294. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62295. };
  62296. /**
  62297. * Called by the particle System when the position is computed for the created particle.
  62298. * @param worldMatrix is the world matrix of the particle system
  62299. * @param positionToUpdate is the position vector to update with the result
  62300. * @param particle is the particle we are computed the position for
  62301. */
  62302. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62303. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  62304. };
  62305. /**
  62306. * Clones the current emitter and returns a copy of it
  62307. * @returns the new emitter
  62308. */
  62309. PointParticleEmitter.prototype.clone = function () {
  62310. var newOne = new PointParticleEmitter();
  62311. BABYLON.Tools.DeepCopy(this, newOne);
  62312. return newOne;
  62313. };
  62314. /**
  62315. * Called by the GPUParticleSystem to setup the update shader
  62316. * @param effect defines the update shader
  62317. */
  62318. PointParticleEmitter.prototype.applyToShader = function (effect) {
  62319. effect.setVector3("direction1", this.direction1);
  62320. effect.setVector3("direction2", this.direction2);
  62321. };
  62322. /**
  62323. * Returns a string to use to update the GPU particles update shader
  62324. * @returns a string containng the defines string
  62325. */
  62326. PointParticleEmitter.prototype.getEffectDefines = function () {
  62327. return "#define POINTEMITTER";
  62328. };
  62329. /**
  62330. * Returns the string "PointParticleEmitter"
  62331. * @returns a string containing the class name
  62332. */
  62333. PointParticleEmitter.prototype.getClassName = function () {
  62334. return "PointParticleEmitter";
  62335. };
  62336. /**
  62337. * Serializes the particle system to a JSON object.
  62338. * @returns the JSON object
  62339. */
  62340. PointParticleEmitter.prototype.serialize = function () {
  62341. var serializationObject = {};
  62342. serializationObject.type = this.getClassName();
  62343. serializationObject.direction1 = this.direction1.asArray();
  62344. serializationObject.direction2 = this.direction2.asArray();
  62345. return serializationObject;
  62346. };
  62347. /**
  62348. * Parse properties from a JSON object
  62349. * @param serializationObject defines the JSON object
  62350. */
  62351. PointParticleEmitter.prototype.parse = function (serializationObject) {
  62352. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62353. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62354. };
  62355. return PointParticleEmitter;
  62356. }());
  62357. BABYLON.PointParticleEmitter = PointParticleEmitter;
  62358. })(BABYLON || (BABYLON = {}));
  62359. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  62360. var BABYLON;
  62361. (function (BABYLON) {
  62362. // Adds the parsers to the scene parsers.
  62363. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  62364. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  62365. if (!individualParser) {
  62366. return;
  62367. }
  62368. // Particles Systems
  62369. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62370. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62371. var parsedParticleSystem = parsedData.particleSystems[index];
  62372. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  62373. }
  62374. }
  62375. });
  62376. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  62377. if (parsedParticleSystem.activeParticleCount) {
  62378. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62379. return ps;
  62380. }
  62381. else {
  62382. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62383. return ps;
  62384. }
  62385. });
  62386. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  62387. if (uniformsNames === void 0) { uniformsNames = []; }
  62388. if (samplers === void 0) { samplers = []; }
  62389. if (defines === void 0) { defines = ""; }
  62390. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  62391. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  62392. if (defines.indexOf(" BILLBOARD") === -1) {
  62393. defines += "\n#define BILLBOARD\n";
  62394. }
  62395. if (samplers.indexOf("diffuseSampler") === -1) {
  62396. samplers.push("diffuseSampler");
  62397. }
  62398. return this.createEffect({
  62399. vertex: "particles",
  62400. fragmentElement: fragmentName
  62401. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  62402. };
  62403. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  62404. var results = new Array();
  62405. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62406. var particleSystem = this.getScene().particleSystems[index];
  62407. if (particleSystem.emitter === this) {
  62408. results.push(particleSystem);
  62409. }
  62410. }
  62411. return results;
  62412. };
  62413. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  62414. var results = new Array();
  62415. var descendants = this.getDescendants();
  62416. descendants.push(this);
  62417. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62418. var particleSystem = this.getScene().particleSystems[index];
  62419. var emitter = particleSystem.emitter;
  62420. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  62421. results.push(particleSystem);
  62422. }
  62423. }
  62424. return results;
  62425. };
  62426. })(BABYLON || (BABYLON = {}));
  62427. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  62428. var BABYLON;
  62429. (function (BABYLON) {
  62430. /**
  62431. * Type of sub emitter
  62432. */
  62433. var SubEmitterType;
  62434. (function (SubEmitterType) {
  62435. /**
  62436. * Attached to the particle over it's lifetime
  62437. */
  62438. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  62439. /**
  62440. * Created when the particle dies
  62441. */
  62442. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  62443. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  62444. /**
  62445. * Sub emitter class used to emit particles from an existing particle
  62446. */
  62447. var SubEmitter = /** @class */ (function () {
  62448. /**
  62449. * Creates a sub emitter
  62450. * @param particleSystem the particle system to be used by the sub emitter
  62451. */
  62452. function SubEmitter(
  62453. /**
  62454. * the particle system to be used by the sub emitter
  62455. */
  62456. particleSystem) {
  62457. this.particleSystem = particleSystem;
  62458. /**
  62459. * Type of the submitter (Default: END)
  62460. */
  62461. this.type = SubEmitterType.END;
  62462. /**
  62463. * 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)
  62464. * Note: This only is supported when using an emitter of type Mesh
  62465. */
  62466. this.inheritDirection = false;
  62467. /**
  62468. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  62469. */
  62470. this.inheritedVelocityAmount = 0;
  62471. // Create mesh as emitter to support rotation
  62472. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  62473. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  62474. }
  62475. // Automatically dispose of subemitter when system is disposed
  62476. particleSystem.onDisposeObservable.add(function () {
  62477. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  62478. particleSystem.emitter.dispose();
  62479. }
  62480. });
  62481. }
  62482. /**
  62483. * Clones the sub emitter
  62484. * @returns the cloned sub emitter
  62485. */
  62486. SubEmitter.prototype.clone = function () {
  62487. // Clone particle system
  62488. var emitter = this.particleSystem.emitter;
  62489. if (!emitter) {
  62490. emitter = new BABYLON.Vector3();
  62491. }
  62492. else if (emitter instanceof BABYLON.Vector3) {
  62493. emitter = emitter.clone();
  62494. }
  62495. else if (emitter instanceof BABYLON.AbstractMesh) {
  62496. emitter = new BABYLON.Mesh("", emitter.getScene());
  62497. emitter.isVisible = false;
  62498. }
  62499. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  62500. // Clone properties
  62501. clone.type = this.type;
  62502. clone.inheritDirection = this.inheritDirection;
  62503. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62504. clone.particleSystem._disposeEmitterOnDispose = true;
  62505. clone.particleSystem.disposeOnStop = true;
  62506. return clone;
  62507. };
  62508. /**
  62509. * Serialize current object to a JSON object
  62510. * @returns the serialized object
  62511. */
  62512. SubEmitter.prototype.serialize = function () {
  62513. var serializationObject = {};
  62514. serializationObject.type = this.type;
  62515. serializationObject.inheritDirection = this.inheritDirection;
  62516. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62517. serializationObject.particleSystem = this.particleSystem.serialize();
  62518. return serializationObject;
  62519. };
  62520. /**
  62521. * Creates a new SubEmitter from a serialized JSON version
  62522. * @param serializationObject defines the JSON object to read from
  62523. * @param scene defines the hosting scene
  62524. * @param rootUrl defines the rootUrl for data loading
  62525. * @returns a new SubEmitter
  62526. */
  62527. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  62528. var system = serializationObject.particleSystem;
  62529. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  62530. subEmitter.type = serializationObject.type;
  62531. subEmitter.inheritDirection = serializationObject.inheritDirection;
  62532. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  62533. subEmitter.particleSystem._isSubEmitter = true;
  62534. return subEmitter;
  62535. };
  62536. /** Release associated resources */
  62537. SubEmitter.prototype.dispose = function () {
  62538. this.particleSystem.dispose();
  62539. };
  62540. return SubEmitter;
  62541. }());
  62542. BABYLON.SubEmitter = SubEmitter;
  62543. })(BABYLON || (BABYLON = {}));
  62544. //# sourceMappingURL=babylon.subEmitter.js.map
  62545. var BABYLON;
  62546. (function (BABYLON) {
  62547. /**
  62548. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  62549. *
  62550. * This returned material effects how the mesh will look based on the code in the shaders.
  62551. *
  62552. * @see http://doc.babylonjs.com/how_to/shader_material
  62553. */
  62554. var ShaderMaterial = /** @class */ (function (_super) {
  62555. __extends(ShaderMaterial, _super);
  62556. /**
  62557. * Instantiate a new shader material.
  62558. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  62559. * This returned material effects how the mesh will look based on the code in the shaders.
  62560. * @see http://doc.babylonjs.com/how_to/shader_material
  62561. * @param name Define the name of the material in the scene
  62562. * @param scene Define the scene the material belongs to
  62563. * @param shaderPath Defines the route to the shader code in one of three ways:
  62564. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  62565. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  62566. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  62567. * @param options Define the options used to create the shader
  62568. */
  62569. function ShaderMaterial(name, scene, shaderPath, options) {
  62570. if (options === void 0) { options = {}; }
  62571. var _this = _super.call(this, name, scene) || this;
  62572. _this._textures = {};
  62573. _this._textureArrays = {};
  62574. _this._floats = {};
  62575. _this._ints = {};
  62576. _this._floatsArrays = {};
  62577. _this._colors3 = {};
  62578. _this._colors3Arrays = {};
  62579. _this._colors4 = {};
  62580. _this._vectors2 = {};
  62581. _this._vectors3 = {};
  62582. _this._vectors4 = {};
  62583. _this._matrices = {};
  62584. _this._matrices3x3 = {};
  62585. _this._matrices2x2 = {};
  62586. _this._vectors2Arrays = {};
  62587. _this._vectors3Arrays = {};
  62588. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  62589. _this._shaderPath = shaderPath;
  62590. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  62591. return _this;
  62592. }
  62593. /**
  62594. * Gets the current class name of the material e.g. "ShaderMaterial"
  62595. * Mainly use in serialization.
  62596. * @returns the class name
  62597. */
  62598. ShaderMaterial.prototype.getClassName = function () {
  62599. return "ShaderMaterial";
  62600. };
  62601. /**
  62602. * Specifies if the material will require alpha blending
  62603. * @returns a boolean specifying if alpha blending is needed
  62604. */
  62605. ShaderMaterial.prototype.needAlphaBlending = function () {
  62606. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  62607. };
  62608. /**
  62609. * Specifies if this material should be rendered in alpha test mode
  62610. * @returns a boolean specifying if an alpha test is needed.
  62611. */
  62612. ShaderMaterial.prototype.needAlphaTesting = function () {
  62613. return this._options.needAlphaTesting;
  62614. };
  62615. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  62616. if (this._options.uniforms.indexOf(uniformName) === -1) {
  62617. this._options.uniforms.push(uniformName);
  62618. }
  62619. };
  62620. /**
  62621. * Set a texture in the shader.
  62622. * @param name Define the name of the uniform samplers as defined in the shader
  62623. * @param texture Define the texture to bind to this sampler
  62624. * @return the material itself allowing "fluent" like uniform updates
  62625. */
  62626. ShaderMaterial.prototype.setTexture = function (name, texture) {
  62627. if (this._options.samplers.indexOf(name) === -1) {
  62628. this._options.samplers.push(name);
  62629. }
  62630. this._textures[name] = texture;
  62631. return this;
  62632. };
  62633. /**
  62634. * Set a texture array in the shader.
  62635. * @param name Define the name of the uniform sampler array as defined in the shader
  62636. * @param textures Define the list of textures to bind to this sampler
  62637. * @return the material itself allowing "fluent" like uniform updates
  62638. */
  62639. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  62640. if (this._options.samplers.indexOf(name) === -1) {
  62641. this._options.samplers.push(name);
  62642. }
  62643. this._checkUniform(name);
  62644. this._textureArrays[name] = textures;
  62645. return this;
  62646. };
  62647. /**
  62648. * Set a float in the shader.
  62649. * @param name Define the name of the uniform as defined in the shader
  62650. * @param value Define the value to give to the uniform
  62651. * @return the material itself allowing "fluent" like uniform updates
  62652. */
  62653. ShaderMaterial.prototype.setFloat = function (name, value) {
  62654. this._checkUniform(name);
  62655. this._floats[name] = value;
  62656. return this;
  62657. };
  62658. /**
  62659. * Set a int in the shader.
  62660. * @param name Define the name of the uniform as defined in the shader
  62661. * @param value Define the value to give to the uniform
  62662. * @return the material itself allowing "fluent" like uniform updates
  62663. */
  62664. ShaderMaterial.prototype.setInt = function (name, value) {
  62665. this._checkUniform(name);
  62666. this._ints[name] = value;
  62667. return this;
  62668. };
  62669. /**
  62670. * Set an array of floats in the shader.
  62671. * @param name Define the name of the uniform as defined in the shader
  62672. * @param value Define the value to give to the uniform
  62673. * @return the material itself allowing "fluent" like uniform updates
  62674. */
  62675. ShaderMaterial.prototype.setFloats = function (name, value) {
  62676. this._checkUniform(name);
  62677. this._floatsArrays[name] = value;
  62678. return this;
  62679. };
  62680. /**
  62681. * Set a vec3 in the shader from a Color3.
  62682. * @param name Define the name of the uniform as defined in the shader
  62683. * @param value Define the value to give to the uniform
  62684. * @return the material itself allowing "fluent" like uniform updates
  62685. */
  62686. ShaderMaterial.prototype.setColor3 = function (name, value) {
  62687. this._checkUniform(name);
  62688. this._colors3[name] = value;
  62689. return this;
  62690. };
  62691. /**
  62692. * Set a vec3 array in the shader from a Color3 array.
  62693. * @param name Define the name of the uniform as defined in the shader
  62694. * @param value Define the value to give to the uniform
  62695. * @return the material itself allowing "fluent" like uniform updates
  62696. */
  62697. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  62698. this._checkUniform(name);
  62699. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  62700. color.toArray(arr, arr.length);
  62701. return arr;
  62702. }, []);
  62703. return this;
  62704. };
  62705. /**
  62706. * Set a vec4 in the shader from a Color4.
  62707. * @param name Define the name of the uniform as defined in the shader
  62708. * @param value Define the value to give to the uniform
  62709. * @return the material itself allowing "fluent" like uniform updates
  62710. */
  62711. ShaderMaterial.prototype.setColor4 = function (name, value) {
  62712. this._checkUniform(name);
  62713. this._colors4[name] = value;
  62714. return this;
  62715. };
  62716. /**
  62717. * Set a vec2 in the shader from a Vector2.
  62718. * @param name Define the name of the uniform as defined in the shader
  62719. * @param value Define the value to give to the uniform
  62720. * @return the material itself allowing "fluent" like uniform updates
  62721. */
  62722. ShaderMaterial.prototype.setVector2 = function (name, value) {
  62723. this._checkUniform(name);
  62724. this._vectors2[name] = value;
  62725. return this;
  62726. };
  62727. /**
  62728. * Set a vec3 in the shader from a Vector3.
  62729. * @param name Define the name of the uniform as defined in the shader
  62730. * @param value Define the value to give to the uniform
  62731. * @return the material itself allowing "fluent" like uniform updates
  62732. */
  62733. ShaderMaterial.prototype.setVector3 = function (name, value) {
  62734. this._checkUniform(name);
  62735. this._vectors3[name] = value;
  62736. return this;
  62737. };
  62738. /**
  62739. * Set a vec4 in the shader from a Vector4.
  62740. * @param name Define the name of the uniform as defined in the shader
  62741. * @param value Define the value to give to the uniform
  62742. * @return the material itself allowing "fluent" like uniform updates
  62743. */
  62744. ShaderMaterial.prototype.setVector4 = function (name, value) {
  62745. this._checkUniform(name);
  62746. this._vectors4[name] = value;
  62747. return this;
  62748. };
  62749. /**
  62750. * Set a mat4 in the shader from a Matrix.
  62751. * @param name Define the name of the uniform as defined in the shader
  62752. * @param value Define the value to give to the uniform
  62753. * @return the material itself allowing "fluent" like uniform updates
  62754. */
  62755. ShaderMaterial.prototype.setMatrix = function (name, value) {
  62756. this._checkUniform(name);
  62757. this._matrices[name] = value;
  62758. return this;
  62759. };
  62760. /**
  62761. * Set a mat3 in the shader from a Float32Array.
  62762. * @param name Define the name of the uniform as defined in the shader
  62763. * @param value Define the value to give to the uniform
  62764. * @return the material itself allowing "fluent" like uniform updates
  62765. */
  62766. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  62767. this._checkUniform(name);
  62768. this._matrices3x3[name] = value;
  62769. return this;
  62770. };
  62771. /**
  62772. * Set a mat2 in the shader from a Float32Array.
  62773. * @param name Define the name of the uniform as defined in the shader
  62774. * @param value Define the value to give to the uniform
  62775. * @return the material itself allowing "fluent" like uniform updates
  62776. */
  62777. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  62778. this._checkUniform(name);
  62779. this._matrices2x2[name] = value;
  62780. return this;
  62781. };
  62782. /**
  62783. * Set a vec2 array in the shader from a number array.
  62784. * @param name Define the name of the uniform as defined in the shader
  62785. * @param value Define the value to give to the uniform
  62786. * @return the material itself allowing "fluent" like uniform updates
  62787. */
  62788. ShaderMaterial.prototype.setArray2 = function (name, value) {
  62789. this._checkUniform(name);
  62790. this._vectors2Arrays[name] = value;
  62791. return this;
  62792. };
  62793. /**
  62794. * Set a vec3 array in the shader from a number array.
  62795. * @param name Define the name of the uniform as defined in the shader
  62796. * @param value Define the value to give to the uniform
  62797. * @return the material itself allowing "fluent" like uniform updates
  62798. */
  62799. ShaderMaterial.prototype.setArray3 = function (name, value) {
  62800. this._checkUniform(name);
  62801. this._vectors3Arrays[name] = value;
  62802. return this;
  62803. };
  62804. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  62805. if (!mesh) {
  62806. return true;
  62807. }
  62808. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  62809. return false;
  62810. }
  62811. return false;
  62812. };
  62813. /**
  62814. * Checks if the material is ready to render the requested mesh
  62815. * @param mesh Define the mesh to render
  62816. * @param useInstances Define whether or not the material is used with instances
  62817. * @returns true if ready, otherwise false
  62818. */
  62819. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  62820. var scene = this.getScene();
  62821. var engine = scene.getEngine();
  62822. if (!this.checkReadyOnEveryCall) {
  62823. if (this._renderId === scene.getRenderId()) {
  62824. if (this._checkCache(scene, mesh, useInstances)) {
  62825. return true;
  62826. }
  62827. }
  62828. }
  62829. // Instances
  62830. var defines = [];
  62831. var attribs = [];
  62832. var fallbacks = new BABYLON.EffectFallbacks();
  62833. for (var index = 0; index < this._options.defines.length; index++) {
  62834. defines.push(this._options.defines[index]);
  62835. }
  62836. for (var index = 0; index < this._options.attributes.length; index++) {
  62837. attribs.push(this._options.attributes[index]);
  62838. }
  62839. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62840. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62841. defines.push("#define VERTEXCOLOR");
  62842. }
  62843. if (useInstances) {
  62844. defines.push("#define INSTANCES");
  62845. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  62846. }
  62847. // Bones
  62848. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62851. if (mesh.numBoneInfluencers > 4) {
  62852. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62853. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62854. }
  62855. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62856. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62857. fallbacks.addCPUSkinningFallback(0, mesh);
  62858. if (this._options.uniforms.indexOf("mBones") === -1) {
  62859. this._options.uniforms.push("mBones");
  62860. }
  62861. }
  62862. else {
  62863. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62864. }
  62865. // Textures
  62866. for (var name in this._textures) {
  62867. if (!this._textures[name].isReady()) {
  62868. return false;
  62869. }
  62870. }
  62871. // Alpha test
  62872. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  62873. defines.push("#define ALPHATEST");
  62874. }
  62875. var previousEffect = this._effect;
  62876. var join = defines.join("\n");
  62877. this._effect = engine.createEffect(this._shaderPath, {
  62878. attributes: attribs,
  62879. uniformsNames: this._options.uniforms,
  62880. uniformBuffersNames: this._options.uniformBuffers,
  62881. samplers: this._options.samplers,
  62882. defines: join,
  62883. fallbacks: fallbacks,
  62884. onCompiled: this.onCompiled,
  62885. onError: this.onError
  62886. }, engine);
  62887. if (!this._effect.isReady()) {
  62888. return false;
  62889. }
  62890. if (previousEffect !== this._effect) {
  62891. scene.resetCachedMaterial();
  62892. }
  62893. this._renderId = scene.getRenderId();
  62894. return true;
  62895. };
  62896. /**
  62897. * Binds the world matrix to the material
  62898. * @param world defines the world transformation matrix
  62899. */
  62900. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62901. var scene = this.getScene();
  62902. if (!this._effect) {
  62903. return;
  62904. }
  62905. if (this._options.uniforms.indexOf("world") !== -1) {
  62906. this._effect.setMatrix("world", world);
  62907. }
  62908. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62909. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62910. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62911. }
  62912. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62913. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62914. }
  62915. };
  62916. /**
  62917. * Binds the material to the mesh
  62918. * @param world defines the world transformation matrix
  62919. * @param mesh defines the mesh to bind the material to
  62920. */
  62921. ShaderMaterial.prototype.bind = function (world, mesh) {
  62922. // Std values
  62923. this.bindOnlyWorldMatrix(world);
  62924. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62925. if (this._options.uniforms.indexOf("view") !== -1) {
  62926. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62927. }
  62928. if (this._options.uniforms.indexOf("projection") !== -1) {
  62929. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62930. }
  62931. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62932. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62933. }
  62934. // Bones
  62935. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62936. var name;
  62937. // Texture
  62938. for (name in this._textures) {
  62939. this._effect.setTexture(name, this._textures[name]);
  62940. }
  62941. // Texture arrays
  62942. for (name in this._textureArrays) {
  62943. this._effect.setTextureArray(name, this._textureArrays[name]);
  62944. }
  62945. // Int
  62946. for (name in this._ints) {
  62947. this._effect.setInt(name, this._ints[name]);
  62948. }
  62949. // Float
  62950. for (name in this._floats) {
  62951. this._effect.setFloat(name, this._floats[name]);
  62952. }
  62953. // Floats
  62954. for (name in this._floatsArrays) {
  62955. this._effect.setArray(name, this._floatsArrays[name]);
  62956. }
  62957. // Color3
  62958. for (name in this._colors3) {
  62959. this._effect.setColor3(name, this._colors3[name]);
  62960. }
  62961. for (name in this._colors3Arrays) {
  62962. this._effect.setArray3(name, this._colors3Arrays[name]);
  62963. }
  62964. // Color4
  62965. for (name in this._colors4) {
  62966. var color = this._colors4[name];
  62967. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62968. }
  62969. // Vector2
  62970. for (name in this._vectors2) {
  62971. this._effect.setVector2(name, this._vectors2[name]);
  62972. }
  62973. // Vector3
  62974. for (name in this._vectors3) {
  62975. this._effect.setVector3(name, this._vectors3[name]);
  62976. }
  62977. // Vector4
  62978. for (name in this._vectors4) {
  62979. this._effect.setVector4(name, this._vectors4[name]);
  62980. }
  62981. // Matrix
  62982. for (name in this._matrices) {
  62983. this._effect.setMatrix(name, this._matrices[name]);
  62984. }
  62985. // Matrix 3x3
  62986. for (name in this._matrices3x3) {
  62987. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62988. }
  62989. // Matrix 2x2
  62990. for (name in this._matrices2x2) {
  62991. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62992. }
  62993. // Vector2Array
  62994. for (name in this._vectors2Arrays) {
  62995. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62996. }
  62997. // Vector3Array
  62998. for (name in this._vectors3Arrays) {
  62999. this._effect.setArray3(name, this._vectors3Arrays[name]);
  63000. }
  63001. }
  63002. this._afterBind(mesh);
  63003. };
  63004. /**
  63005. * Gets the active textures from the material
  63006. * @returns an array of textures
  63007. */
  63008. ShaderMaterial.prototype.getActiveTextures = function () {
  63009. var activeTextures = _super.prototype.getActiveTextures.call(this);
  63010. for (var name in this._textures) {
  63011. activeTextures.push(this._textures[name]);
  63012. }
  63013. for (var name in this._textureArrays) {
  63014. var array = this._textureArrays[name];
  63015. for (var index = 0; index < array.length; index++) {
  63016. activeTextures.push(array[index]);
  63017. }
  63018. }
  63019. return activeTextures;
  63020. };
  63021. /**
  63022. * Specifies if the material uses a texture
  63023. * @param texture defines the texture to check against the material
  63024. * @returns a boolean specifying if the material uses the texture
  63025. */
  63026. ShaderMaterial.prototype.hasTexture = function (texture) {
  63027. if (_super.prototype.hasTexture.call(this, texture)) {
  63028. return true;
  63029. }
  63030. for (var name in this._textures) {
  63031. if (this._textures[name] === texture) {
  63032. return true;
  63033. }
  63034. }
  63035. for (var name in this._textureArrays) {
  63036. var array = this._textureArrays[name];
  63037. for (var index = 0; index < array.length; index++) {
  63038. if (array[index] === texture) {
  63039. return true;
  63040. }
  63041. }
  63042. }
  63043. return false;
  63044. };
  63045. /**
  63046. * Makes a duplicate of the material, and gives it a new name
  63047. * @param name defines the new name for the duplicated material
  63048. * @returns the cloned material
  63049. */
  63050. ShaderMaterial.prototype.clone = function (name) {
  63051. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  63052. return newShaderMaterial;
  63053. };
  63054. /**
  63055. * Disposes the material
  63056. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  63057. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  63058. */
  63059. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  63060. if (forceDisposeTextures) {
  63061. var name;
  63062. for (name in this._textures) {
  63063. this._textures[name].dispose();
  63064. }
  63065. for (name in this._textureArrays) {
  63066. var array = this._textureArrays[name];
  63067. for (var index = 0; index < array.length; index++) {
  63068. array[index].dispose();
  63069. }
  63070. }
  63071. }
  63072. this._textures = {};
  63073. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  63074. };
  63075. /**
  63076. * Serializes this material in a JSON representation
  63077. * @returns the serialized material object
  63078. */
  63079. ShaderMaterial.prototype.serialize = function () {
  63080. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63081. serializationObject.customType = "BABYLON.ShaderMaterial";
  63082. serializationObject.options = this._options;
  63083. serializationObject.shaderPath = this._shaderPath;
  63084. var name;
  63085. // Texture
  63086. serializationObject.textures = {};
  63087. for (name in this._textures) {
  63088. serializationObject.textures[name] = this._textures[name].serialize();
  63089. }
  63090. // Texture arrays
  63091. serializationObject.textureArrays = {};
  63092. for (name in this._textureArrays) {
  63093. serializationObject.textureArrays[name] = [];
  63094. var array = this._textureArrays[name];
  63095. for (var index = 0; index < array.length; index++) {
  63096. serializationObject.textureArrays[name].push(array[index].serialize());
  63097. }
  63098. }
  63099. // Float
  63100. serializationObject.floats = {};
  63101. for (name in this._floats) {
  63102. serializationObject.floats[name] = this._floats[name];
  63103. }
  63104. // Float s
  63105. serializationObject.FloatArrays = {};
  63106. for (name in this._floatsArrays) {
  63107. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  63108. }
  63109. // Color3
  63110. serializationObject.colors3 = {};
  63111. for (name in this._colors3) {
  63112. serializationObject.colors3[name] = this._colors3[name].asArray();
  63113. }
  63114. // Color3 array
  63115. serializationObject.colors3Arrays = {};
  63116. for (name in this._colors3Arrays) {
  63117. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  63118. }
  63119. // Color4
  63120. serializationObject.colors4 = {};
  63121. for (name in this._colors4) {
  63122. serializationObject.colors4[name] = this._colors4[name].asArray();
  63123. }
  63124. // Vector2
  63125. serializationObject.vectors2 = {};
  63126. for (name in this._vectors2) {
  63127. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  63128. }
  63129. // Vector3
  63130. serializationObject.vectors3 = {};
  63131. for (name in this._vectors3) {
  63132. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  63133. }
  63134. // Vector4
  63135. serializationObject.vectors4 = {};
  63136. for (name in this._vectors4) {
  63137. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  63138. }
  63139. // Matrix
  63140. serializationObject.matrices = {};
  63141. for (name in this._matrices) {
  63142. serializationObject.matrices[name] = this._matrices[name].asArray();
  63143. }
  63144. // Matrix 3x3
  63145. serializationObject.matrices3x3 = {};
  63146. for (name in this._matrices3x3) {
  63147. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  63148. }
  63149. // Matrix 2x2
  63150. serializationObject.matrices2x2 = {};
  63151. for (name in this._matrices2x2) {
  63152. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  63153. }
  63154. // Vector2Array
  63155. serializationObject.vectors2Arrays = {};
  63156. for (name in this._vectors2Arrays) {
  63157. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  63158. }
  63159. // Vector3Array
  63160. serializationObject.vectors3Arrays = {};
  63161. for (name in this._vectors3Arrays) {
  63162. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  63163. }
  63164. return serializationObject;
  63165. };
  63166. /**
  63167. * Creates a shader material from parsed shader material data
  63168. * @param source defines the JSON represnetation of the material
  63169. * @param scene defines the hosting scene
  63170. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  63171. * @returns a new material
  63172. */
  63173. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  63174. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  63175. var name;
  63176. // Texture
  63177. for (name in source.textures) {
  63178. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  63179. }
  63180. // Texture arrays
  63181. for (name in source.textureArrays) {
  63182. var array = source.textureArrays[name];
  63183. var textureArray = new Array();
  63184. for (var index = 0; index < array.length; index++) {
  63185. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  63186. }
  63187. material.setTextureArray(name, textureArray);
  63188. }
  63189. // Float
  63190. for (name in source.floats) {
  63191. material.setFloat(name, source.floats[name]);
  63192. }
  63193. // Float s
  63194. for (name in source.floatsArrays) {
  63195. material.setFloats(name, source.floatsArrays[name]);
  63196. }
  63197. // Color3
  63198. for (name in source.colors3) {
  63199. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  63200. }
  63201. // Color3 arrays
  63202. for (name in source.colors3Arrays) {
  63203. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  63204. if (i % 3 === 0) {
  63205. arr.push([num]);
  63206. }
  63207. else {
  63208. arr[arr.length - 1].push(num);
  63209. }
  63210. return arr;
  63211. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  63212. material.setColor3Array(name, colors);
  63213. }
  63214. // Color4
  63215. for (name in source.colors4) {
  63216. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  63217. }
  63218. // Vector2
  63219. for (name in source.vectors2) {
  63220. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  63221. }
  63222. // Vector3
  63223. for (name in source.vectors3) {
  63224. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  63225. }
  63226. // Vector4
  63227. for (name in source.vectors4) {
  63228. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  63229. }
  63230. // Matrix
  63231. for (name in source.matrices) {
  63232. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  63233. }
  63234. // Matrix 3x3
  63235. for (name in source.matrices3x3) {
  63236. material.setMatrix3x3(name, source.matrices3x3[name]);
  63237. }
  63238. // Matrix 2x2
  63239. for (name in source.matrices2x2) {
  63240. material.setMatrix2x2(name, source.matrices2x2[name]);
  63241. }
  63242. // Vector2Array
  63243. for (name in source.vectors2Arrays) {
  63244. material.setArray2(name, source.vectors2Arrays[name]);
  63245. }
  63246. // Vector3Array
  63247. for (name in source.vectors3Arrays) {
  63248. material.setArray3(name, source.vectors3Arrays[name]);
  63249. }
  63250. return material;
  63251. };
  63252. return ShaderMaterial;
  63253. }(BABYLON.Material));
  63254. BABYLON.ShaderMaterial = ShaderMaterial;
  63255. })(BABYLON || (BABYLON = {}));
  63256. //# sourceMappingURL=babylon.shaderMaterial.js.map
  63257. var BABYLON;
  63258. (function (BABYLON) {
  63259. /**
  63260. * Mesh representing the gorund
  63261. */
  63262. var GroundMesh = /** @class */ (function (_super) {
  63263. __extends(GroundMesh, _super);
  63264. function GroundMesh(name, scene) {
  63265. var _this = _super.call(this, name, scene) || this;
  63266. /** If octree should be generated */
  63267. _this.generateOctree = false;
  63268. return _this;
  63269. }
  63270. /**
  63271. * "GroundMesh"
  63272. * @returns "GroundMesh"
  63273. */
  63274. GroundMesh.prototype.getClassName = function () {
  63275. return "GroundMesh";
  63276. };
  63277. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  63278. /**
  63279. * The minimum of x and y subdivisions
  63280. */
  63281. get: function () {
  63282. return Math.min(this._subdivisionsX, this._subdivisionsY);
  63283. },
  63284. enumerable: true,
  63285. configurable: true
  63286. });
  63287. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  63288. /**
  63289. * X subdivisions
  63290. */
  63291. get: function () {
  63292. return this._subdivisionsX;
  63293. },
  63294. enumerable: true,
  63295. configurable: true
  63296. });
  63297. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  63298. /**
  63299. * Y subdivisions
  63300. */
  63301. get: function () {
  63302. return this._subdivisionsY;
  63303. },
  63304. enumerable: true,
  63305. configurable: true
  63306. });
  63307. /**
  63308. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  63309. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  63310. * @param chunksCount the number of subdivisions for x and y
  63311. * @param octreeBlocksSize (Default: 32)
  63312. */
  63313. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  63314. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  63315. this._subdivisionsX = chunksCount;
  63316. this._subdivisionsY = chunksCount;
  63317. this.subdivide(chunksCount);
  63318. // Call the octree system optimization if it is defined.
  63319. var thisAsAny = this;
  63320. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  63321. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  63322. }
  63323. };
  63324. /**
  63325. * Returns a height (y) value in the Worl system :
  63326. * the ground altitude at the coordinates (x, z) expressed in the World system.
  63327. * @param x x coordinate
  63328. * @param z z coordinate
  63329. * @returns the ground y position if (x, z) are outside the ground surface.
  63330. */
  63331. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  63332. var world = this.getWorldMatrix();
  63333. var invMat = BABYLON.Tmp.Matrix[5];
  63334. world.invertToRef(invMat);
  63335. var tmpVect = BABYLON.Tmp.Vector3[8];
  63336. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  63337. x = tmpVect.x;
  63338. z = tmpVect.z;
  63339. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63340. return this.position.y;
  63341. }
  63342. if (!this._heightQuads || this._heightQuads.length == 0) {
  63343. this._initHeightQuads();
  63344. this._computeHeightQuads();
  63345. }
  63346. var facet = this._getFacetAt(x, z);
  63347. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  63348. // return y in the World system
  63349. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  63350. return tmpVect.y;
  63351. };
  63352. /**
  63353. * Returns a normalized vector (Vector3) orthogonal to the ground
  63354. * at the ground coordinates (x, z) expressed in the World system.
  63355. * @param x x coordinate
  63356. * @param z z coordinate
  63357. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  63358. */
  63359. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  63360. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  63361. this.getNormalAtCoordinatesToRef(x, z, normal);
  63362. return normal;
  63363. };
  63364. /**
  63365. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  63366. * at the ground coordinates (x, z) expressed in the World system.
  63367. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  63368. * @param x x coordinate
  63369. * @param z z coordinate
  63370. * @param ref vector to store the result
  63371. * @returns the GroundMesh.
  63372. */
  63373. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  63374. var world = this.getWorldMatrix();
  63375. var tmpMat = BABYLON.Tmp.Matrix[5];
  63376. world.invertToRef(tmpMat);
  63377. var tmpVect = BABYLON.Tmp.Vector3[8];
  63378. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  63379. x = tmpVect.x;
  63380. z = tmpVect.z;
  63381. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63382. return this;
  63383. }
  63384. if (!this._heightQuads || this._heightQuads.length == 0) {
  63385. this._initHeightQuads();
  63386. this._computeHeightQuads();
  63387. }
  63388. var facet = this._getFacetAt(x, z);
  63389. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  63390. return this;
  63391. };
  63392. /**
  63393. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  63394. * if the ground has been updated.
  63395. * This can be used in the render loop.
  63396. * @returns the GroundMesh.
  63397. */
  63398. GroundMesh.prototype.updateCoordinateHeights = function () {
  63399. if (!this._heightQuads || this._heightQuads.length == 0) {
  63400. this._initHeightQuads();
  63401. }
  63402. this._computeHeightQuads();
  63403. return this;
  63404. };
  63405. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  63406. GroundMesh.prototype._getFacetAt = function (x, z) {
  63407. // retrieve col and row from x, z coordinates in the ground local system
  63408. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  63409. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  63410. var quad = this._heightQuads[row * this._subdivisionsX + col];
  63411. var facet;
  63412. if (z < quad.slope.x * x + quad.slope.y) {
  63413. facet = quad.facet1;
  63414. }
  63415. else {
  63416. facet = quad.facet2;
  63417. }
  63418. return facet;
  63419. };
  63420. // Creates and populates the heightMap array with "facet" elements :
  63421. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  63422. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63423. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63424. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63425. // Returns the GroundMesh.
  63426. GroundMesh.prototype._initHeightQuads = function () {
  63427. var subdivisionsX = this._subdivisionsX;
  63428. var subdivisionsY = this._subdivisionsY;
  63429. this._heightQuads = new Array();
  63430. for (var row = 0; row < subdivisionsY; row++) {
  63431. for (var col = 0; col < subdivisionsX; col++) {
  63432. 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) };
  63433. this._heightQuads[row * subdivisionsX + col] = quad;
  63434. }
  63435. }
  63436. return this;
  63437. };
  63438. // Compute each quad element values and update the the heightMap array :
  63439. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63440. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63441. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63442. // Returns the GroundMesh.
  63443. GroundMesh.prototype._computeHeightQuads = function () {
  63444. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63445. if (!positions) {
  63446. return this;
  63447. }
  63448. var v1 = BABYLON.Tmp.Vector3[3];
  63449. var v2 = BABYLON.Tmp.Vector3[2];
  63450. var v3 = BABYLON.Tmp.Vector3[1];
  63451. var v4 = BABYLON.Tmp.Vector3[0];
  63452. var v1v2 = BABYLON.Tmp.Vector3[4];
  63453. var v1v3 = BABYLON.Tmp.Vector3[5];
  63454. var v1v4 = BABYLON.Tmp.Vector3[6];
  63455. var norm1 = BABYLON.Tmp.Vector3[7];
  63456. var norm2 = BABYLON.Tmp.Vector3[8];
  63457. var i = 0;
  63458. var j = 0;
  63459. var k = 0;
  63460. var cd = 0; // 2D slope coefficient : z = cd * x + h
  63461. var h = 0;
  63462. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  63463. var d2 = 0;
  63464. var subdivisionsX = this._subdivisionsX;
  63465. var subdivisionsY = this._subdivisionsY;
  63466. for (var row = 0; row < subdivisionsY; row++) {
  63467. for (var col = 0; col < subdivisionsX; col++) {
  63468. i = col * 3;
  63469. j = row * (subdivisionsX + 1) * 3;
  63470. k = (row + 1) * (subdivisionsX + 1) * 3;
  63471. v1.x = positions[j + i];
  63472. v1.y = positions[j + i + 1];
  63473. v1.z = positions[j + i + 2];
  63474. v2.x = positions[j + i + 3];
  63475. v2.y = positions[j + i + 4];
  63476. v2.z = positions[j + i + 5];
  63477. v3.x = positions[k + i];
  63478. v3.y = positions[k + i + 1];
  63479. v3.z = positions[k + i + 2];
  63480. v4.x = positions[k + i + 3];
  63481. v4.y = positions[k + i + 4];
  63482. v4.z = positions[k + i + 5];
  63483. // 2D slope V1V4
  63484. cd = (v4.z - v1.z) / (v4.x - v1.x);
  63485. h = v1.z - cd * v1.x; // v1 belongs to the slope
  63486. // facet equations :
  63487. // we compute each facet normal vector
  63488. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  63489. // we compute the value d by applying the equation to v1 which belongs to the plane
  63490. // then we store the facet equation in a Vector4
  63491. v2.subtractToRef(v1, v1v2);
  63492. v3.subtractToRef(v1, v1v3);
  63493. v4.subtractToRef(v1, v1v4);
  63494. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  63495. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  63496. norm1.normalize();
  63497. norm2.normalize();
  63498. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  63499. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  63500. var quad = this._heightQuads[row * subdivisionsX + col];
  63501. quad.slope.copyFromFloats(cd, h);
  63502. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  63503. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  63504. }
  63505. }
  63506. return this;
  63507. };
  63508. /**
  63509. * Serializes this ground mesh
  63510. * @param serializationObject object to write serialization to
  63511. */
  63512. GroundMesh.prototype.serialize = function (serializationObject) {
  63513. _super.prototype.serialize.call(this, serializationObject);
  63514. serializationObject.subdivisionsX = this._subdivisionsX;
  63515. serializationObject.subdivisionsY = this._subdivisionsY;
  63516. serializationObject.minX = this._minX;
  63517. serializationObject.maxX = this._maxX;
  63518. serializationObject.minZ = this._minZ;
  63519. serializationObject.maxZ = this._maxZ;
  63520. serializationObject.width = this._width;
  63521. serializationObject.height = this._height;
  63522. };
  63523. /**
  63524. * Parses a serialized ground mesh
  63525. * @param parsedMesh the serialized mesh
  63526. * @param scene the scene to create the ground mesh in
  63527. * @returns the created ground mesh
  63528. */
  63529. GroundMesh.Parse = function (parsedMesh, scene) {
  63530. var result = new GroundMesh(parsedMesh.name, scene);
  63531. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  63532. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  63533. result._minX = parsedMesh.minX;
  63534. result._maxX = parsedMesh.maxX;
  63535. result._minZ = parsedMesh.minZ;
  63536. result._maxZ = parsedMesh.maxZ;
  63537. result._width = parsedMesh.width;
  63538. result._height = parsedMesh.height;
  63539. return result;
  63540. };
  63541. return GroundMesh;
  63542. }(BABYLON.Mesh));
  63543. BABYLON.GroundMesh = GroundMesh;
  63544. })(BABYLON || (BABYLON = {}));
  63545. //# sourceMappingURL=babylon.groundMesh.js.map
  63546. var BABYLON;
  63547. (function (BABYLON) {
  63548. /**
  63549. * Creates an instance based on a source mesh.
  63550. */
  63551. var InstancedMesh = /** @class */ (function (_super) {
  63552. __extends(InstancedMesh, _super);
  63553. function InstancedMesh(name, source) {
  63554. var _this = _super.call(this, name, source.getScene()) || this;
  63555. source.instances.push(_this);
  63556. _this._sourceMesh = source;
  63557. _this.position.copyFrom(source.position);
  63558. _this.rotation.copyFrom(source.rotation);
  63559. _this.scaling.copyFrom(source.scaling);
  63560. if (source.rotationQuaternion) {
  63561. _this.rotationQuaternion = source.rotationQuaternion.clone();
  63562. }
  63563. _this.infiniteDistance = source.infiniteDistance;
  63564. _this.setPivotMatrix(source.getPivotMatrix());
  63565. _this.refreshBoundingInfo();
  63566. _this._syncSubMeshes();
  63567. return _this;
  63568. }
  63569. /**
  63570. * Returns the string "InstancedMesh".
  63571. */
  63572. InstancedMesh.prototype.getClassName = function () {
  63573. return "InstancedMesh";
  63574. };
  63575. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  63576. // Methods
  63577. /**
  63578. * If the source mesh receives shadows
  63579. */
  63580. get: function () {
  63581. return this._sourceMesh.receiveShadows;
  63582. },
  63583. enumerable: true,
  63584. configurable: true
  63585. });
  63586. Object.defineProperty(InstancedMesh.prototype, "material", {
  63587. /**
  63588. * The material of the source mesh
  63589. */
  63590. get: function () {
  63591. return this._sourceMesh.material;
  63592. },
  63593. enumerable: true,
  63594. configurable: true
  63595. });
  63596. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  63597. /**
  63598. * Visibility of the source mesh
  63599. */
  63600. get: function () {
  63601. return this._sourceMesh.visibility;
  63602. },
  63603. enumerable: true,
  63604. configurable: true
  63605. });
  63606. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  63607. /**
  63608. * Skeleton of the source mesh
  63609. */
  63610. get: function () {
  63611. return this._sourceMesh.skeleton;
  63612. },
  63613. enumerable: true,
  63614. configurable: true
  63615. });
  63616. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  63617. /**
  63618. * Rendering ground id of the source mesh
  63619. */
  63620. get: function () {
  63621. return this._sourceMesh.renderingGroupId;
  63622. },
  63623. set: function (value) {
  63624. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  63625. return;
  63626. }
  63627. //no-op with warning
  63628. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  63629. },
  63630. enumerable: true,
  63631. configurable: true
  63632. });
  63633. /**
  63634. * Returns the total number of vertices (integer).
  63635. */
  63636. InstancedMesh.prototype.getTotalVertices = function () {
  63637. return this._sourceMesh.getTotalVertices();
  63638. };
  63639. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  63640. /**
  63641. * The source mesh of the instance
  63642. */
  63643. get: function () {
  63644. return this._sourceMesh;
  63645. },
  63646. enumerable: true,
  63647. configurable: true
  63648. });
  63649. /**
  63650. * Is this node ready to be used/rendered
  63651. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  63652. * @return {boolean} is it ready
  63653. */
  63654. InstancedMesh.prototype.isReady = function (completeCheck) {
  63655. if (completeCheck === void 0) { completeCheck = false; }
  63656. return this._sourceMesh.isReady(completeCheck, true);
  63657. };
  63658. /**
  63659. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  63660. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  63661. * @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.
  63662. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  63663. */
  63664. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  63665. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  63666. };
  63667. /**
  63668. * Sets the vertex data of the mesh geometry for the requested `kind`.
  63669. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  63670. * The `data` are either a numeric array either a Float32Array.
  63671. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  63672. * 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).
  63673. * Note that a new underlying VertexBuffer object is created each call.
  63674. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  63675. *
  63676. * Possible `kind` values :
  63677. * - BABYLON.VertexBuffer.PositionKind
  63678. * - BABYLON.VertexBuffer.UVKind
  63679. * - BABYLON.VertexBuffer.UV2Kind
  63680. * - BABYLON.VertexBuffer.UV3Kind
  63681. * - BABYLON.VertexBuffer.UV4Kind
  63682. * - BABYLON.VertexBuffer.UV5Kind
  63683. * - BABYLON.VertexBuffer.UV6Kind
  63684. * - BABYLON.VertexBuffer.ColorKind
  63685. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63686. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63687. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63688. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63689. *
  63690. * Returns the Mesh.
  63691. */
  63692. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  63693. if (this.sourceMesh) {
  63694. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  63695. }
  63696. return this.sourceMesh;
  63697. };
  63698. /**
  63699. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  63700. * If the mesh has no geometry, it is simply returned as it is.
  63701. * The `data` are either a numeric array either a Float32Array.
  63702. * No new underlying VertexBuffer object is created.
  63703. * 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.
  63704. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  63705. *
  63706. * Possible `kind` values :
  63707. * - BABYLON.VertexBuffer.PositionKind
  63708. * - BABYLON.VertexBuffer.UVKind
  63709. * - BABYLON.VertexBuffer.UV2Kind
  63710. * - BABYLON.VertexBuffer.UV3Kind
  63711. * - BABYLON.VertexBuffer.UV4Kind
  63712. * - BABYLON.VertexBuffer.UV5Kind
  63713. * - BABYLON.VertexBuffer.UV6Kind
  63714. * - BABYLON.VertexBuffer.ColorKind
  63715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63719. *
  63720. * Returns the Mesh.
  63721. */
  63722. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  63723. if (this.sourceMesh) {
  63724. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  63725. }
  63726. return this.sourceMesh;
  63727. };
  63728. /**
  63729. * Sets the mesh indices.
  63730. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  63731. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  63732. * This method creates a new index buffer each call.
  63733. * Returns the Mesh.
  63734. */
  63735. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  63736. if (totalVertices === void 0) { totalVertices = null; }
  63737. if (this.sourceMesh) {
  63738. this.sourceMesh.setIndices(indices, totalVertices);
  63739. }
  63740. return this.sourceMesh;
  63741. };
  63742. /**
  63743. * Boolean : True if the mesh owns the requested kind of data.
  63744. */
  63745. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  63746. return this._sourceMesh.isVerticesDataPresent(kind);
  63747. };
  63748. /**
  63749. * Returns an array of indices (IndicesArray).
  63750. */
  63751. InstancedMesh.prototype.getIndices = function () {
  63752. return this._sourceMesh.getIndices();
  63753. };
  63754. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  63755. get: function () {
  63756. return this._sourceMesh._positions;
  63757. },
  63758. enumerable: true,
  63759. configurable: true
  63760. });
  63761. /**
  63762. * Sets a new updated BoundingInfo to the mesh.
  63763. * @returns the mesh.
  63764. */
  63765. InstancedMesh.prototype.refreshBoundingInfo = function () {
  63766. var meshBB = this._sourceMesh.getBoundingInfo();
  63767. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  63768. this._updateBoundingInfo();
  63769. return this;
  63770. };
  63771. /** @hidden */
  63772. InstancedMesh.prototype._preActivate = function () {
  63773. if (this._currentLOD) {
  63774. this._currentLOD._preActivate();
  63775. }
  63776. return this;
  63777. };
  63778. /** @hidden */
  63779. InstancedMesh.prototype._activate = function (renderId) {
  63780. if (this._currentLOD) {
  63781. this._currentLOD._registerInstanceForRenderId(this, renderId);
  63782. }
  63783. return this;
  63784. };
  63785. /**
  63786. * Returns the current associated LOD AbstractMesh.
  63787. */
  63788. InstancedMesh.prototype.getLOD = function (camera) {
  63789. if (!camera) {
  63790. return this;
  63791. }
  63792. var boundingInfo = this.getBoundingInfo();
  63793. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  63794. if (this._currentLOD === this.sourceMesh) {
  63795. return this;
  63796. }
  63797. return this._currentLOD;
  63798. };
  63799. /** @hidden */
  63800. InstancedMesh.prototype._syncSubMeshes = function () {
  63801. this.releaseSubMeshes();
  63802. if (this._sourceMesh.subMeshes) {
  63803. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  63804. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  63805. }
  63806. }
  63807. return this;
  63808. };
  63809. /** @hidden */
  63810. InstancedMesh.prototype._generatePointsArray = function () {
  63811. return this._sourceMesh._generatePointsArray();
  63812. };
  63813. /**
  63814. * Creates a new InstancedMesh from the current mesh.
  63815. * - name (string) : the cloned mesh name
  63816. * - newParent (optional Node) : the optional Node to parent the clone to.
  63817. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  63818. *
  63819. * Returns the clone.
  63820. */
  63821. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63822. var result = this._sourceMesh.createInstance(name);
  63823. // Deep copy
  63824. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  63825. // Bounding info
  63826. this.refreshBoundingInfo();
  63827. // Parent
  63828. if (newParent) {
  63829. result.parent = newParent;
  63830. }
  63831. if (!doNotCloneChildren) {
  63832. // Children
  63833. for (var index = 0; index < this.getScene().meshes.length; index++) {
  63834. var mesh = this.getScene().meshes[index];
  63835. if (mesh.parent === this) {
  63836. mesh.clone(mesh.name, result);
  63837. }
  63838. }
  63839. }
  63840. result.computeWorldMatrix(true);
  63841. return result;
  63842. };
  63843. /**
  63844. * Disposes the InstancedMesh.
  63845. * Returns nothing.
  63846. */
  63847. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  63848. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  63849. // Remove from mesh
  63850. var index = this._sourceMesh.instances.indexOf(this);
  63851. this._sourceMesh.instances.splice(index, 1);
  63852. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  63853. };
  63854. return InstancedMesh;
  63855. }(BABYLON.AbstractMesh));
  63856. BABYLON.InstancedMesh = InstancedMesh;
  63857. })(BABYLON || (BABYLON = {}));
  63858. //# sourceMappingURL=babylon.instancedMesh.js.map
  63859. var BABYLON;
  63860. (function (BABYLON) {
  63861. /**
  63862. * Line mesh
  63863. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  63864. */
  63865. var LinesMesh = /** @class */ (function (_super) {
  63866. __extends(LinesMesh, _super);
  63867. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  63868. /**
  63869. * If vertex color should be applied to the mesh
  63870. */
  63871. useVertexColor,
  63872. /**
  63873. * If vertex alpha should be applied to the mesh
  63874. */
  63875. useVertexAlpha) {
  63876. if (scene === void 0) { scene = null; }
  63877. if (parent === void 0) { parent = null; }
  63878. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  63879. _this.useVertexColor = useVertexColor;
  63880. _this.useVertexAlpha = useVertexAlpha;
  63881. /**
  63882. * Color of the line (Default: White)
  63883. */
  63884. _this.color = new BABYLON.Color3(1, 1, 1);
  63885. /**
  63886. * Alpha of the line (Default: 1)
  63887. */
  63888. _this.alpha = 1;
  63889. if (source) {
  63890. _this.color = source.color.clone();
  63891. _this.alpha = source.alpha;
  63892. _this.useVertexColor = source.useVertexColor;
  63893. _this.useVertexAlpha = source.useVertexAlpha;
  63894. }
  63895. _this._intersectionThreshold = 0.1;
  63896. var defines = [];
  63897. var options = {
  63898. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  63899. uniforms: ["world", "viewProjection"],
  63900. needAlphaBlending: true,
  63901. defines: defines
  63902. };
  63903. if (useVertexAlpha === false) {
  63904. options.needAlphaBlending = false;
  63905. }
  63906. if (!useVertexColor) {
  63907. options.uniforms.push("color");
  63908. }
  63909. else {
  63910. options.defines.push("#define VERTEXCOLOR");
  63911. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  63912. }
  63913. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  63914. return _this;
  63915. }
  63916. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  63917. /**
  63918. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63919. * This margin is expressed in world space coordinates, so its value may vary.
  63920. * Default value is 0.1
  63921. * @returns the intersection Threshold value.
  63922. */
  63923. get: function () {
  63924. return this._intersectionThreshold;
  63925. },
  63926. /**
  63927. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63928. * This margin is expressed in world space coordinates, so its value may vary.
  63929. */
  63930. set: function (value) {
  63931. if (this._intersectionThreshold === value) {
  63932. return;
  63933. }
  63934. this._intersectionThreshold = value;
  63935. if (this.geometry) {
  63936. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  63937. }
  63938. },
  63939. enumerable: true,
  63940. configurable: true
  63941. });
  63942. /**
  63943. * Returns the string "LineMesh"
  63944. */
  63945. LinesMesh.prototype.getClassName = function () {
  63946. return "LinesMesh";
  63947. };
  63948. Object.defineProperty(LinesMesh.prototype, "material", {
  63949. /**
  63950. * @hidden
  63951. */
  63952. get: function () {
  63953. return this._colorShader;
  63954. },
  63955. /**
  63956. * @hidden
  63957. */
  63958. set: function (value) {
  63959. // Do nothing
  63960. },
  63961. enumerable: true,
  63962. configurable: true
  63963. });
  63964. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63965. /**
  63966. * @hidden
  63967. */
  63968. get: function () {
  63969. return false;
  63970. },
  63971. enumerable: true,
  63972. configurable: true
  63973. });
  63974. /** @hidden */
  63975. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63976. if (!this._geometry) {
  63977. return this;
  63978. }
  63979. // VBOs
  63980. this._geometry._bind(this._colorShader.getEffect());
  63981. // Color
  63982. if (!this.useVertexColor) {
  63983. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  63984. }
  63985. return this;
  63986. };
  63987. /** @hidden */
  63988. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  63989. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  63990. return this;
  63991. }
  63992. var engine = this.getScene().getEngine();
  63993. // Draw order
  63994. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63995. return this;
  63996. };
  63997. /**
  63998. * Disposes of the line mesh
  63999. * @param doNotRecurse If children should be disposed
  64000. */
  64001. LinesMesh.prototype.dispose = function (doNotRecurse) {
  64002. this._colorShader.dispose();
  64003. _super.prototype.dispose.call(this, doNotRecurse);
  64004. };
  64005. /**
  64006. * Returns a new LineMesh object cloned from the current one.
  64007. */
  64008. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  64009. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  64010. };
  64011. return LinesMesh;
  64012. }(BABYLON.Mesh));
  64013. BABYLON.LinesMesh = LinesMesh;
  64014. })(BABYLON || (BABYLON = {}));
  64015. //# sourceMappingURL=babylon.linesMesh.js.map
  64016. var BABYLON;
  64017. (function (BABYLON) {
  64018. /**
  64019. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64020. * The underlying implementation relies on an associative array to ensure the best performances.
  64021. * The value can be anything including 'null' but except 'undefined'
  64022. */
  64023. var StringDictionary = /** @class */ (function () {
  64024. function StringDictionary() {
  64025. this._count = 0;
  64026. this._data = {};
  64027. }
  64028. /**
  64029. * This will clear this dictionary and copy the content from the 'source' one.
  64030. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64031. * @param source the dictionary to take the content from and copy to this dictionary
  64032. */
  64033. StringDictionary.prototype.copyFrom = function (source) {
  64034. var _this = this;
  64035. this.clear();
  64036. source.forEach(function (t, v) { return _this.add(t, v); });
  64037. };
  64038. /**
  64039. * Get a value based from its key
  64040. * @param key the given key to get the matching value from
  64041. * @return the value if found, otherwise undefined is returned
  64042. */
  64043. StringDictionary.prototype.get = function (key) {
  64044. var val = this._data[key];
  64045. if (val !== undefined) {
  64046. return val;
  64047. }
  64048. return undefined;
  64049. };
  64050. /**
  64051. * Get a value from its key or add it if it doesn't exist.
  64052. * This method will ensure you that a given key/data will be present in the dictionary.
  64053. * @param key the given key to get the matching value from
  64054. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64055. * The factory will only be invoked if there's no data for the given key.
  64056. * @return the value corresponding to the key.
  64057. */
  64058. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64059. var val = this.get(key);
  64060. if (val !== undefined) {
  64061. return val;
  64062. }
  64063. val = factory(key);
  64064. if (val) {
  64065. this.add(key, val);
  64066. }
  64067. return val;
  64068. };
  64069. /**
  64070. * Get a value from its key if present in the dictionary otherwise add it
  64071. * @param key the key to get the value from
  64072. * @param val if there's no such key/value pair in the dictionary add it with this value
  64073. * @return the value corresponding to the key
  64074. */
  64075. StringDictionary.prototype.getOrAdd = function (key, val) {
  64076. var curVal = this.get(key);
  64077. if (curVal !== undefined) {
  64078. return curVal;
  64079. }
  64080. this.add(key, val);
  64081. return val;
  64082. };
  64083. /**
  64084. * Check if there's a given key in the dictionary
  64085. * @param key the key to check for
  64086. * @return true if the key is present, false otherwise
  64087. */
  64088. StringDictionary.prototype.contains = function (key) {
  64089. return this._data[key] !== undefined;
  64090. };
  64091. /**
  64092. * Add a new key and its corresponding value
  64093. * @param key the key to add
  64094. * @param value the value corresponding to the key
  64095. * @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
  64096. */
  64097. StringDictionary.prototype.add = function (key, value) {
  64098. if (this._data[key] !== undefined) {
  64099. return false;
  64100. }
  64101. this._data[key] = value;
  64102. ++this._count;
  64103. return true;
  64104. };
  64105. /**
  64106. * Update a specific value associated to a key
  64107. * @param key defines the key to use
  64108. * @param value defines the value to store
  64109. * @returns true if the value was updated (or false if the key was not found)
  64110. */
  64111. StringDictionary.prototype.set = function (key, value) {
  64112. if (this._data[key] === undefined) {
  64113. return false;
  64114. }
  64115. this._data[key] = value;
  64116. return true;
  64117. };
  64118. /**
  64119. * Get the element of the given key and remove it from the dictionary
  64120. * @param key defines the key to search
  64121. * @returns the value associated with the key or null if not found
  64122. */
  64123. StringDictionary.prototype.getAndRemove = function (key) {
  64124. var val = this.get(key);
  64125. if (val !== undefined) {
  64126. delete this._data[key];
  64127. --this._count;
  64128. return val;
  64129. }
  64130. return null;
  64131. };
  64132. /**
  64133. * Remove a key/value from the dictionary.
  64134. * @param key the key to remove
  64135. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64136. */
  64137. StringDictionary.prototype.remove = function (key) {
  64138. if (this.contains(key)) {
  64139. delete this._data[key];
  64140. --this._count;
  64141. return true;
  64142. }
  64143. return false;
  64144. };
  64145. /**
  64146. * Clear the whole content of the dictionary
  64147. */
  64148. StringDictionary.prototype.clear = function () {
  64149. this._data = {};
  64150. this._count = 0;
  64151. };
  64152. Object.defineProperty(StringDictionary.prototype, "count", {
  64153. /**
  64154. * Gets the current count
  64155. */
  64156. get: function () {
  64157. return this._count;
  64158. },
  64159. enumerable: true,
  64160. configurable: true
  64161. });
  64162. /**
  64163. * Execute a callback on each key/val of the dictionary.
  64164. * Note that you can remove any element in this dictionary in the callback implementation
  64165. * @param callback the callback to execute on a given key/value pair
  64166. */
  64167. StringDictionary.prototype.forEach = function (callback) {
  64168. for (var cur in this._data) {
  64169. var val = this._data[cur];
  64170. callback(cur, val);
  64171. }
  64172. };
  64173. /**
  64174. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64175. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64176. * Note that you can remove any element in this dictionary in the callback implementation
  64177. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64178. * @returns the first item
  64179. */
  64180. StringDictionary.prototype.first = function (callback) {
  64181. for (var cur in this._data) {
  64182. var val = this._data[cur];
  64183. var res = callback(cur, val);
  64184. if (res) {
  64185. return res;
  64186. }
  64187. }
  64188. return null;
  64189. };
  64190. return StringDictionary;
  64191. }());
  64192. BABYLON.StringDictionary = StringDictionary;
  64193. })(BABYLON || (BABYLON = {}));
  64194. //# sourceMappingURL=babylon.stringDictionary.js.map
  64195. var BABYLON;
  64196. (function (BABYLON) {
  64197. var Debug;
  64198. (function (Debug) {
  64199. /**
  64200. * Class used to render a debug view of a given skeleton
  64201. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  64202. */
  64203. var SkeletonViewer = /** @class */ (function () {
  64204. /**
  64205. * Creates a new SkeletonViewer
  64206. * @param skeleton defines the skeleton to render
  64207. * @param mesh defines the mesh attached to the skeleton
  64208. * @param scene defines the hosting scene
  64209. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  64210. * @param renderingGroupId defines the rendering group id to use with the viewer
  64211. */
  64212. function SkeletonViewer(
  64213. /** defines the skeleton to render */
  64214. skeleton,
  64215. /** defines the mesh attached to the skeleton */
  64216. mesh, scene,
  64217. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  64218. autoUpdateBonesMatrices,
  64219. /** defines the rendering group id to use with the viewer */
  64220. renderingGroupId) {
  64221. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  64222. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  64223. this.skeleton = skeleton;
  64224. this.mesh = mesh;
  64225. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  64226. this.renderingGroupId = renderingGroupId;
  64227. /** Gets or sets the color used to render the skeleton */
  64228. this.color = BABYLON.Color3.White();
  64229. this._debugLines = new Array();
  64230. this._isEnabled = false;
  64231. this._scene = scene;
  64232. this.update();
  64233. this._renderFunction = this.update.bind(this);
  64234. }
  64235. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  64236. get: function () {
  64237. return this._isEnabled;
  64238. },
  64239. /** Gets or sets a boolean indicating if the viewer is enabled */
  64240. set: function (value) {
  64241. if (this._isEnabled === value) {
  64242. return;
  64243. }
  64244. this._isEnabled = value;
  64245. if (value) {
  64246. this._scene.registerBeforeRender(this._renderFunction);
  64247. }
  64248. else {
  64249. this._scene.unregisterBeforeRender(this._renderFunction);
  64250. }
  64251. },
  64252. enumerable: true,
  64253. configurable: true
  64254. });
  64255. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  64256. if (x === void 0) { x = 0; }
  64257. if (y === void 0) { y = 0; }
  64258. if (z === void 0) { z = 0; }
  64259. var tmat = BABYLON.Tmp.Matrix[0];
  64260. var parentBone = bone.getParent();
  64261. tmat.copyFrom(bone.getLocalMatrix());
  64262. if (x !== 0 || y !== 0 || z !== 0) {
  64263. var tmat2 = BABYLON.Tmp.Matrix[1];
  64264. BABYLON.Matrix.IdentityToRef(tmat2);
  64265. tmat2.m[12] = x;
  64266. tmat2.m[13] = y;
  64267. tmat2.m[14] = z;
  64268. tmat2.multiplyToRef(tmat, tmat);
  64269. }
  64270. if (parentBone) {
  64271. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64272. }
  64273. tmat.multiplyToRef(meshMat, tmat);
  64274. position.x = tmat.m[12];
  64275. position.y = tmat.m[13];
  64276. position.z = tmat.m[14];
  64277. };
  64278. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64279. var len = bones.length;
  64280. var meshPos = this.mesh.position;
  64281. for (var i = 0; i < len; i++) {
  64282. var bone = bones[i];
  64283. var points = this._debugLines[i];
  64284. if (!points) {
  64285. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64286. this._debugLines[i] = points;
  64287. }
  64288. this._getBonePosition(points[0], bone, meshMat);
  64289. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64290. points[0].subtractInPlace(meshPos);
  64291. points[1].subtractInPlace(meshPos);
  64292. }
  64293. };
  64294. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64295. var len = bones.length;
  64296. var boneNum = 0;
  64297. var meshPos = this.mesh.position;
  64298. for (var i = len - 1; i >= 0; i--) {
  64299. var childBone = bones[i];
  64300. var parentBone = childBone.getParent();
  64301. if (!parentBone) {
  64302. continue;
  64303. }
  64304. var points = this._debugLines[boneNum];
  64305. if (!points) {
  64306. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64307. this._debugLines[boneNum] = points;
  64308. }
  64309. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64310. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64311. points[0].subtractInPlace(meshPos);
  64312. points[1].subtractInPlace(meshPos);
  64313. boneNum++;
  64314. }
  64315. };
  64316. /** Update the viewer to sync with current skeleton state */
  64317. SkeletonViewer.prototype.update = function () {
  64318. if (this.autoUpdateBonesMatrices) {
  64319. this.skeleton.computeAbsoluteTransforms();
  64320. }
  64321. if (this.skeleton.bones[0].length === undefined) {
  64322. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64323. }
  64324. else {
  64325. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64326. }
  64327. if (!this._debugMesh) {
  64328. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  64329. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64330. }
  64331. else {
  64332. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64333. }
  64334. this._debugMesh.position.copyFrom(this.mesh.position);
  64335. this._debugMesh.color = this.color;
  64336. };
  64337. /** Release associated resources */
  64338. SkeletonViewer.prototype.dispose = function () {
  64339. if (this._debugMesh) {
  64340. this.isEnabled = false;
  64341. this._debugMesh.dispose();
  64342. this._debugMesh = null;
  64343. }
  64344. };
  64345. return SkeletonViewer;
  64346. }());
  64347. Debug.SkeletonViewer = SkeletonViewer;
  64348. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64349. })(BABYLON || (BABYLON = {}));
  64350. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64351. /**
  64352. * Module Debug contains the (visual) components to debug a scene correctly
  64353. */
  64354. var BABYLON;
  64355. (function (BABYLON) {
  64356. var Debug;
  64357. (function (Debug) {
  64358. /**
  64359. * The Axes viewer will show 3 axes in a specific point in space
  64360. */
  64361. var AxesViewer = /** @class */ (function () {
  64362. /**
  64363. * Creates a new AxesViewer
  64364. * @param scene defines the hosting scene
  64365. * @param scaleLines defines a number used to scale line length (1 by default)
  64366. */
  64367. function AxesViewer(scene, scaleLines) {
  64368. if (scaleLines === void 0) { scaleLines = 1; }
  64369. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64370. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64371. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64372. /**
  64373. * Gets or sets a number used to scale line length
  64374. */
  64375. this.scaleLines = 1;
  64376. this.scaleLines = scaleLines;
  64377. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64378. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64379. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64380. this._xmesh.renderingGroupId = 2;
  64381. this._ymesh.renderingGroupId = 2;
  64382. this._zmesh.renderingGroupId = 2;
  64383. this._xmesh.material.checkReadyOnlyOnce = true;
  64384. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64385. this._ymesh.material.checkReadyOnlyOnce = true;
  64386. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64387. this._zmesh.material.checkReadyOnlyOnce = true;
  64388. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64389. this.scene = scene;
  64390. }
  64391. /**
  64392. * Force the viewer to update
  64393. * @param position defines the position of the viewer
  64394. * @param xaxis defines the x axis of the viewer
  64395. * @param yaxis defines the y axis of the viewer
  64396. * @param zaxis defines the z axis of the viewer
  64397. */
  64398. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64399. var scaleLines = this.scaleLines;
  64400. if (this._xmesh) {
  64401. this._xmesh.position.copyFrom(position);
  64402. }
  64403. if (this._ymesh) {
  64404. this._ymesh.position.copyFrom(position);
  64405. }
  64406. if (this._zmesh) {
  64407. this._zmesh.position.copyFrom(position);
  64408. }
  64409. var point2 = this._xline[1];
  64410. point2.x = xaxis.x * scaleLines;
  64411. point2.y = xaxis.y * scaleLines;
  64412. point2.z = xaxis.z * scaleLines;
  64413. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  64414. point2 = this._yline[1];
  64415. point2.x = yaxis.x * scaleLines;
  64416. point2.y = yaxis.y * scaleLines;
  64417. point2.z = yaxis.z * scaleLines;
  64418. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  64419. point2 = this._zline[1];
  64420. point2.x = zaxis.x * scaleLines;
  64421. point2.y = zaxis.y * scaleLines;
  64422. point2.z = zaxis.z * scaleLines;
  64423. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  64424. };
  64425. /** Releases resources */
  64426. AxesViewer.prototype.dispose = function () {
  64427. if (this._xmesh) {
  64428. this._xmesh.dispose();
  64429. }
  64430. if (this._ymesh) {
  64431. this._ymesh.dispose();
  64432. }
  64433. if (this._zmesh) {
  64434. this._zmesh.dispose();
  64435. }
  64436. this._xmesh = null;
  64437. this._ymesh = null;
  64438. this._zmesh = null;
  64439. this.scene = null;
  64440. };
  64441. return AxesViewer;
  64442. }());
  64443. Debug.AxesViewer = AxesViewer;
  64444. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64445. })(BABYLON || (BABYLON = {}));
  64446. //# sourceMappingURL=babylon.axesViewer.js.map
  64447. var BABYLON;
  64448. (function (BABYLON) {
  64449. var Debug;
  64450. (function (Debug) {
  64451. /**
  64452. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  64453. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  64454. */
  64455. var BoneAxesViewer = /** @class */ (function (_super) {
  64456. __extends(BoneAxesViewer, _super);
  64457. /**
  64458. * Creates a new BoneAxesViewer
  64459. * @param scene defines the hosting scene
  64460. * @param bone defines the target bone
  64461. * @param mesh defines the target mesh
  64462. * @param scaleLines defines a scaling factor for line length (1 by default)
  64463. */
  64464. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64465. if (scaleLines === void 0) { scaleLines = 1; }
  64466. var _this = _super.call(this, scene, scaleLines) || this;
  64467. /** Gets current position */
  64468. _this.pos = BABYLON.Vector3.Zero();
  64469. /** Gets direction of X axis */
  64470. _this.xaxis = BABYLON.Vector3.Zero();
  64471. /** Gets direction of Y axis */
  64472. _this.yaxis = BABYLON.Vector3.Zero();
  64473. /** Gets direction of Z axis */
  64474. _this.zaxis = BABYLON.Vector3.Zero();
  64475. _this.mesh = mesh;
  64476. _this.bone = bone;
  64477. return _this;
  64478. }
  64479. /**
  64480. * Force the viewer to update
  64481. */
  64482. BoneAxesViewer.prototype.update = function () {
  64483. if (!this.mesh || !this.bone) {
  64484. return;
  64485. }
  64486. var bone = this.bone;
  64487. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64488. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64489. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64490. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64491. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64492. };
  64493. /** Releases resources */
  64494. BoneAxesViewer.prototype.dispose = function () {
  64495. if (this.mesh) {
  64496. this.mesh = null;
  64497. this.bone = null;
  64498. _super.prototype.dispose.call(this);
  64499. }
  64500. };
  64501. return BoneAxesViewer;
  64502. }(Debug.AxesViewer));
  64503. Debug.BoneAxesViewer = BoneAxesViewer;
  64504. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64505. })(BABYLON || (BABYLON = {}));
  64506. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64507. var BABYLON;
  64508. (function (BABYLON) {
  64509. /**
  64510. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64511. * in order to better appreciate the issue one might have.
  64512. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64513. */
  64514. var RayHelper = /** @class */ (function () {
  64515. /**
  64516. * Instantiate a new ray helper.
  64517. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64518. * in order to better appreciate the issue one might have.
  64519. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64520. * @param ray Defines the ray we are currently tryin to visualize
  64521. */
  64522. function RayHelper(ray) {
  64523. this.ray = ray;
  64524. }
  64525. /**
  64526. * Helper function to create a colored helper in a scene in one line.
  64527. * @param ray Defines the ray we are currently tryin to visualize
  64528. * @param scene Defines the scene the ray is used in
  64529. * @param color Defines the color we want to see the ray in
  64530. * @returns The newly created ray helper.
  64531. */
  64532. RayHelper.CreateAndShow = function (ray, scene, color) {
  64533. var helper = new RayHelper(ray);
  64534. helper.show(scene, color);
  64535. return helper;
  64536. };
  64537. /**
  64538. * Shows the ray we are willing to debug.
  64539. * @param scene Defines the scene the ray needs to be rendered in
  64540. * @param color Defines the color the ray needs to be rendered in
  64541. */
  64542. RayHelper.prototype.show = function (scene, color) {
  64543. if (!this._renderFunction && this.ray) {
  64544. var ray = this.ray;
  64545. this._renderFunction = this._render.bind(this);
  64546. this._scene = scene;
  64547. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64548. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64549. if (this._renderFunction) {
  64550. this._scene.registerBeforeRender(this._renderFunction);
  64551. }
  64552. }
  64553. if (color && this._renderLine) {
  64554. this._renderLine.color.copyFrom(color);
  64555. }
  64556. };
  64557. /**
  64558. * Hides the ray we are debugging.
  64559. */
  64560. RayHelper.prototype.hide = function () {
  64561. if (this._renderFunction && this._scene) {
  64562. this._scene.unregisterBeforeRender(this._renderFunction);
  64563. this._scene = null;
  64564. this._renderFunction = null;
  64565. if (this._renderLine) {
  64566. this._renderLine.dispose();
  64567. this._renderLine = null;
  64568. }
  64569. this._renderPoints = [];
  64570. }
  64571. };
  64572. RayHelper.prototype._render = function () {
  64573. var ray = this.ray;
  64574. if (!ray) {
  64575. return;
  64576. }
  64577. var point = this._renderPoints[1];
  64578. var len = Math.min(ray.length, 1000000);
  64579. point.copyFrom(ray.direction);
  64580. point.scaleInPlace(len);
  64581. point.addInPlace(ray.origin);
  64582. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64583. };
  64584. /**
  64585. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  64586. * @param mesh Defines the mesh we want the helper attached to
  64587. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  64588. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  64589. * @param length Defines the length of the ray
  64590. */
  64591. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64592. this._attachedToMesh = mesh;
  64593. var ray = this.ray;
  64594. if (!ray) {
  64595. return;
  64596. }
  64597. if (!ray.direction) {
  64598. ray.direction = BABYLON.Vector3.Zero();
  64599. }
  64600. if (!ray.origin) {
  64601. ray.origin = BABYLON.Vector3.Zero();
  64602. }
  64603. if (length) {
  64604. ray.length = length;
  64605. }
  64606. if (!meshSpaceOrigin) {
  64607. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64608. }
  64609. if (!meshSpaceDirection) {
  64610. // -1 so that this will work with Mesh.lookAt
  64611. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64612. }
  64613. if (!this._meshSpaceDirection) {
  64614. this._meshSpaceDirection = meshSpaceDirection.clone();
  64615. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64616. }
  64617. else {
  64618. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64619. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64620. }
  64621. if (!this._updateToMeshFunction) {
  64622. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64623. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64624. }
  64625. this._updateToMesh();
  64626. };
  64627. /**
  64628. * Detach the ray helper from the mesh it has previously been attached to.
  64629. */
  64630. RayHelper.prototype.detachFromMesh = function () {
  64631. if (this._attachedToMesh) {
  64632. if (this._updateToMeshFunction) {
  64633. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64634. }
  64635. this._attachedToMesh = null;
  64636. this._updateToMeshFunction = null;
  64637. }
  64638. };
  64639. RayHelper.prototype._updateToMesh = function () {
  64640. var ray = this.ray;
  64641. if (!this._attachedToMesh || !ray) {
  64642. return;
  64643. }
  64644. if (this._attachedToMesh._isDisposed) {
  64645. this.detachFromMesh();
  64646. return;
  64647. }
  64648. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64649. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64650. };
  64651. /**
  64652. * Dispose the helper and release its associated resources.
  64653. */
  64654. RayHelper.prototype.dispose = function () {
  64655. this.hide();
  64656. this.detachFromMesh();
  64657. this.ray = null;
  64658. };
  64659. return RayHelper;
  64660. }());
  64661. BABYLON.RayHelper = RayHelper;
  64662. })(BABYLON || (BABYLON = {}));
  64663. //# sourceMappingURL=babylon.rayHelper.js.map
  64664. var BABYLON;
  64665. (function (BABYLON) {
  64666. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  64667. get: function () {
  64668. if (!this._debugLayer) {
  64669. this._debugLayer = new DebugLayer(this);
  64670. }
  64671. return this._debugLayer;
  64672. },
  64673. enumerable: true,
  64674. configurable: true
  64675. });
  64676. /**
  64677. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64678. * what is happening in your scene
  64679. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64680. */
  64681. var DebugLayer = /** @class */ (function () {
  64682. /**
  64683. * Instantiates a new debug layer.
  64684. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64685. * what is happening in your scene
  64686. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64687. * @param scene Defines the scene to inspect
  64688. */
  64689. function DebugLayer(scene) {
  64690. var _this = this;
  64691. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64692. /**
  64693. * Observable triggered when a property is changed through the inspector.
  64694. */
  64695. this.onPropertyChangedObservable = new BABYLON.Observable();
  64696. this._scene = scene;
  64697. this._scene.onDisposeObservable.add(function () {
  64698. // Debug layer
  64699. if (_this._scene._debugLayer) {
  64700. _this._scene._debugLayer.hide();
  64701. }
  64702. });
  64703. }
  64704. /** Creates the inspector window. */
  64705. DebugLayer.prototype._createInspector = function (config) {
  64706. if (config === void 0) { config = {}; }
  64707. var popup = config.popup || false;
  64708. var initialTab = config.initialTab || 0;
  64709. var parentElement = config.parentElement || null;
  64710. if (!this._inspector) {
  64711. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64712. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64713. } // else nothing to do as instance is already created
  64714. };
  64715. /**
  64716. * Get if the inspector is visible or not.
  64717. * @returns true if visible otherwise, false
  64718. */
  64719. DebugLayer.prototype.isVisible = function () {
  64720. if (!this._inspector) {
  64721. return false;
  64722. }
  64723. return true;
  64724. };
  64725. /**
  64726. * Hide the inspector and close its window.
  64727. */
  64728. DebugLayer.prototype.hide = function () {
  64729. if (this._inspector) {
  64730. try {
  64731. this._inspector.dispose();
  64732. }
  64733. catch (e) {
  64734. // If the inspector has been removed directly from the inspector tool
  64735. }
  64736. this.onPropertyChangedObservable.clear();
  64737. this._inspector = null;
  64738. }
  64739. };
  64740. /**
  64741. *
  64742. * Launch the debugLayer.
  64743. *
  64744. * initialTab:
  64745. * | Value | Tab Name |
  64746. * | --- | --- |
  64747. * | 0 | Scene |
  64748. * | 1 | Console |
  64749. * | 2 | Stats |
  64750. * | 3 | Textures |
  64751. * | 4 | Mesh |
  64752. * | 5 | Light |
  64753. * | 6 | Material |
  64754. * | 7 | GLTF |
  64755. * | 8 | GUI |
  64756. * | 9 | Physics |
  64757. * | 10 | Camera |
  64758. * | 11 | Audio |
  64759. *
  64760. * @param config Define the configuration of the inspector
  64761. */
  64762. DebugLayer.prototype.show = function (config) {
  64763. if (config === void 0) { config = {}; }
  64764. if (typeof this.BJSINSPECTOR == 'undefined') {
  64765. // Load inspector and add it to the DOM
  64766. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64767. }
  64768. else {
  64769. // Otherwise creates the inspector
  64770. this._createInspector(config);
  64771. }
  64772. };
  64773. /**
  64774. * Gets the active tab
  64775. * @return the index of the active tab or -1 if the inspector is hidden
  64776. */
  64777. DebugLayer.prototype.getActiveTab = function () {
  64778. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  64779. };
  64780. /**
  64781. * Define the url to get the inspector script from.
  64782. * By default it uses the babylonjs CDN.
  64783. * @ignoreNaming
  64784. */
  64785. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64786. return DebugLayer;
  64787. }());
  64788. BABYLON.DebugLayer = DebugLayer;
  64789. })(BABYLON || (BABYLON = {}));
  64790. //# sourceMappingURL=babylon.debugLayer.js.map
  64791. var BABYLON;
  64792. (function (BABYLON) {
  64793. var Debug;
  64794. (function (Debug) {
  64795. /**
  64796. * Used to show the physics impostor around the specific mesh
  64797. */
  64798. var PhysicsViewer = /** @class */ (function () {
  64799. /**
  64800. * Creates a new PhysicsViewer
  64801. * @param scene defines the hosting scene
  64802. */
  64803. function PhysicsViewer(scene) {
  64804. /** @hidden */
  64805. this._impostors = [];
  64806. /** @hidden */
  64807. this._meshes = [];
  64808. /** @hidden */
  64809. this._numMeshes = 0;
  64810. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64811. var physicEngine = this._scene.getPhysicsEngine();
  64812. if (physicEngine) {
  64813. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  64814. }
  64815. }
  64816. /** @hidden */
  64817. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64818. var plugin = this._physicsEnginePlugin;
  64819. for (var i = 0; i < this._numMeshes; i++) {
  64820. var impostor = this._impostors[i];
  64821. if (!impostor) {
  64822. continue;
  64823. }
  64824. if (impostor.isDisposed) {
  64825. this.hideImpostor(this._impostors[i--]);
  64826. }
  64827. else {
  64828. var mesh = this._meshes[i];
  64829. if (mesh && plugin) {
  64830. plugin.syncMeshWithImpostor(mesh, impostor);
  64831. }
  64832. }
  64833. }
  64834. };
  64835. /**
  64836. * Renders a specified physic impostor
  64837. * @param impostor defines the impostor to render
  64838. */
  64839. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64840. if (!this._scene) {
  64841. return;
  64842. }
  64843. for (var i = 0; i < this._numMeshes; i++) {
  64844. if (this._impostors[i] == impostor) {
  64845. return;
  64846. }
  64847. }
  64848. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64849. if (debugMesh) {
  64850. this._impostors[this._numMeshes] = impostor;
  64851. this._meshes[this._numMeshes] = debugMesh;
  64852. if (this._numMeshes === 0) {
  64853. this._renderFunction = this._updateDebugMeshes.bind(this);
  64854. this._scene.registerBeforeRender(this._renderFunction);
  64855. }
  64856. this._numMeshes++;
  64857. }
  64858. };
  64859. /**
  64860. * Hides a specified physic impostor
  64861. * @param impostor defines the impostor to hide
  64862. */
  64863. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64864. if (!impostor || !this._scene) {
  64865. return;
  64866. }
  64867. var removed = false;
  64868. for (var i = 0; i < this._numMeshes; i++) {
  64869. if (this._impostors[i] == impostor) {
  64870. var mesh = this._meshes[i];
  64871. if (!mesh) {
  64872. continue;
  64873. }
  64874. this._scene.removeMesh(mesh);
  64875. mesh.dispose();
  64876. this._numMeshes--;
  64877. if (this._numMeshes > 0) {
  64878. this._meshes[i] = this._meshes[this._numMeshes];
  64879. this._impostors[i] = this._impostors[this._numMeshes];
  64880. this._meshes[this._numMeshes] = null;
  64881. this._impostors[this._numMeshes] = null;
  64882. }
  64883. else {
  64884. this._meshes[0] = null;
  64885. this._impostors[0] = null;
  64886. }
  64887. removed = true;
  64888. break;
  64889. }
  64890. }
  64891. if (removed && this._numMeshes === 0) {
  64892. this._scene.unregisterBeforeRender(this._renderFunction);
  64893. }
  64894. };
  64895. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64896. if (!this._debugMaterial) {
  64897. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64898. this._debugMaterial.wireframe = true;
  64899. }
  64900. return this._debugMaterial;
  64901. };
  64902. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64903. if (!this._debugBoxMesh) {
  64904. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64905. this._debugBoxMesh.renderingGroupId = 1;
  64906. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64907. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64908. scene.removeMesh(this._debugBoxMesh);
  64909. }
  64910. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64911. };
  64912. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64913. if (!this._debugSphereMesh) {
  64914. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64915. this._debugSphereMesh.renderingGroupId = 1;
  64916. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64917. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64918. scene.removeMesh(this._debugSphereMesh);
  64919. }
  64920. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64921. };
  64922. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64923. var mesh = null;
  64924. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64925. mesh = this._getDebugBoxMesh(scene);
  64926. impostor.getBoxSizeToRef(mesh.scaling);
  64927. }
  64928. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64929. mesh = this._getDebugSphereMesh(scene);
  64930. var radius = impostor.getRadius();
  64931. mesh.scaling.x = radius * 2;
  64932. mesh.scaling.y = radius * 2;
  64933. mesh.scaling.z = radius * 2;
  64934. }
  64935. return mesh;
  64936. };
  64937. /** Releases all resources */
  64938. PhysicsViewer.prototype.dispose = function () {
  64939. for (var i = 0; i < this._numMeshes; i++) {
  64940. this.hideImpostor(this._impostors[i]);
  64941. }
  64942. if (this._debugBoxMesh) {
  64943. this._debugBoxMesh.dispose();
  64944. }
  64945. if (this._debugSphereMesh) {
  64946. this._debugSphereMesh.dispose();
  64947. }
  64948. if (this._debugMaterial) {
  64949. this._debugMaterial.dispose();
  64950. }
  64951. this._impostors.length = 0;
  64952. this._scene = null;
  64953. this._physicsEnginePlugin = null;
  64954. };
  64955. return PhysicsViewer;
  64956. }());
  64957. Debug.PhysicsViewer = PhysicsViewer;
  64958. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64959. })(BABYLON || (BABYLON = {}));
  64960. //# sourceMappingURL=babylon.physicsViewer.js.map
  64961. var BABYLON;
  64962. (function (BABYLON) {
  64963. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  64964. get: function () {
  64965. return this._forceShowBoundingBoxes || false;
  64966. },
  64967. set: function (value) {
  64968. this._forceShowBoundingBoxes = value;
  64969. // Lazyly creates a BB renderer if needed.
  64970. if (value) {
  64971. this.getBoundingBoxRenderer();
  64972. }
  64973. },
  64974. enumerable: true,
  64975. configurable: true
  64976. });
  64977. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  64978. if (!this._boundingBoxRenderer) {
  64979. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64980. }
  64981. return this._boundingBoxRenderer;
  64982. };
  64983. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  64984. get: function () {
  64985. return this._showBoundingBox || false;
  64986. },
  64987. set: function (value) {
  64988. this._showBoundingBox = value;
  64989. // Lazyly creates a BB renderer if needed.
  64990. if (value) {
  64991. this.getScene().getBoundingBoxRenderer();
  64992. }
  64993. },
  64994. enumerable: true,
  64995. configurable: true
  64996. });
  64997. /**
  64998. * Component responsible of rendering the bounding box of the meshes in a scene.
  64999. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  65000. */
  65001. var BoundingBoxRenderer = /** @class */ (function () {
  65002. /**
  65003. * Instantiates a new bounding box renderer in a scene.
  65004. * @param scene the scene the renderer renders in
  65005. */
  65006. function BoundingBoxRenderer(scene) {
  65007. /**
  65008. * The component name helpfull to identify the component in the list of scene components.
  65009. */
  65010. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  65011. /**
  65012. * Color of the bounding box lines placed in front of an object
  65013. */
  65014. this.frontColor = new BABYLON.Color3(1, 1, 1);
  65015. /**
  65016. * Color of the bounding box lines placed behind an object
  65017. */
  65018. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  65019. /**
  65020. * Defines if the renderer should show the back lines or not
  65021. */
  65022. this.showBackLines = true;
  65023. /**
  65024. * @hidden
  65025. */
  65026. this.renderList = new BABYLON.SmartArray(32);
  65027. this._vertexBuffers = {};
  65028. this.scene = scene;
  65029. scene._addComponent(this);
  65030. }
  65031. /**
  65032. * Registers the component in a given scene
  65033. */
  65034. BoundingBoxRenderer.prototype.register = function () {
  65035. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  65036. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  65037. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  65038. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  65039. };
  65040. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  65041. if (mesh.showSubMeshesBoundingBox) {
  65042. var boundingInfo = subMesh.getBoundingInfo();
  65043. if (boundingInfo !== null && boundingInfo !== undefined) {
  65044. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  65045. this.renderList.push(boundingInfo.boundingBox);
  65046. }
  65047. }
  65048. };
  65049. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  65050. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  65051. var boundingInfo = sourceMesh.getBoundingInfo();
  65052. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  65053. this.renderList.push(boundingInfo.boundingBox);
  65054. }
  65055. };
  65056. BoundingBoxRenderer.prototype._prepareRessources = function () {
  65057. if (this._colorShader) {
  65058. return;
  65059. }
  65060. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  65061. attributes: [BABYLON.VertexBuffer.PositionKind],
  65062. uniforms: ["world", "viewProjection", "color"]
  65063. });
  65064. var engine = this.scene.getEngine();
  65065. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  65066. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  65067. this._createIndexBuffer();
  65068. };
  65069. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  65070. var engine = this.scene.getEngine();
  65071. 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]);
  65072. };
  65073. /**
  65074. * Rebuilds the elements related to this component in case of
  65075. * context lost for instance.
  65076. */
  65077. BoundingBoxRenderer.prototype.rebuild = function () {
  65078. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65079. if (vb) {
  65080. vb._rebuild();
  65081. }
  65082. this._createIndexBuffer();
  65083. };
  65084. /**
  65085. * @hidden
  65086. */
  65087. BoundingBoxRenderer.prototype.reset = function () {
  65088. this.renderList.reset();
  65089. };
  65090. /**
  65091. * Render the bounding boxes of a specific rendering group
  65092. * @param renderingGroupId defines the rendering group to render
  65093. */
  65094. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  65095. if (this.renderList.length === 0) {
  65096. return;
  65097. }
  65098. this._prepareRessources();
  65099. if (!this._colorShader.isReady()) {
  65100. return;
  65101. }
  65102. var engine = this.scene.getEngine();
  65103. engine.setDepthWrite(false);
  65104. this._colorShader._preBind();
  65105. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  65106. var boundingBox = this.renderList.data[boundingBoxIndex];
  65107. if (boundingBox._tag !== renderingGroupId) {
  65108. continue;
  65109. }
  65110. var min = boundingBox.minimum;
  65111. var max = boundingBox.maximum;
  65112. var diff = max.subtract(min);
  65113. var median = min.add(diff.scale(0.5));
  65114. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  65115. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  65116. .multiply(boundingBox.getWorldMatrix());
  65117. // VBOs
  65118. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  65119. if (this.showBackLines) {
  65120. // Back
  65121. engine.setDepthFunctionToGreaterOrEqual();
  65122. this.scene.resetCachedMaterial();
  65123. this._colorShader.setColor4("color", this.backColor.toColor4());
  65124. this._colorShader.bind(worldMatrix);
  65125. // Draw order
  65126. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65127. }
  65128. // Front
  65129. engine.setDepthFunctionToLess();
  65130. this.scene.resetCachedMaterial();
  65131. this._colorShader.setColor4("color", this.frontColor.toColor4());
  65132. this._colorShader.bind(worldMatrix);
  65133. // Draw order
  65134. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65135. }
  65136. this._colorShader.unbind();
  65137. engine.setDepthFunctionToLessOrEqual();
  65138. engine.setDepthWrite(true);
  65139. };
  65140. /**
  65141. * In case of occlusion queries, we can render the occlusion bounding box through this method
  65142. * @param mesh Define the mesh to render the occlusion bounding box for
  65143. */
  65144. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  65145. this._prepareRessources();
  65146. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  65147. return;
  65148. }
  65149. var engine = this.scene.getEngine();
  65150. engine.setDepthWrite(false);
  65151. engine.setColorWrite(false);
  65152. this._colorShader._preBind();
  65153. var boundingBox = mesh._boundingInfo.boundingBox;
  65154. var min = boundingBox.minimum;
  65155. var max = boundingBox.maximum;
  65156. var diff = max.subtract(min);
  65157. var median = min.add(diff.scale(0.5));
  65158. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  65159. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  65160. .multiply(boundingBox.getWorldMatrix());
  65161. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  65162. engine.setDepthFunctionToLess();
  65163. this.scene.resetCachedMaterial();
  65164. this._colorShader.bind(worldMatrix);
  65165. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  65166. this._colorShader.unbind();
  65167. engine.setDepthFunctionToLessOrEqual();
  65168. engine.setDepthWrite(true);
  65169. engine.setColorWrite(true);
  65170. };
  65171. /**
  65172. * Dispose and release the resources attached to this renderer.
  65173. */
  65174. BoundingBoxRenderer.prototype.dispose = function () {
  65175. if (!this._colorShader) {
  65176. return;
  65177. }
  65178. this.renderList.dispose();
  65179. this._colorShader.dispose();
  65180. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65181. if (buffer) {
  65182. buffer.dispose();
  65183. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65184. }
  65185. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  65186. };
  65187. return BoundingBoxRenderer;
  65188. }());
  65189. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  65190. })(BABYLON || (BABYLON = {}));
  65191. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  65192. var BABYLON;
  65193. (function (BABYLON) {
  65194. BABYLON.Engine.prototype.createTransformFeedback = function () {
  65195. return this._gl.createTransformFeedback();
  65196. };
  65197. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  65198. this._gl.deleteTransformFeedback(value);
  65199. };
  65200. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  65201. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  65202. };
  65203. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  65204. if (usePoints === void 0) { usePoints = true; }
  65205. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  65206. };
  65207. BABYLON.Engine.prototype.endTransformFeedback = function () {
  65208. this._gl.endTransformFeedback();
  65209. };
  65210. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  65211. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  65212. };
  65213. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  65214. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  65215. };
  65216. })(BABYLON || (BABYLON = {}));
  65217. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  65218. var BABYLON;
  65219. (function (BABYLON) {
  65220. /**
  65221. * This represents a GPU particle system in Babylon
  65222. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  65223. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  65224. */
  65225. var GPUParticleSystem = /** @class */ (function (_super) {
  65226. __extends(GPUParticleSystem, _super);
  65227. /**
  65228. * Instantiates a GPU particle system.
  65229. * 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.
  65230. * @param name The name of the particle system
  65231. * @param options The options used to create the system
  65232. * @param scene The scene the particle system belongs to
  65233. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  65234. */
  65235. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  65236. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  65237. var _this = _super.call(this, name) || this;
  65238. /**
  65239. * The layer mask we are rendering the particles through.
  65240. */
  65241. _this.layerMask = 0x0FFFFFFF;
  65242. _this._accumulatedCount = 0;
  65243. _this._targetIndex = 0;
  65244. _this._currentRenderId = -1;
  65245. _this._started = false;
  65246. _this._stopped = false;
  65247. _this._timeDelta = 0;
  65248. _this._attributesStrideSize = 21;
  65249. _this._actualFrame = 0;
  65250. _this._rawTextureWidth = 256;
  65251. /**
  65252. * An event triggered when the system is disposed.
  65253. */
  65254. _this.onDisposeObservable = new BABYLON.Observable();
  65255. /**
  65256. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  65257. * to override the particles.
  65258. */
  65259. _this.forceDepthWrite = false;
  65260. _this._preWarmDone = false;
  65261. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65262. // Setup the default processing configuration to the scene.
  65263. _this._attachImageProcessingConfiguration(null);
  65264. _this._engine = _this._scene.getEngine();
  65265. if (!options.randomTextureSize) {
  65266. delete options.randomTextureSize;
  65267. }
  65268. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  65269. var optionsAsNumber = options;
  65270. if (isFinite(optionsAsNumber)) {
  65271. fullOptions.capacity = optionsAsNumber;
  65272. }
  65273. _this._capacity = fullOptions.capacity;
  65274. _this._activeCount = fullOptions.capacity;
  65275. _this._currentActiveCount = 0;
  65276. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  65277. _this._scene.particleSystems.push(_this);
  65278. _this._updateEffectOptions = {
  65279. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  65280. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  65281. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  65282. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  65283. uniformBuffersNames: [],
  65284. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  65285. defines: "",
  65286. fallbacks: null,
  65287. onCompiled: null,
  65288. onError: null,
  65289. indexParameters: null,
  65290. maxSimultaneousLights: 0,
  65291. transformFeedbackVaryings: []
  65292. };
  65293. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  65294. // Random data
  65295. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  65296. var d = [];
  65297. for (var i = 0; i < maxTextureSize; ++i) {
  65298. d.push(Math.random());
  65299. d.push(Math.random());
  65300. d.push(Math.random());
  65301. d.push(Math.random());
  65302. }
  65303. _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);
  65304. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65305. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65306. d = [];
  65307. for (var i = 0; i < maxTextureSize; ++i) {
  65308. d.push(Math.random());
  65309. d.push(Math.random());
  65310. d.push(Math.random());
  65311. d.push(Math.random());
  65312. }
  65313. _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);
  65314. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65315. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65316. _this._randomTextureSize = maxTextureSize;
  65317. return _this;
  65318. }
  65319. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  65320. /**
  65321. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  65322. */
  65323. get: function () {
  65324. if (!BABYLON.Engine.LastCreatedEngine) {
  65325. return false;
  65326. }
  65327. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  65328. },
  65329. enumerable: true,
  65330. configurable: true
  65331. });
  65332. /**
  65333. * Gets the maximum number of particles active at the same time.
  65334. * @returns The max number of active particles.
  65335. */
  65336. GPUParticleSystem.prototype.getCapacity = function () {
  65337. return this._capacity;
  65338. };
  65339. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  65340. /**
  65341. * Gets or set the number of active particles
  65342. */
  65343. get: function () {
  65344. return this._activeCount;
  65345. },
  65346. set: function (value) {
  65347. this._activeCount = Math.min(value, this._capacity);
  65348. },
  65349. enumerable: true,
  65350. configurable: true
  65351. });
  65352. /**
  65353. * Is this system ready to be used/rendered
  65354. * @return true if the system is ready
  65355. */
  65356. GPUParticleSystem.prototype.isReady = function () {
  65357. if (!this._updateEffect) {
  65358. this._recreateUpdateEffect();
  65359. this._recreateRenderEffect();
  65360. return false;
  65361. }
  65362. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  65363. return false;
  65364. }
  65365. return true;
  65366. };
  65367. /**
  65368. * Gets if the system has been started. (Note: this will still be true after stop is called)
  65369. * @returns True if it has been started, otherwise false.
  65370. */
  65371. GPUParticleSystem.prototype.isStarted = function () {
  65372. return this._started;
  65373. };
  65374. /**
  65375. * Starts the particle system and begins to emit
  65376. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  65377. */
  65378. GPUParticleSystem.prototype.start = function (delay) {
  65379. var _this = this;
  65380. if (delay === void 0) { delay = this.startDelay; }
  65381. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  65382. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  65383. }
  65384. if (delay) {
  65385. setTimeout(function () {
  65386. _this.start(0);
  65387. }, delay);
  65388. return;
  65389. }
  65390. this._started = true;
  65391. this._stopped = false;
  65392. this._preWarmDone = false;
  65393. // Animations
  65394. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  65395. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  65396. }
  65397. };
  65398. /**
  65399. * Stops the particle system.
  65400. */
  65401. GPUParticleSystem.prototype.stop = function () {
  65402. this._stopped = true;
  65403. };
  65404. /**
  65405. * Remove all active particles
  65406. */
  65407. GPUParticleSystem.prototype.reset = function () {
  65408. this._releaseBuffers();
  65409. this._releaseVAOs();
  65410. this._currentActiveCount = 0;
  65411. this._targetIndex = 0;
  65412. };
  65413. /**
  65414. * Returns the string "GPUParticleSystem"
  65415. * @returns a string containing the class name
  65416. */
  65417. GPUParticleSystem.prototype.getClassName = function () {
  65418. return "GPUParticleSystem";
  65419. };
  65420. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  65421. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  65422. this._releaseBuffers();
  65423. return this;
  65424. };
  65425. /**
  65426. * Adds a new color gradient
  65427. * @param gradient defines the gradient to use (between 0 and 1)
  65428. * @param color1 defines the color to affect to the specified gradient
  65429. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  65430. * @returns the current particle system
  65431. */
  65432. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  65433. if (!this._colorGradients) {
  65434. this._colorGradients = [];
  65435. }
  65436. var colorGradient = new BABYLON.ColorGradient();
  65437. colorGradient.gradient = gradient;
  65438. colorGradient.color1 = color1;
  65439. this._colorGradients.push(colorGradient);
  65440. this._colorGradients.sort(function (a, b) {
  65441. if (a.gradient < b.gradient) {
  65442. return -1;
  65443. }
  65444. else if (a.gradient > b.gradient) {
  65445. return 1;
  65446. }
  65447. return 0;
  65448. });
  65449. if (this._colorGradientsTexture) {
  65450. this._colorGradientsTexture.dispose();
  65451. this._colorGradientsTexture = null;
  65452. }
  65453. this._releaseBuffers();
  65454. return this;
  65455. };
  65456. /**
  65457. * Remove a specific color gradient
  65458. * @param gradient defines the gradient to remove
  65459. * @returns the current particle system
  65460. */
  65461. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  65462. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  65463. this._colorGradientsTexture = null;
  65464. return this;
  65465. };
  65466. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  65467. var valueGradient = new BABYLON.FactorGradient();
  65468. valueGradient.gradient = gradient;
  65469. valueGradient.factor1 = factor;
  65470. factorGradients.push(valueGradient);
  65471. factorGradients.sort(function (a, b) {
  65472. if (a.gradient < b.gradient) {
  65473. return -1;
  65474. }
  65475. else if (a.gradient > b.gradient) {
  65476. return 1;
  65477. }
  65478. return 0;
  65479. });
  65480. this._releaseBuffers();
  65481. };
  65482. /**
  65483. * Adds a new size gradient
  65484. * @param gradient defines the gradient to use (between 0 and 1)
  65485. * @param factor defines the size factor to affect to the specified gradient
  65486. * @returns the current particle system
  65487. */
  65488. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  65489. if (!this._sizeGradients) {
  65490. this._sizeGradients = [];
  65491. }
  65492. this._addFactorGradient(this._sizeGradients, gradient, factor);
  65493. if (this._sizeGradientsTexture) {
  65494. this._sizeGradientsTexture.dispose();
  65495. this._sizeGradientsTexture = null;
  65496. }
  65497. this._releaseBuffers();
  65498. return this;
  65499. };
  65500. /**
  65501. * Remove a specific size gradient
  65502. * @param gradient defines the gradient to remove
  65503. * @returns the current particle system
  65504. */
  65505. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  65506. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  65507. this._sizeGradientsTexture = null;
  65508. return this;
  65509. };
  65510. /**
  65511. * Adds a new angular speed gradient
  65512. * @param gradient defines the gradient to use (between 0 and 1)
  65513. * @param factor defines the angular speed to affect to the specified gradient
  65514. * @returns the current particle system
  65515. */
  65516. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  65517. if (!this._angularSpeedGradients) {
  65518. this._angularSpeedGradients = [];
  65519. }
  65520. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  65521. if (this._angularSpeedGradientsTexture) {
  65522. this._angularSpeedGradientsTexture.dispose();
  65523. this._angularSpeedGradientsTexture = null;
  65524. }
  65525. this._releaseBuffers();
  65526. return this;
  65527. };
  65528. /**
  65529. * Remove a specific angular speed gradient
  65530. * @param gradient defines the gradient to remove
  65531. * @returns the current particle system
  65532. */
  65533. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  65534. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  65535. this._angularSpeedGradientsTexture = null;
  65536. return this;
  65537. };
  65538. /**
  65539. * Adds a new velocity gradient
  65540. * @param gradient defines the gradient to use (between 0 and 1)
  65541. * @param factor defines the velocity to affect to the specified gradient
  65542. * @returns the current particle system
  65543. */
  65544. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  65545. if (!this._velocityGradients) {
  65546. this._velocityGradients = [];
  65547. }
  65548. this._addFactorGradient(this._velocityGradients, gradient, factor);
  65549. if (this._velocityGradientsTexture) {
  65550. this._velocityGradientsTexture.dispose();
  65551. this._velocityGradientsTexture = null;
  65552. }
  65553. this._releaseBuffers();
  65554. return this;
  65555. };
  65556. /**
  65557. * Remove a specific velocity gradient
  65558. * @param gradient defines the gradient to remove
  65559. * @returns the current particle system
  65560. */
  65561. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  65562. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  65563. this._velocityGradientsTexture = null;
  65564. return this;
  65565. };
  65566. /**
  65567. * Adds a new limit velocity gradient
  65568. * @param gradient defines the gradient to use (between 0 and 1)
  65569. * @param factor defines the limit velocity value to affect to the specified gradient
  65570. * @returns the current particle system
  65571. */
  65572. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  65573. if (!this._limitVelocityGradients) {
  65574. this._limitVelocityGradients = [];
  65575. }
  65576. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  65577. if (this._limitVelocityGradientsTexture) {
  65578. this._limitVelocityGradientsTexture.dispose();
  65579. this._limitVelocityGradientsTexture = null;
  65580. }
  65581. this._releaseBuffers();
  65582. return this;
  65583. };
  65584. /**
  65585. * Remove a specific limit velocity gradient
  65586. * @param gradient defines the gradient to remove
  65587. * @returns the current particle system
  65588. */
  65589. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  65590. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  65591. this._limitVelocityGradientsTexture = null;
  65592. return this;
  65593. };
  65594. /**
  65595. * Adds a new drag gradient
  65596. * @param gradient defines the gradient to use (between 0 and 1)
  65597. * @param factor defines the drag value to affect to the specified gradient
  65598. * @returns the current particle system
  65599. */
  65600. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  65601. if (!this._dragGradients) {
  65602. this._dragGradients = [];
  65603. }
  65604. this._addFactorGradient(this._dragGradients, gradient, factor);
  65605. if (this._dragGradientsTexture) {
  65606. this._dragGradientsTexture.dispose();
  65607. this._dragGradientsTexture = null;
  65608. }
  65609. this._releaseBuffers();
  65610. return this;
  65611. };
  65612. /**
  65613. * Remove a specific drag gradient
  65614. * @param gradient defines the gradient to remove
  65615. * @returns the current particle system
  65616. */
  65617. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  65618. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  65619. this._dragGradientsTexture = null;
  65620. return this;
  65621. };
  65622. /**
  65623. * Not supported by GPUParticleSystem
  65624. * @param gradient defines the gradient to use (between 0 and 1)
  65625. * @param factor defines the emit rate value to affect to the specified gradient
  65626. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65627. * @returns the current particle system
  65628. */
  65629. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  65630. // Do nothing as emit rate is not supported by GPUParticleSystem
  65631. return this;
  65632. };
  65633. /**
  65634. * Not supported by GPUParticleSystem
  65635. * @param gradient defines the gradient to remove
  65636. * @returns the current particle system
  65637. */
  65638. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  65639. // Do nothing as emit rate is not supported by GPUParticleSystem
  65640. return this;
  65641. };
  65642. /**
  65643. * Not supported by GPUParticleSystem
  65644. * @param gradient defines the gradient to use (between 0 and 1)
  65645. * @param factor defines the start size value to affect to the specified gradient
  65646. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65647. * @returns the current particle system
  65648. */
  65649. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  65650. // Do nothing as start size is not supported by GPUParticleSystem
  65651. return this;
  65652. };
  65653. /**
  65654. * Not supported by GPUParticleSystem
  65655. * @param gradient defines the gradient to remove
  65656. * @returns the current particle system
  65657. */
  65658. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  65659. // Do nothing as start size is not supported by GPUParticleSystem
  65660. return this;
  65661. };
  65662. /**
  65663. * Not supported by GPUParticleSystem
  65664. * @param gradient defines the gradient to use (between 0 and 1)
  65665. * @param min defines the color remap minimal range
  65666. * @param max defines the color remap maximal range
  65667. * @returns the current particle system
  65668. */
  65669. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  65670. // Do nothing as start size is not supported by GPUParticleSystem
  65671. return this;
  65672. };
  65673. /**
  65674. * Not supported by GPUParticleSystem
  65675. * @param gradient defines the gradient to remove
  65676. * @returns the current particle system
  65677. */
  65678. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  65679. // Do nothing as start size is not supported by GPUParticleSystem
  65680. return this;
  65681. };
  65682. /**
  65683. * Not supported by GPUParticleSystem
  65684. * @param gradient defines the gradient to use (between 0 and 1)
  65685. * @param min defines the alpha remap minimal range
  65686. * @param max defines the alpha remap maximal range
  65687. * @returns the current particle system
  65688. */
  65689. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  65690. // Do nothing as start size is not supported by GPUParticleSystem
  65691. return this;
  65692. };
  65693. /**
  65694. * Not supported by GPUParticleSystem
  65695. * @param gradient defines the gradient to remove
  65696. * @returns the current particle system
  65697. */
  65698. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  65699. // Do nothing as start size is not supported by GPUParticleSystem
  65700. return this;
  65701. };
  65702. /**
  65703. * Not supported by GPUParticleSystem
  65704. * @param gradient defines the gradient to use (between 0 and 1)
  65705. * @param color defines the color to affect to the specified gradient
  65706. * @returns the current particle system
  65707. */
  65708. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  65709. //Not supported by GPUParticleSystem
  65710. return this;
  65711. };
  65712. /**
  65713. * Not supported by GPUParticleSystem
  65714. * @param gradient defines the gradient to remove
  65715. * @returns the current particle system
  65716. */
  65717. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  65718. //Not supported by GPUParticleSystem
  65719. return this;
  65720. };
  65721. /**
  65722. * Not supported by GPUParticleSystem
  65723. * @returns the list of ramp gradients
  65724. */
  65725. GPUParticleSystem.prototype.getRampGradients = function () {
  65726. return null;
  65727. };
  65728. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  65729. /**
  65730. * Not supported by GPUParticleSystem
  65731. * Gets or sets a boolean indicating that ramp gradients must be used
  65732. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  65733. */
  65734. get: function () {
  65735. //Not supported by GPUParticleSystem
  65736. return false;
  65737. },
  65738. set: function (value) {
  65739. //Not supported by GPUParticleSystem
  65740. },
  65741. enumerable: true,
  65742. configurable: true
  65743. });
  65744. /**
  65745. * Not supported by GPUParticleSystem
  65746. * @param gradient defines the gradient to use (between 0 and 1)
  65747. * @param factor defines the life time factor to affect to the specified gradient
  65748. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65749. * @returns the current particle system
  65750. */
  65751. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  65752. //Not supported by GPUParticleSystem
  65753. return this;
  65754. };
  65755. /**
  65756. * Not supported by GPUParticleSystem
  65757. * @param gradient defines the gradient to remove
  65758. * @returns the current particle system
  65759. */
  65760. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  65761. //Not supported by GPUParticleSystem
  65762. return this;
  65763. };
  65764. GPUParticleSystem.prototype._reset = function () {
  65765. this._releaseBuffers();
  65766. };
  65767. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  65768. var updateVertexBuffers = {};
  65769. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  65770. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  65771. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  65772. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  65773. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  65774. var offset = 12;
  65775. if (!this._colorGradientsTexture) {
  65776. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  65777. offset += 4;
  65778. }
  65779. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  65780. offset += 3;
  65781. if (!this._isBillboardBased) {
  65782. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  65783. offset += 3;
  65784. }
  65785. if (this._angularSpeedGradientsTexture) {
  65786. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  65787. offset += 1;
  65788. }
  65789. else {
  65790. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  65791. offset += 2;
  65792. }
  65793. if (this._isAnimationSheetEnabled) {
  65794. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  65795. offset += 1;
  65796. if (this.spriteRandomStartCell) {
  65797. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  65798. offset += 1;
  65799. }
  65800. }
  65801. if (this.noiseTexture) {
  65802. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  65803. offset += 3;
  65804. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  65805. offset += 3;
  65806. }
  65807. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  65808. this._engine.bindArrayBuffer(null);
  65809. return vao;
  65810. };
  65811. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  65812. var renderVertexBuffers = {};
  65813. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  65814. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  65815. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  65816. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  65817. var offset = 12;
  65818. if (!this._colorGradientsTexture) {
  65819. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  65820. offset += 4;
  65821. }
  65822. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  65823. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  65824. }
  65825. offset += 3; // Direction
  65826. if (!this._isBillboardBased) {
  65827. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  65828. offset += 3;
  65829. }
  65830. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  65831. if (this._angularSpeedGradientsTexture) {
  65832. offset++;
  65833. }
  65834. else {
  65835. offset += 2;
  65836. }
  65837. if (this._isAnimationSheetEnabled) {
  65838. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  65839. offset += 1;
  65840. if (this.spriteRandomStartCell) {
  65841. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  65842. offset += 1;
  65843. }
  65844. }
  65845. if (this.noiseTexture) {
  65846. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  65847. offset += 3;
  65848. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  65849. offset += 3;
  65850. }
  65851. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  65852. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  65853. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  65854. this._engine.bindArrayBuffer(null);
  65855. return vao;
  65856. };
  65857. GPUParticleSystem.prototype._initialize = function (force) {
  65858. if (force === void 0) { force = false; }
  65859. if (this._buffer0 && !force) {
  65860. return;
  65861. }
  65862. var engine = this._scene.getEngine();
  65863. var data = new Array();
  65864. if (!this.isBillboardBased) {
  65865. this._attributesStrideSize += 3;
  65866. }
  65867. if (this._colorGradientsTexture) {
  65868. this._attributesStrideSize -= 4;
  65869. }
  65870. if (this._angularSpeedGradientsTexture) {
  65871. this._attributesStrideSize -= 1;
  65872. }
  65873. if (this._isAnimationSheetEnabled) {
  65874. this._attributesStrideSize += 1;
  65875. if (this.spriteRandomStartCell) {
  65876. this._attributesStrideSize += 1;
  65877. }
  65878. }
  65879. if (this.noiseTexture) {
  65880. this._attributesStrideSize += 6;
  65881. }
  65882. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  65883. // position
  65884. data.push(0.0);
  65885. data.push(0.0);
  65886. data.push(0.0);
  65887. // Age and life
  65888. data.push(0.0); // create the particle as a dead one to create a new one at start
  65889. data.push(0.0);
  65890. // Seed
  65891. data.push(Math.random());
  65892. data.push(Math.random());
  65893. data.push(Math.random());
  65894. data.push(Math.random());
  65895. // Size
  65896. data.push(0.0);
  65897. data.push(0.0);
  65898. data.push(0.0);
  65899. if (!this._colorGradientsTexture) {
  65900. // color
  65901. data.push(0.0);
  65902. data.push(0.0);
  65903. data.push(0.0);
  65904. data.push(0.0);
  65905. }
  65906. // direction
  65907. data.push(0.0);
  65908. data.push(0.0);
  65909. data.push(0.0);
  65910. if (!this.isBillboardBased) {
  65911. // initialDirection
  65912. data.push(0.0);
  65913. data.push(0.0);
  65914. data.push(0.0);
  65915. }
  65916. // angle
  65917. data.push(0.0);
  65918. if (!this._angularSpeedGradientsTexture) {
  65919. data.push(0.0);
  65920. }
  65921. if (this._isAnimationSheetEnabled) {
  65922. data.push(0.0);
  65923. if (this.spriteRandomStartCell) {
  65924. data.push(0.0);
  65925. }
  65926. }
  65927. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  65928. data.push(Math.random());
  65929. data.push(Math.random());
  65930. data.push(Math.random());
  65931. data.push(Math.random());
  65932. data.push(Math.random());
  65933. data.push(Math.random());
  65934. }
  65935. }
  65936. // Sprite data
  65937. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  65938. -0.5, 0.5, 0, 1,
  65939. -0.5, -0.5, 0, 0,
  65940. 0.5, -0.5, 1, 0]);
  65941. // Buffers
  65942. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65943. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65944. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  65945. // Update VAO
  65946. this._updateVAO = [];
  65947. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  65948. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  65949. // Render VAO
  65950. this._renderVAO = [];
  65951. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  65952. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  65953. // Links
  65954. this._sourceBuffer = this._buffer0;
  65955. this._targetBuffer = this._buffer1;
  65956. };
  65957. /** @hidden */
  65958. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  65959. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  65960. if (this._isBillboardBased) {
  65961. defines += "\n#define BILLBOARD";
  65962. }
  65963. if (this._colorGradientsTexture) {
  65964. defines += "\n#define COLORGRADIENTS";
  65965. }
  65966. if (this._sizeGradientsTexture) {
  65967. defines += "\n#define SIZEGRADIENTS";
  65968. }
  65969. if (this._angularSpeedGradientsTexture) {
  65970. defines += "\n#define ANGULARSPEEDGRADIENTS";
  65971. }
  65972. if (this._velocityGradientsTexture) {
  65973. defines += "\n#define VELOCITYGRADIENTS";
  65974. }
  65975. if (this._limitVelocityGradientsTexture) {
  65976. defines += "\n#define LIMITVELOCITYGRADIENTS";
  65977. }
  65978. if (this._dragGradientsTexture) {
  65979. defines += "\n#define DRAGGRADIENTS";
  65980. }
  65981. if (this.isAnimationSheetEnabled) {
  65982. defines += "\n#define ANIMATESHEET";
  65983. if (this.spriteRandomStartCell) {
  65984. defines += "\n#define ANIMATESHEETRANDOMSTART";
  65985. }
  65986. }
  65987. if (this.noiseTexture) {
  65988. defines += "\n#define NOISE";
  65989. }
  65990. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  65991. return;
  65992. }
  65993. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  65994. if (!this._colorGradientsTexture) {
  65995. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  65996. }
  65997. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  65998. if (!this._isBillboardBased) {
  65999. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  66000. }
  66001. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  66002. if (this.isAnimationSheetEnabled) {
  66003. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  66004. if (this.spriteRandomStartCell) {
  66005. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  66006. }
  66007. }
  66008. if (this.noiseTexture) {
  66009. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  66010. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  66011. }
  66012. this._updateEffectOptions.defines = defines;
  66013. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  66014. };
  66015. /** @hidden */
  66016. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  66017. var defines = "";
  66018. if (this._scene.clipPlane) {
  66019. defines = "\n#define CLIPPLANE";
  66020. }
  66021. if (this._scene.clipPlane2) {
  66022. defines = "\n#define CLIPPLANE2";
  66023. }
  66024. if (this._scene.clipPlane3) {
  66025. defines = "\n#define CLIPPLANE3";
  66026. }
  66027. if (this._scene.clipPlane4) {
  66028. defines = "\n#define CLIPPLANE4";
  66029. }
  66030. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  66031. defines = "\n#define BLENDMULTIPLYMODE";
  66032. }
  66033. if (this._isBillboardBased) {
  66034. defines += "\n#define BILLBOARD";
  66035. switch (this.billboardMode) {
  66036. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  66037. defines += "\n#define BILLBOARDY";
  66038. break;
  66039. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  66040. defines += "\n#define BILLBOARDSTRETCHED";
  66041. break;
  66042. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  66043. default:
  66044. break;
  66045. }
  66046. }
  66047. if (this._colorGradientsTexture) {
  66048. defines += "\n#define COLORGRADIENTS";
  66049. }
  66050. if (this.isAnimationSheetEnabled) {
  66051. defines += "\n#define ANIMATESHEET";
  66052. }
  66053. if (this._imageProcessingConfiguration) {
  66054. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  66055. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  66056. }
  66057. if (this._renderEffect && this._renderEffect.defines === defines) {
  66058. return;
  66059. }
  66060. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  66061. var samplers = ["textureSampler", "colorGradientSampler"];
  66062. if (BABYLON.ImageProcessingConfiguration) {
  66063. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  66064. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  66065. }
  66066. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  66067. };
  66068. /**
  66069. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  66070. * @param preWarm defines if we are in the pre-warmimg phase
  66071. */
  66072. GPUParticleSystem.prototype.animate = function (preWarm) {
  66073. if (preWarm === void 0) { preWarm = false; }
  66074. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  66075. this._actualFrame += this._timeDelta;
  66076. if (!this._stopped) {
  66077. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  66078. this.stop();
  66079. }
  66080. }
  66081. };
  66082. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  66083. var texture = this[textureName];
  66084. if (!factorGradients || !factorGradients.length || texture) {
  66085. return;
  66086. }
  66087. var data = new Float32Array(this._rawTextureWidth);
  66088. for (var x = 0; x < this._rawTextureWidth; x++) {
  66089. var ratio = x / this._rawTextureWidth;
  66090. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  66091. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  66092. });
  66093. }
  66094. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66095. };
  66096. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  66097. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  66098. };
  66099. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  66100. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  66101. };
  66102. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  66103. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  66104. };
  66105. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  66106. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  66107. };
  66108. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  66109. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  66110. };
  66111. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  66112. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  66113. return;
  66114. }
  66115. var data = new Uint8Array(this._rawTextureWidth * 4);
  66116. var tmpColor = BABYLON.Tmp.Color4[0];
  66117. for (var x = 0; x < this._rawTextureWidth; x++) {
  66118. var ratio = x / this._rawTextureWidth;
  66119. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  66120. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  66121. data[x * 4] = tmpColor.r * 255;
  66122. data[x * 4 + 1] = tmpColor.g * 255;
  66123. data[x * 4 + 2] = tmpColor.b * 255;
  66124. data[x * 4 + 3] = tmpColor.a * 255;
  66125. });
  66126. }
  66127. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66128. };
  66129. /**
  66130. * Renders the particle system in its current state
  66131. * @param preWarm defines if the system should only update the particles but not render them
  66132. * @returns the current number of particles
  66133. */
  66134. GPUParticleSystem.prototype.render = function (preWarm) {
  66135. if (preWarm === void 0) { preWarm = false; }
  66136. if (!this._started) {
  66137. return 0;
  66138. }
  66139. this._createColorGradientTexture();
  66140. this._createSizeGradientTexture();
  66141. this._createAngularSpeedGradientTexture();
  66142. this._createVelocityGradientTexture();
  66143. this._createLimitVelocityGradientTexture();
  66144. this._createDragGradientTexture();
  66145. this._recreateUpdateEffect();
  66146. this._recreateRenderEffect();
  66147. if (!this.isReady()) {
  66148. return 0;
  66149. }
  66150. if (!preWarm) {
  66151. if (!this._preWarmDone && this.preWarmCycles) {
  66152. for (var index = 0; index < this.preWarmCycles; index++) {
  66153. this.animate(true);
  66154. this.render(true);
  66155. }
  66156. this._preWarmDone = true;
  66157. }
  66158. if (this._currentRenderId === this._scene.getRenderId()) {
  66159. return 0;
  66160. }
  66161. this._currentRenderId = this._scene.getRenderId();
  66162. }
  66163. // Get everything ready to render
  66164. this._initialize();
  66165. this._accumulatedCount += this.emitRate * this._timeDelta;
  66166. if (this._accumulatedCount > 1) {
  66167. var intPart = this._accumulatedCount | 0;
  66168. this._accumulatedCount -= intPart;
  66169. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  66170. }
  66171. if (!this._currentActiveCount) {
  66172. return 0;
  66173. }
  66174. // Enable update effect
  66175. this._engine.enableEffect(this._updateEffect);
  66176. this._engine.setState(false);
  66177. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  66178. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  66179. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  66180. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  66181. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  66182. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  66183. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  66184. if (!this._colorGradientsTexture) {
  66185. this._updateEffect.setDirectColor4("color1", this.color1);
  66186. this._updateEffect.setDirectColor4("color2", this.color2);
  66187. }
  66188. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  66189. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  66190. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  66191. this._updateEffect.setVector3("gravity", this.gravity);
  66192. if (this._sizeGradientsTexture) {
  66193. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  66194. }
  66195. if (this._angularSpeedGradientsTexture) {
  66196. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  66197. }
  66198. if (this._velocityGradientsTexture) {
  66199. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  66200. }
  66201. if (this._limitVelocityGradientsTexture) {
  66202. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  66203. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  66204. }
  66205. if (this._dragGradientsTexture) {
  66206. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  66207. }
  66208. if (this.particleEmitterType) {
  66209. this.particleEmitterType.applyToShader(this._updateEffect);
  66210. }
  66211. if (this._isAnimationSheetEnabled) {
  66212. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  66213. }
  66214. if (this.noiseTexture) {
  66215. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  66216. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  66217. }
  66218. var emitterWM;
  66219. if (this.emitter.position) {
  66220. var emitterMesh = this.emitter;
  66221. emitterWM = emitterMesh.getWorldMatrix();
  66222. }
  66223. else {
  66224. var emitterPosition = this.emitter;
  66225. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  66226. }
  66227. this._updateEffect.setMatrix("emitterWM", emitterWM);
  66228. // Bind source VAO
  66229. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  66230. // Update
  66231. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  66232. this._engine.setRasterizerState(false);
  66233. this._engine.beginTransformFeedback(true);
  66234. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  66235. this._engine.endTransformFeedback();
  66236. this._engine.setRasterizerState(true);
  66237. this._engine.bindTransformFeedbackBuffer(null);
  66238. if (!preWarm) {
  66239. // Enable render effect
  66240. this._engine.enableEffect(this._renderEffect);
  66241. var viewMatrix = this._scene.getViewMatrix();
  66242. this._renderEffect.setMatrix("view", viewMatrix);
  66243. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  66244. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  66245. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  66246. if (this._colorGradientsTexture) {
  66247. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  66248. }
  66249. else {
  66250. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  66251. }
  66252. if (this._isAnimationSheetEnabled && this.particleTexture) {
  66253. var baseSize = this.particleTexture.getBaseSize();
  66254. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  66255. }
  66256. if (this._isBillboardBased) {
  66257. var camera = this._scene.activeCamera;
  66258. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  66259. }
  66260. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  66261. var invView = viewMatrix.clone();
  66262. invView.invert();
  66263. this._renderEffect.setMatrix("invView", invView);
  66264. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  66265. }
  66266. // image processing
  66267. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  66268. this._imageProcessingConfiguration.bind(this._renderEffect);
  66269. }
  66270. // Draw order
  66271. switch (this.blendMode) {
  66272. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  66273. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  66274. break;
  66275. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  66276. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  66277. break;
  66278. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  66279. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  66280. break;
  66281. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  66282. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  66283. break;
  66284. }
  66285. if (this.forceDepthWrite) {
  66286. this._engine.setDepthWrite(true);
  66287. }
  66288. // Bind source VAO
  66289. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  66290. // Render
  66291. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  66292. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66293. }
  66294. // Switch VAOs
  66295. this._targetIndex++;
  66296. if (this._targetIndex === 2) {
  66297. this._targetIndex = 0;
  66298. }
  66299. // Switch buffers
  66300. var tmpBuffer = this._sourceBuffer;
  66301. this._sourceBuffer = this._targetBuffer;
  66302. this._targetBuffer = tmpBuffer;
  66303. return this._currentActiveCount;
  66304. };
  66305. /**
  66306. * Rebuilds the particle system
  66307. */
  66308. GPUParticleSystem.prototype.rebuild = function () {
  66309. this._initialize(true);
  66310. };
  66311. GPUParticleSystem.prototype._releaseBuffers = function () {
  66312. if (this._buffer0) {
  66313. this._buffer0.dispose();
  66314. this._buffer0 = null;
  66315. }
  66316. if (this._buffer1) {
  66317. this._buffer1.dispose();
  66318. this._buffer1 = null;
  66319. }
  66320. if (this._spriteBuffer) {
  66321. this._spriteBuffer.dispose();
  66322. this._spriteBuffer = null;
  66323. }
  66324. };
  66325. GPUParticleSystem.prototype._releaseVAOs = function () {
  66326. if (!this._updateVAO) {
  66327. return;
  66328. }
  66329. for (var index = 0; index < this._updateVAO.length; index++) {
  66330. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  66331. }
  66332. this._updateVAO = [];
  66333. for (var index = 0; index < this._renderVAO.length; index++) {
  66334. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  66335. }
  66336. this._renderVAO = [];
  66337. };
  66338. /**
  66339. * Disposes the particle system and free the associated resources
  66340. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  66341. */
  66342. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  66343. if (disposeTexture === void 0) { disposeTexture = true; }
  66344. var index = this._scene.particleSystems.indexOf(this);
  66345. if (index > -1) {
  66346. this._scene.particleSystems.splice(index, 1);
  66347. }
  66348. this._releaseBuffers();
  66349. this._releaseVAOs();
  66350. if (this._colorGradientsTexture) {
  66351. this._colorGradientsTexture.dispose();
  66352. this._colorGradientsTexture = null;
  66353. }
  66354. if (this._sizeGradientsTexture) {
  66355. this._sizeGradientsTexture.dispose();
  66356. this._sizeGradientsTexture = null;
  66357. }
  66358. if (this._angularSpeedGradientsTexture) {
  66359. this._angularSpeedGradientsTexture.dispose();
  66360. this._angularSpeedGradientsTexture = null;
  66361. }
  66362. if (this._velocityGradientsTexture) {
  66363. this._velocityGradientsTexture.dispose();
  66364. this._velocityGradientsTexture = null;
  66365. }
  66366. if (this._limitVelocityGradientsTexture) {
  66367. this._limitVelocityGradientsTexture.dispose();
  66368. this._limitVelocityGradientsTexture = null;
  66369. }
  66370. if (this._dragGradientsTexture) {
  66371. this._dragGradientsTexture.dispose();
  66372. this._dragGradientsTexture = null;
  66373. }
  66374. if (this._randomTexture) {
  66375. this._randomTexture.dispose();
  66376. this._randomTexture = null;
  66377. }
  66378. if (this._randomTexture2) {
  66379. this._randomTexture2.dispose();
  66380. this._randomTexture2 = null;
  66381. }
  66382. if (disposeTexture && this.particleTexture) {
  66383. this.particleTexture.dispose();
  66384. this.particleTexture = null;
  66385. }
  66386. if (disposeTexture && this.noiseTexture) {
  66387. this.noiseTexture.dispose();
  66388. this.noiseTexture = null;
  66389. }
  66390. // Callback
  66391. this.onDisposeObservable.notifyObservers(this);
  66392. this.onDisposeObservable.clear();
  66393. };
  66394. /**
  66395. * Clones the particle system.
  66396. * @param name The name of the cloned object
  66397. * @param newEmitter The new emitter to use
  66398. * @returns the cloned particle system
  66399. */
  66400. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  66401. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  66402. BABYLON.Tools.DeepCopy(this, result);
  66403. if (newEmitter === undefined) {
  66404. newEmitter = this.emitter;
  66405. }
  66406. result.emitter = newEmitter;
  66407. if (this.particleTexture) {
  66408. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  66409. }
  66410. return result;
  66411. };
  66412. /**
  66413. * Serializes the particle system to a JSON object.
  66414. * @returns the JSON object
  66415. */
  66416. GPUParticleSystem.prototype.serialize = function () {
  66417. var serializationObject = {};
  66418. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  66419. serializationObject.activeParticleCount = this.activeParticleCount;
  66420. return serializationObject;
  66421. };
  66422. /**
  66423. * Parses a JSON object to create a GPU particle system.
  66424. * @param parsedParticleSystem The JSON object to parse
  66425. * @param scene The scene to create the particle system in
  66426. * @param rootUrl The root url to use to load external dependencies like texture
  66427. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  66428. * @returns the parsed GPU particle system
  66429. */
  66430. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  66431. if (doNotStart === void 0) { doNotStart = false; }
  66432. var name = parsedParticleSystem.name;
  66433. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  66434. if (parsedParticleSystem.activeParticleCount) {
  66435. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  66436. }
  66437. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  66438. // Auto start
  66439. if (parsedParticleSystem.preventAutoStart) {
  66440. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  66441. }
  66442. if (!doNotStart && !particleSystem.preventAutoStart) {
  66443. particleSystem.start();
  66444. }
  66445. return particleSystem;
  66446. };
  66447. return GPUParticleSystem;
  66448. }(BABYLON.BaseParticleSystem));
  66449. BABYLON.GPUParticleSystem = GPUParticleSystem;
  66450. })(BABYLON || (BABYLON = {}));
  66451. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  66452. var BABYLON;
  66453. (function (BABYLON) {
  66454. /**
  66455. * Represents one particle of a solid particle system.
  66456. */
  66457. var SolidParticle = /** @class */ (function () {
  66458. /**
  66459. * Creates a Solid Particle object.
  66460. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  66461. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  66462. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  66463. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  66464. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  66465. * @param shapeId (integer) is the model shape identifier in the SPS.
  66466. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  66467. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  66468. */
  66469. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  66470. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  66471. /**
  66472. * particle global index
  66473. */
  66474. this.idx = 0;
  66475. /**
  66476. * The color of the particle
  66477. */
  66478. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66479. /**
  66480. * The world space position of the particle.
  66481. */
  66482. this.position = BABYLON.Vector3.Zero();
  66483. /**
  66484. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  66485. */
  66486. this.rotation = BABYLON.Vector3.Zero();
  66487. /**
  66488. * The scaling of the particle.
  66489. */
  66490. this.scaling = BABYLON.Vector3.One();
  66491. /**
  66492. * The uvs of the particle.
  66493. */
  66494. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  66495. /**
  66496. * The current speed of the particle.
  66497. */
  66498. this.velocity = BABYLON.Vector3.Zero();
  66499. /**
  66500. * The pivot point in the particle local space.
  66501. */
  66502. this.pivot = BABYLON.Vector3.Zero();
  66503. /**
  66504. * Must the particle be translated from its pivot point in its local space ?
  66505. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  66506. * Default : false
  66507. */
  66508. this.translateFromPivot = false;
  66509. /**
  66510. * Is the particle active or not ?
  66511. */
  66512. this.alive = true;
  66513. /**
  66514. * Is the particle visible or not ?
  66515. */
  66516. this.isVisible = true;
  66517. /**
  66518. * Index of this particle in the global "positions" array (Internal use)
  66519. * @hidden
  66520. */
  66521. this._pos = 0;
  66522. /**
  66523. * @hidden Index of this particle in the global "indices" array (Internal use)
  66524. */
  66525. this._ind = 0;
  66526. /**
  66527. * ModelShape id of this particle
  66528. */
  66529. this.shapeId = 0;
  66530. /**
  66531. * Index of the particle in its shape id (Internal use)
  66532. */
  66533. this.idxInShape = 0;
  66534. /**
  66535. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  66536. */
  66537. this._stillInvisible = false;
  66538. /**
  66539. * @hidden Last computed particle rotation matrix
  66540. */
  66541. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  66542. /**
  66543. * Parent particle Id, if any.
  66544. * Default null.
  66545. */
  66546. this.parentId = null;
  66547. /**
  66548. * @hidden Internal global position in the SPS.
  66549. */
  66550. this._globalPosition = BABYLON.Vector3.Zero();
  66551. this.idx = particleIndex;
  66552. this._pos = positionIndex;
  66553. this._ind = indiceIndex;
  66554. this._model = model;
  66555. this.shapeId = shapeId;
  66556. this.idxInShape = idxInShape;
  66557. this._sps = sps;
  66558. if (modelBoundingInfo) {
  66559. this._modelBoundingInfo = modelBoundingInfo;
  66560. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  66561. }
  66562. }
  66563. Object.defineProperty(SolidParticle.prototype, "scale", {
  66564. /**
  66565. * Legacy support, changed scale to scaling
  66566. */
  66567. get: function () {
  66568. return this.scaling;
  66569. },
  66570. /**
  66571. * Legacy support, changed scale to scaling
  66572. */
  66573. set: function (scale) {
  66574. this.scaling = scale;
  66575. },
  66576. enumerable: true,
  66577. configurable: true
  66578. });
  66579. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  66580. /**
  66581. * Legacy support, changed quaternion to rotationQuaternion
  66582. */
  66583. get: function () {
  66584. return this.rotationQuaternion;
  66585. },
  66586. /**
  66587. * Legacy support, changed quaternion to rotationQuaternion
  66588. */
  66589. set: function (q) {
  66590. this.rotationQuaternion = q;
  66591. },
  66592. enumerable: true,
  66593. configurable: true
  66594. });
  66595. /**
  66596. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  66597. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  66598. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  66599. * @returns true if it intersects
  66600. */
  66601. SolidParticle.prototype.intersectsMesh = function (target) {
  66602. if (!this._boundingInfo || !target._boundingInfo) {
  66603. return false;
  66604. }
  66605. if (this._sps._bSphereOnly) {
  66606. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  66607. }
  66608. return this._boundingInfo.intersects(target._boundingInfo, false);
  66609. };
  66610. return SolidParticle;
  66611. }());
  66612. BABYLON.SolidParticle = SolidParticle;
  66613. /**
  66614. * Represents the shape of the model used by one particle of a solid particle system.
  66615. * SPS internal tool, don't use it manually.
  66616. */
  66617. var ModelShape = /** @class */ (function () {
  66618. /**
  66619. * 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.
  66620. * SPS internal tool, don't use it manually.
  66621. * @hidden
  66622. */
  66623. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  66624. /**
  66625. * length of the shape in the model indices array (internal use)
  66626. * @hidden
  66627. */
  66628. this._indicesLength = 0;
  66629. this.shapeID = id;
  66630. this._shape = shape;
  66631. this._indicesLength = indicesLength;
  66632. this._shapeUV = shapeUV;
  66633. this._positionFunction = posFunction;
  66634. this._vertexFunction = vtxFunction;
  66635. }
  66636. return ModelShape;
  66637. }());
  66638. BABYLON.ModelShape = ModelShape;
  66639. /**
  66640. * Represents a Depth Sorted Particle in the solid particle system.
  66641. */
  66642. var DepthSortedParticle = /** @class */ (function () {
  66643. function DepthSortedParticle() {
  66644. /**
  66645. * Index of the particle in the "indices" array
  66646. */
  66647. this.ind = 0;
  66648. /**
  66649. * Length of the particle shape in the "indices" array
  66650. */
  66651. this.indicesLength = 0;
  66652. /**
  66653. * Squared distance from the particle to the camera
  66654. */
  66655. this.sqDistance = 0.0;
  66656. }
  66657. return DepthSortedParticle;
  66658. }());
  66659. BABYLON.DepthSortedParticle = DepthSortedParticle;
  66660. })(BABYLON || (BABYLON = {}));
  66661. //# sourceMappingURL=babylon.solidParticle.js.map
  66662. var BABYLON;
  66663. (function (BABYLON) {
  66664. /**
  66665. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  66666. *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.
  66667. * The SPS is also a particle system. It provides some methods to manage the particles.
  66668. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  66669. *
  66670. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  66671. */
  66672. var SolidParticleSystem = /** @class */ (function () {
  66673. /**
  66674. * Creates a SPS (Solid Particle System) object.
  66675. * @param name (String) is the SPS name, this will be the underlying mesh name.
  66676. * @param scene (Scene) is the scene in which the SPS is added.
  66677. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  66678. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  66679. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  66680. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  66681. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  66682. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  66683. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  66684. */
  66685. function SolidParticleSystem(name, scene, options) {
  66686. /**
  66687. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  66688. * Example : var p = SPS.particles[i];
  66689. */
  66690. this.particles = new Array();
  66691. /**
  66692. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  66693. */
  66694. this.nbParticles = 0;
  66695. /**
  66696. * If the particles must ever face the camera (default false). Useful for planar particles.
  66697. */
  66698. this.billboard = false;
  66699. /**
  66700. * Recompute normals when adding a shape
  66701. */
  66702. this.recomputeNormals = true;
  66703. /**
  66704. * This a counter ofr your own usage. It's not set by any SPS functions.
  66705. */
  66706. this.counter = 0;
  66707. /**
  66708. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  66709. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  66710. */
  66711. this.vars = {};
  66712. /**
  66713. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  66714. * @hidden
  66715. */
  66716. this._bSphereOnly = false;
  66717. /**
  66718. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  66719. * @hidden
  66720. */
  66721. this._bSphereRadiusFactor = 1.0;
  66722. this._positions = new Array();
  66723. this._indices = new Array();
  66724. this._normals = new Array();
  66725. this._colors = new Array();
  66726. this._uvs = new Array();
  66727. this._index = 0; // indices index
  66728. this._updatable = true;
  66729. this._pickable = false;
  66730. this._isVisibilityBoxLocked = false;
  66731. this._alwaysVisible = false;
  66732. this._depthSort = false;
  66733. this._shapeCounter = 0;
  66734. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  66735. this._color = new BABYLON.Color4(0, 0, 0, 0);
  66736. this._computeParticleColor = true;
  66737. this._computeParticleTexture = true;
  66738. this._computeParticleRotation = true;
  66739. this._computeParticleVertex = false;
  66740. this._computeBoundingBox = false;
  66741. this._depthSortParticles = true;
  66742. this._cam_axisZ = BABYLON.Vector3.Zero();
  66743. this._cam_axisY = BABYLON.Vector3.Zero();
  66744. this._cam_axisX = BABYLON.Vector3.Zero();
  66745. this._axisZ = BABYLON.Axis.Z;
  66746. this._camDir = BABYLON.Vector3.Zero();
  66747. this._camInvertedPosition = BABYLON.Vector3.Zero();
  66748. this._rotMatrix = new BABYLON.Matrix();
  66749. this._invertMatrix = new BABYLON.Matrix();
  66750. this._rotated = BABYLON.Vector3.Zero();
  66751. this._quaternion = new BABYLON.Quaternion();
  66752. this._vertex = BABYLON.Vector3.Zero();
  66753. this._normal = BABYLON.Vector3.Zero();
  66754. this._yaw = 0.0;
  66755. this._pitch = 0.0;
  66756. this._roll = 0.0;
  66757. this._halfroll = 0.0;
  66758. this._halfpitch = 0.0;
  66759. this._halfyaw = 0.0;
  66760. this._sinRoll = 0.0;
  66761. this._cosRoll = 0.0;
  66762. this._sinPitch = 0.0;
  66763. this._cosPitch = 0.0;
  66764. this._sinYaw = 0.0;
  66765. this._cosYaw = 0.0;
  66766. this._mustUnrotateFixedNormals = false;
  66767. this._minimum = BABYLON.Vector3.Zero();
  66768. this._maximum = BABYLON.Vector3.Zero();
  66769. this._minBbox = BABYLON.Vector3.Zero();
  66770. this._maxBbox = BABYLON.Vector3.Zero();
  66771. this._particlesIntersect = false;
  66772. this._depthSortFunction = function (p1, p2) {
  66773. return (p2.sqDistance - p1.sqDistance);
  66774. };
  66775. this._needs32Bits = false;
  66776. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  66777. this._scaledPivot = BABYLON.Vector3.Zero();
  66778. this._particleHasParent = false;
  66779. this.name = name;
  66780. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66781. this._camera = scene.activeCamera;
  66782. this._pickable = options ? options.isPickable : false;
  66783. this._depthSort = options ? options.enableDepthSort : false;
  66784. this._particlesIntersect = options ? options.particleIntersection : false;
  66785. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  66786. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  66787. if (options && options.updatable !== undefined) {
  66788. this._updatable = options.updatable;
  66789. }
  66790. else {
  66791. this._updatable = true;
  66792. }
  66793. if (this._pickable) {
  66794. this.pickedParticles = [];
  66795. }
  66796. if (this._depthSort) {
  66797. this.depthSortedParticles = [];
  66798. }
  66799. }
  66800. /**
  66801. * Builds the SPS underlying mesh. Returns a standard Mesh.
  66802. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  66803. * @returns the created mesh
  66804. */
  66805. SolidParticleSystem.prototype.buildMesh = function () {
  66806. if (this.nbParticles === 0) {
  66807. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  66808. this.addShape(triangle, 1);
  66809. triangle.dispose();
  66810. }
  66811. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  66812. this._positions32 = new Float32Array(this._positions);
  66813. this._uvs32 = new Float32Array(this._uvs);
  66814. this._colors32 = new Float32Array(this._colors);
  66815. if (this.recomputeNormals) {
  66816. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  66817. }
  66818. this._normals32 = new Float32Array(this._normals);
  66819. this._fixedNormal32 = new Float32Array(this._normals);
  66820. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  66821. this._unrotateFixedNormals();
  66822. }
  66823. var vertexData = new BABYLON.VertexData();
  66824. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  66825. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  66826. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  66827. if (this._uvs32.length > 0) {
  66828. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  66829. }
  66830. if (this._colors32.length > 0) {
  66831. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  66832. }
  66833. var mesh = new BABYLON.Mesh(this.name, this._scene);
  66834. vertexData.applyToMesh(mesh, this._updatable);
  66835. this.mesh = mesh;
  66836. this.mesh.isPickable = this._pickable;
  66837. // free memory
  66838. if (!this._depthSort) {
  66839. this._indices = null;
  66840. }
  66841. this._positions = null;
  66842. this._normals = null;
  66843. this._uvs = null;
  66844. this._colors = null;
  66845. if (!this._updatable) {
  66846. this.particles.length = 0;
  66847. }
  66848. return mesh;
  66849. };
  66850. /**
  66851. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  66852. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  66853. * Thus the particles generated from `digest()` have their property `position` set yet.
  66854. * @param mesh ( Mesh ) is the mesh to be digested
  66855. * @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
  66856. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  66857. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  66858. * @returns the current SPS
  66859. */
  66860. SolidParticleSystem.prototype.digest = function (mesh, options) {
  66861. var size = (options && options.facetNb) || 1;
  66862. var number = (options && options.number) || 0;
  66863. var delta = (options && options.delta) || 0;
  66864. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66865. var meshInd = mesh.getIndices();
  66866. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66867. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66868. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66869. var f = 0; // facet counter
  66870. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  66871. // compute size from number
  66872. if (number) {
  66873. number = (number > totalFacets) ? totalFacets : number;
  66874. size = Math.round(totalFacets / number);
  66875. delta = 0;
  66876. }
  66877. else {
  66878. size = (size > totalFacets) ? totalFacets : size;
  66879. }
  66880. var facetPos = []; // submesh positions
  66881. var facetInd = []; // submesh indices
  66882. var facetUV = []; // submesh UV
  66883. var facetCol = []; // submesh colors
  66884. var barycenter = BABYLON.Vector3.Zero();
  66885. var sizeO = size;
  66886. while (f < totalFacets) {
  66887. size = sizeO + Math.floor((1 + delta) * Math.random());
  66888. if (f > totalFacets - size) {
  66889. size = totalFacets - f;
  66890. }
  66891. // reset temp arrays
  66892. facetPos.length = 0;
  66893. facetInd.length = 0;
  66894. facetUV.length = 0;
  66895. facetCol.length = 0;
  66896. // iterate over "size" facets
  66897. var fi = 0;
  66898. for (var j = f * 3; j < (f + size) * 3; j++) {
  66899. facetInd.push(fi);
  66900. var i = meshInd[j];
  66901. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  66902. if (meshUV) {
  66903. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  66904. }
  66905. if (meshCol) {
  66906. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  66907. }
  66908. fi++;
  66909. }
  66910. // create a model shape for each single particle
  66911. var idx = this.nbParticles;
  66912. var shape = this._posToShape(facetPos);
  66913. var shapeUV = this._uvsToShapeUV(facetUV);
  66914. // compute the barycenter of the shape
  66915. var v;
  66916. for (v = 0; v < shape.length; v++) {
  66917. barycenter.addInPlace(shape[v]);
  66918. }
  66919. barycenter.scaleInPlace(1 / shape.length);
  66920. // shift the shape from its barycenter to the origin
  66921. for (v = 0; v < shape.length; v++) {
  66922. shape[v].subtractInPlace(barycenter);
  66923. }
  66924. var bInfo;
  66925. if (this._particlesIntersect) {
  66926. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  66927. }
  66928. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  66929. // add the particle in the SPS
  66930. var currentPos = this._positions.length;
  66931. var currentInd = this._indices.length;
  66932. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  66933. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  66934. // initialize the particle position
  66935. this.particles[this.nbParticles].position.addInPlace(barycenter);
  66936. this._index += shape.length;
  66937. idx++;
  66938. this.nbParticles++;
  66939. this._shapeCounter++;
  66940. f += size;
  66941. }
  66942. return this;
  66943. };
  66944. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  66945. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  66946. var index = 0;
  66947. var idx = 0;
  66948. for (var p = 0; p < this.particles.length; p++) {
  66949. this._particle = this.particles[p];
  66950. this._shape = this._particle._model._shape;
  66951. if (this._particle.rotationQuaternion) {
  66952. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66953. }
  66954. else {
  66955. this._yaw = this._particle.rotation.y;
  66956. this._pitch = this._particle.rotation.x;
  66957. this._roll = this._particle.rotation.z;
  66958. this._quaternionRotationYPR();
  66959. }
  66960. this._quaternionToRotationMatrix();
  66961. this._rotMatrix.invertToRef(this._invertMatrix);
  66962. for (var pt = 0; pt < this._shape.length; pt++) {
  66963. idx = index + pt * 3;
  66964. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  66965. this._fixedNormal32[idx] = this._normal.x;
  66966. this._fixedNormal32[idx + 1] = this._normal.y;
  66967. this._fixedNormal32[idx + 2] = this._normal.z;
  66968. }
  66969. index = idx + 3;
  66970. }
  66971. };
  66972. //reset copy
  66973. SolidParticleSystem.prototype._resetCopy = function () {
  66974. this._copy.position.x = 0;
  66975. this._copy.position.y = 0;
  66976. this._copy.position.z = 0;
  66977. this._copy.rotation.x = 0;
  66978. this._copy.rotation.y = 0;
  66979. this._copy.rotation.z = 0;
  66980. this._copy.rotationQuaternion = null;
  66981. this._copy.scaling.x = 1.0;
  66982. this._copy.scaling.y = 1.0;
  66983. this._copy.scaling.z = 1.0;
  66984. this._copy.uvs.x = 0;
  66985. this._copy.uvs.y = 0;
  66986. this._copy.uvs.z = 1.0;
  66987. this._copy.uvs.w = 1.0;
  66988. this._copy.color = null;
  66989. this._copy.translateFromPivot = false;
  66990. };
  66991. // _meshBuilder : inserts the shape model in the global SPS mesh
  66992. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  66993. var i;
  66994. var u = 0;
  66995. var c = 0;
  66996. var n = 0;
  66997. this._resetCopy();
  66998. if (options && options.positionFunction) { // call to custom positionFunction
  66999. options.positionFunction(this._copy, idx, idxInShape);
  67000. this._mustUnrotateFixedNormals = true;
  67001. }
  67002. if (this._copy.rotationQuaternion) {
  67003. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  67004. }
  67005. else {
  67006. this._yaw = this._copy.rotation.y;
  67007. this._pitch = this._copy.rotation.x;
  67008. this._roll = this._copy.rotation.z;
  67009. this._quaternionRotationYPR();
  67010. }
  67011. this._quaternionToRotationMatrix();
  67012. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  67013. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  67014. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  67015. if (this._copy.translateFromPivot) {
  67016. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  67017. }
  67018. else {
  67019. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  67020. }
  67021. for (i = 0; i < shape.length; i++) {
  67022. this._vertex.x = shape[i].x;
  67023. this._vertex.y = shape[i].y;
  67024. this._vertex.z = shape[i].z;
  67025. if (options && options.vertexFunction) {
  67026. options.vertexFunction(this._copy, this._vertex, i);
  67027. }
  67028. this._vertex.x *= this._copy.scaling.x;
  67029. this._vertex.y *= this._copy.scaling.y;
  67030. this._vertex.z *= this._copy.scaling.z;
  67031. this._vertex.x -= this._scaledPivot.x;
  67032. this._vertex.y -= this._scaledPivot.y;
  67033. this._vertex.z -= this._scaledPivot.z;
  67034. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  67035. this._rotated.addInPlace(this._pivotBackTranslation);
  67036. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  67037. if (meshUV) {
  67038. 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);
  67039. u += 2;
  67040. }
  67041. if (this._copy.color) {
  67042. this._color = this._copy.color;
  67043. }
  67044. else if (meshCol && meshCol[c] !== undefined) {
  67045. this._color.r = meshCol[c];
  67046. this._color.g = meshCol[c + 1];
  67047. this._color.b = meshCol[c + 2];
  67048. this._color.a = meshCol[c + 3];
  67049. }
  67050. else {
  67051. this._color.r = 1.0;
  67052. this._color.g = 1.0;
  67053. this._color.b = 1.0;
  67054. this._color.a = 1.0;
  67055. }
  67056. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  67057. c += 4;
  67058. if (!this.recomputeNormals && meshNor) {
  67059. this._normal.x = meshNor[n];
  67060. this._normal.y = meshNor[n + 1];
  67061. this._normal.z = meshNor[n + 2];
  67062. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  67063. normals.push(this._normal.x, this._normal.y, this._normal.z);
  67064. n += 3;
  67065. }
  67066. }
  67067. for (i = 0; i < meshInd.length; i++) {
  67068. var current_ind = p + meshInd[i];
  67069. indices.push(current_ind);
  67070. if (current_ind > 65535) {
  67071. this._needs32Bits = true;
  67072. }
  67073. }
  67074. if (this._pickable) {
  67075. var nbfaces = meshInd.length / 3;
  67076. for (i = 0; i < nbfaces; i++) {
  67077. this.pickedParticles.push({ idx: idx, faceId: i });
  67078. }
  67079. }
  67080. if (this._depthSort) {
  67081. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  67082. }
  67083. return this._copy;
  67084. };
  67085. // returns a shape array from positions array
  67086. SolidParticleSystem.prototype._posToShape = function (positions) {
  67087. var shape = [];
  67088. for (var i = 0; i < positions.length; i += 3) {
  67089. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  67090. }
  67091. return shape;
  67092. };
  67093. // returns a shapeUV array from a Vector4 uvs
  67094. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  67095. var shapeUV = [];
  67096. if (uvs) {
  67097. for (var i = 0; i < uvs.length; i++) {
  67098. shapeUV.push(uvs[i]);
  67099. }
  67100. }
  67101. return shapeUV;
  67102. };
  67103. // adds a new particle object in the particles array
  67104. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  67105. if (bInfo === void 0) { bInfo = null; }
  67106. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  67107. this.particles.push(sp);
  67108. return sp;
  67109. };
  67110. /**
  67111. * Adds some particles to the SPS from the model shape. Returns the shape id.
  67112. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  67113. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  67114. * @param nb (positive integer) the number of particles to be created from this model
  67115. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  67116. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  67117. * @returns the number of shapes in the system
  67118. */
  67119. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  67120. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67121. var meshInd = mesh.getIndices();
  67122. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67123. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67124. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67125. var bbInfo;
  67126. if (this._particlesIntersect) {
  67127. bbInfo = mesh.getBoundingInfo();
  67128. }
  67129. var shape = this._posToShape(meshPos);
  67130. var shapeUV = this._uvsToShapeUV(meshUV);
  67131. var posfunc = options ? options.positionFunction : null;
  67132. var vtxfunc = options ? options.vertexFunction : null;
  67133. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  67134. // particles
  67135. var sp;
  67136. var currentCopy;
  67137. var idx = this.nbParticles;
  67138. for (var i = 0; i < nb; i++) {
  67139. var currentPos = this._positions.length;
  67140. var currentInd = this._indices.length;
  67141. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  67142. if (this._updatable) {
  67143. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  67144. sp.position.copyFrom(currentCopy.position);
  67145. sp.rotation.copyFrom(currentCopy.rotation);
  67146. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  67147. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  67148. }
  67149. if (currentCopy.color && sp.color) {
  67150. sp.color.copyFrom(currentCopy.color);
  67151. }
  67152. sp.scaling.copyFrom(currentCopy.scaling);
  67153. sp.uvs.copyFrom(currentCopy.uvs);
  67154. }
  67155. this._index += shape.length;
  67156. idx++;
  67157. }
  67158. this.nbParticles += nb;
  67159. this._shapeCounter++;
  67160. return this._shapeCounter - 1;
  67161. };
  67162. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  67163. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  67164. this._resetCopy();
  67165. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  67166. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  67167. }
  67168. if (this._copy.rotationQuaternion) {
  67169. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  67170. }
  67171. else {
  67172. this._yaw = this._copy.rotation.y;
  67173. this._pitch = this._copy.rotation.x;
  67174. this._roll = this._copy.rotation.z;
  67175. this._quaternionRotationYPR();
  67176. }
  67177. this._quaternionToRotationMatrix();
  67178. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67179. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67180. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67181. if (this._copy.translateFromPivot) {
  67182. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  67183. }
  67184. else {
  67185. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  67186. }
  67187. this._shape = particle._model._shape;
  67188. for (var pt = 0; pt < this._shape.length; pt++) {
  67189. this._vertex.x = this._shape[pt].x;
  67190. this._vertex.y = this._shape[pt].y;
  67191. this._vertex.z = this._shape[pt].z;
  67192. if (particle._model._vertexFunction) {
  67193. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  67194. }
  67195. this._vertex.x *= this._copy.scaling.x;
  67196. this._vertex.y *= this._copy.scaling.y;
  67197. this._vertex.z *= this._copy.scaling.z;
  67198. this._vertex.x -= this._scaledPivot.x;
  67199. this._vertex.y -= this._scaledPivot.y;
  67200. this._vertex.z -= this._scaledPivot.z;
  67201. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  67202. this._rotated.addInPlace(this._pivotBackTranslation);
  67203. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  67204. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  67205. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  67206. }
  67207. particle.position.x = 0.0;
  67208. particle.position.y = 0.0;
  67209. particle.position.z = 0.0;
  67210. particle.rotation.x = 0.0;
  67211. particle.rotation.y = 0.0;
  67212. particle.rotation.z = 0.0;
  67213. particle.rotationQuaternion = null;
  67214. particle.scaling.x = 1.0;
  67215. particle.scaling.y = 1.0;
  67216. particle.scaling.z = 1.0;
  67217. particle.uvs.x = 0.0;
  67218. particle.uvs.y = 0.0;
  67219. particle.uvs.z = 1.0;
  67220. particle.uvs.w = 1.0;
  67221. particle.pivot.x = 0.0;
  67222. particle.pivot.y = 0.0;
  67223. particle.pivot.z = 0.0;
  67224. particle.translateFromPivot = false;
  67225. particle.parentId = null;
  67226. };
  67227. /**
  67228. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  67229. * @returns the SPS.
  67230. */
  67231. SolidParticleSystem.prototype.rebuildMesh = function () {
  67232. for (var p = 0; p < this.particles.length; p++) {
  67233. this._rebuildParticle(this.particles[p]);
  67234. }
  67235. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67236. return this;
  67237. };
  67238. /**
  67239. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  67240. * This method calls `updateParticle()` for each particle of the SPS.
  67241. * For an animated SPS, it is usually called within the render loop.
  67242. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  67243. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  67244. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  67245. * @returns the SPS.
  67246. */
  67247. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  67248. if (start === void 0) { start = 0; }
  67249. if (end === void 0) { end = this.nbParticles - 1; }
  67250. if (update === void 0) { update = true; }
  67251. if (!this._updatable) {
  67252. return this;
  67253. }
  67254. // custom beforeUpdate
  67255. this.beforeUpdateParticles(start, end, update);
  67256. this._cam_axisX.x = 1.0;
  67257. this._cam_axisX.y = 0.0;
  67258. this._cam_axisX.z = 0.0;
  67259. this._cam_axisY.x = 0.0;
  67260. this._cam_axisY.y = 1.0;
  67261. this._cam_axisY.z = 0.0;
  67262. this._cam_axisZ.x = 0.0;
  67263. this._cam_axisZ.y = 0.0;
  67264. this._cam_axisZ.z = 1.0;
  67265. // cases when the World Matrix is to be computed first
  67266. if (this.billboard || this._depthSort) {
  67267. this.mesh.computeWorldMatrix(true);
  67268. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  67269. }
  67270. // if the particles will always face the camera
  67271. if (this.billboard) {
  67272. // compute the camera position and un-rotate it by the current mesh rotation
  67273. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  67274. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  67275. this._cam_axisZ.normalize();
  67276. // same for camera up vector extracted from the cam view matrix
  67277. var view = this._camera.getViewMatrix(true);
  67278. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  67279. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  67280. this._cam_axisY.normalize();
  67281. this._cam_axisX.normalize();
  67282. }
  67283. // if depthSort, compute the camera global position in the mesh local system
  67284. if (this._depthSort) {
  67285. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  67286. }
  67287. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  67288. var idx = 0; // current position index in the global array positions32
  67289. var index = 0; // position start index in the global array positions32 of the current particle
  67290. var colidx = 0; // current color index in the global array colors32
  67291. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  67292. var uvidx = 0; // current uv index in the global array uvs32
  67293. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  67294. var pt = 0; // current index in the particle model shape
  67295. if (this.mesh.isFacetDataEnabled) {
  67296. this._computeBoundingBox = true;
  67297. }
  67298. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  67299. if (this._computeBoundingBox) {
  67300. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  67301. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  67302. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  67303. }
  67304. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  67305. if (this.mesh._boundingInfo) {
  67306. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  67307. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  67308. }
  67309. }
  67310. }
  67311. // particle loop
  67312. index = this.particles[start]._pos;
  67313. var vpos = (index / 3) | 0;
  67314. colorIndex = vpos * 4;
  67315. uvIndex = vpos * 2;
  67316. for (var p = start; p <= end; p++) {
  67317. this._particle = this.particles[p];
  67318. this._shape = this._particle._model._shape;
  67319. this._shapeUV = this._particle._model._shapeUV;
  67320. // call to custom user function to update the particle properties
  67321. this.updateParticle(this._particle);
  67322. // camera-particle distance for depth sorting
  67323. if (this._depthSort && this._depthSortParticles) {
  67324. var dsp = this.depthSortedParticles[p];
  67325. dsp.ind = this._particle._ind;
  67326. dsp.indicesLength = this._particle._model._indicesLength;
  67327. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  67328. }
  67329. // skip the computations for inactive or already invisible particles
  67330. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  67331. // increment indexes for the next particle
  67332. pt = this._shape.length;
  67333. index += pt * 3;
  67334. colorIndex += pt * 4;
  67335. uvIndex += pt * 2;
  67336. continue;
  67337. }
  67338. if (this._particle.isVisible) {
  67339. this._particle._stillInvisible = false; // un-mark permanent invisibility
  67340. this._particleHasParent = (this._particle.parentId !== null);
  67341. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67342. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67343. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67344. // particle rotation matrix
  67345. if (this.billboard) {
  67346. this._particle.rotation.x = 0.0;
  67347. this._particle.rotation.y = 0.0;
  67348. }
  67349. if (this._computeParticleRotation || this.billboard) {
  67350. if (this._particle.rotationQuaternion) {
  67351. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  67352. }
  67353. else {
  67354. this._yaw = this._particle.rotation.y;
  67355. this._pitch = this._particle.rotation.x;
  67356. this._roll = this._particle.rotation.z;
  67357. this._quaternionRotationYPR();
  67358. }
  67359. this._quaternionToRotationMatrix();
  67360. }
  67361. if (this._particleHasParent) {
  67362. this._parent = this.particles[this._particle.parentId];
  67363. 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];
  67364. 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];
  67365. 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];
  67366. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  67367. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  67368. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  67369. if (this._computeParticleRotation || this.billboard) {
  67370. 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];
  67371. 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];
  67372. 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];
  67373. 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];
  67374. 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];
  67375. 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];
  67376. 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];
  67377. 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];
  67378. 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];
  67379. }
  67380. }
  67381. else {
  67382. this._particle._globalPosition.x = this._particle.position.x;
  67383. this._particle._globalPosition.y = this._particle.position.y;
  67384. this._particle._globalPosition.z = this._particle.position.z;
  67385. if (this._computeParticleRotation || this.billboard) {
  67386. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  67387. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  67388. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  67389. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  67390. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  67391. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  67392. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  67393. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  67394. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  67395. }
  67396. }
  67397. if (this._particle.translateFromPivot) {
  67398. this._pivotBackTranslation.x = 0.0;
  67399. this._pivotBackTranslation.y = 0.0;
  67400. this._pivotBackTranslation.z = 0.0;
  67401. }
  67402. else {
  67403. this._pivotBackTranslation.x = this._scaledPivot.x;
  67404. this._pivotBackTranslation.y = this._scaledPivot.y;
  67405. this._pivotBackTranslation.z = this._scaledPivot.z;
  67406. }
  67407. // particle vertex loop
  67408. for (pt = 0; pt < this._shape.length; pt++) {
  67409. idx = index + pt * 3;
  67410. colidx = colorIndex + pt * 4;
  67411. uvidx = uvIndex + pt * 2;
  67412. this._vertex.x = this._shape[pt].x;
  67413. this._vertex.y = this._shape[pt].y;
  67414. this._vertex.z = this._shape[pt].z;
  67415. if (this._computeParticleVertex) {
  67416. this.updateParticleVertex(this._particle, this._vertex, pt);
  67417. }
  67418. // positions
  67419. this._vertex.x *= this._particle.scaling.x;
  67420. this._vertex.y *= this._particle.scaling.y;
  67421. this._vertex.z *= this._particle.scaling.z;
  67422. this._vertex.x -= this._scaledPivot.x;
  67423. this._vertex.y -= this._scaledPivot.y;
  67424. this._vertex.z -= this._scaledPivot.z;
  67425. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67426. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67427. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67428. this._rotated.x += this._pivotBackTranslation.x;
  67429. this._rotated.y += this._pivotBackTranslation.y;
  67430. this._rotated.z += this._pivotBackTranslation.z;
  67431. 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;
  67432. 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;
  67433. 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;
  67434. if (this._computeBoundingBox) {
  67435. if (this._positions32[idx] < this._minimum.x) {
  67436. this._minimum.x = this._positions32[idx];
  67437. }
  67438. if (this._positions32[idx] > this._maximum.x) {
  67439. this._maximum.x = this._positions32[idx];
  67440. }
  67441. if (this._positions32[idx + 1] < this._minimum.y) {
  67442. this._minimum.y = this._positions32[idx + 1];
  67443. }
  67444. if (this._positions32[idx + 1] > this._maximum.y) {
  67445. this._maximum.y = this._positions32[idx + 1];
  67446. }
  67447. if (this._positions32[idx + 2] < this._minimum.z) {
  67448. this._minimum.z = this._positions32[idx + 2];
  67449. }
  67450. if (this._positions32[idx + 2] > this._maximum.z) {
  67451. this._maximum.z = this._positions32[idx + 2];
  67452. }
  67453. }
  67454. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  67455. if (!this._computeParticleVertex) {
  67456. this._normal.x = this._fixedNormal32[idx];
  67457. this._normal.y = this._fixedNormal32[idx + 1];
  67458. this._normal.z = this._fixedNormal32[idx + 2];
  67459. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  67460. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  67461. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  67462. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67463. 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;
  67464. 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;
  67465. }
  67466. if (this._computeParticleColor && this._particle.color) {
  67467. this._colors32[colidx] = this._particle.color.r;
  67468. this._colors32[colidx + 1] = this._particle.color.g;
  67469. this._colors32[colidx + 2] = this._particle.color.b;
  67470. this._colors32[colidx + 3] = this._particle.color.a;
  67471. }
  67472. if (this._computeParticleTexture) {
  67473. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67474. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67475. }
  67476. }
  67477. }
  67478. // particle just set invisible : scaled to zero and positioned at the origin
  67479. else {
  67480. this._particle._stillInvisible = true; // mark the particle as invisible
  67481. for (pt = 0; pt < this._shape.length; pt++) {
  67482. idx = index + pt * 3;
  67483. colidx = colorIndex + pt * 4;
  67484. uvidx = uvIndex + pt * 2;
  67485. this._positions32[idx] = 0.0;
  67486. this._positions32[idx + 1] = 0.0;
  67487. this._positions32[idx + 2] = 0.0;
  67488. this._normals32[idx] = 0.0;
  67489. this._normals32[idx + 1] = 0.0;
  67490. this._normals32[idx + 2] = 0.0;
  67491. if (this._computeParticleColor && this._particle.color) {
  67492. this._colors32[colidx] = this._particle.color.r;
  67493. this._colors32[colidx + 1] = this._particle.color.g;
  67494. this._colors32[colidx + 2] = this._particle.color.b;
  67495. this._colors32[colidx + 3] = this._particle.color.a;
  67496. }
  67497. if (this._computeParticleTexture) {
  67498. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67499. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67500. }
  67501. }
  67502. }
  67503. // if the particle intersections must be computed : update the bbInfo
  67504. if (this._particlesIntersect) {
  67505. var bInfo = this._particle._boundingInfo;
  67506. var bBox = bInfo.boundingBox;
  67507. var bSphere = bInfo.boundingSphere;
  67508. if (!this._bSphereOnly) {
  67509. // place, scale and rotate the particle bbox within the SPS local system, then update it
  67510. for (var b = 0; b < bBox.vectors.length; b++) {
  67511. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  67512. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  67513. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  67514. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67515. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67516. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67517. 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;
  67518. 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;
  67519. 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;
  67520. }
  67521. bBox._update(this.mesh._worldMatrix);
  67522. }
  67523. // place and scale the particle bouding sphere in the SPS local system, then update it
  67524. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  67525. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  67526. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  67527. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  67528. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  67529. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  67530. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  67531. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  67532. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  67533. 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));
  67534. bSphere._update(this.mesh._worldMatrix);
  67535. }
  67536. // increment indexes for the next particle
  67537. index = idx + 3;
  67538. colorIndex = colidx + 4;
  67539. uvIndex = uvidx + 2;
  67540. }
  67541. // if the VBO must be updated
  67542. if (update) {
  67543. if (this._computeParticleColor) {
  67544. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  67545. }
  67546. if (this._computeParticleTexture) {
  67547. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  67548. }
  67549. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67550. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  67551. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  67552. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  67553. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  67554. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  67555. for (var i = 0; i < this._normals32.length; i++) {
  67556. this._fixedNormal32[i] = this._normals32[i];
  67557. }
  67558. }
  67559. if (!this.mesh.areNormalsFrozen) {
  67560. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  67561. }
  67562. }
  67563. if (this._depthSort && this._depthSortParticles) {
  67564. this.depthSortedParticles.sort(this._depthSortFunction);
  67565. var dspl = this.depthSortedParticles.length;
  67566. var sorted = 0;
  67567. var lind = 0;
  67568. var sind = 0;
  67569. var sid = 0;
  67570. for (sorted = 0; sorted < dspl; sorted++) {
  67571. lind = this.depthSortedParticles[sorted].indicesLength;
  67572. sind = this.depthSortedParticles[sorted].ind;
  67573. for (var i = 0; i < lind; i++) {
  67574. this._indices32[sid] = this._indices[sind + i];
  67575. sid++;
  67576. }
  67577. }
  67578. this.mesh.updateIndices(this._indices32);
  67579. }
  67580. }
  67581. if (this._computeBoundingBox) {
  67582. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  67583. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  67584. }
  67585. this.afterUpdateParticles(start, end, update);
  67586. return this;
  67587. };
  67588. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  67589. this._halfroll = this._roll * 0.5;
  67590. this._halfpitch = this._pitch * 0.5;
  67591. this._halfyaw = this._yaw * 0.5;
  67592. this._sinRoll = Math.sin(this._halfroll);
  67593. this._cosRoll = Math.cos(this._halfroll);
  67594. this._sinPitch = Math.sin(this._halfpitch);
  67595. this._cosPitch = Math.cos(this._halfpitch);
  67596. this._sinYaw = Math.sin(this._halfyaw);
  67597. this._cosYaw = Math.cos(this._halfyaw);
  67598. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  67599. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  67600. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  67601. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  67602. };
  67603. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  67604. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  67605. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  67606. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  67607. this._rotMatrix.m[3] = 0;
  67608. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  67609. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  67610. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  67611. this._rotMatrix.m[7] = 0;
  67612. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  67613. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  67614. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  67615. this._rotMatrix.m[11] = 0;
  67616. this._rotMatrix.m[12] = 0;
  67617. this._rotMatrix.m[13] = 0;
  67618. this._rotMatrix.m[14] = 0;
  67619. this._rotMatrix.m[15] = 1.0;
  67620. };
  67621. /**
  67622. * Disposes the SPS.
  67623. */
  67624. SolidParticleSystem.prototype.dispose = function () {
  67625. this.mesh.dispose();
  67626. this.vars = null;
  67627. // drop references to internal big arrays for the GC
  67628. this._positions = null;
  67629. this._indices = null;
  67630. this._normals = null;
  67631. this._uvs = null;
  67632. this._colors = null;
  67633. this._indices32 = null;
  67634. this._positions32 = null;
  67635. this._normals32 = null;
  67636. this._fixedNormal32 = null;
  67637. this._uvs32 = null;
  67638. this._colors32 = null;
  67639. this.pickedParticles = null;
  67640. };
  67641. /**
  67642. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  67643. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67644. * @returns the SPS.
  67645. */
  67646. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  67647. if (!this._isVisibilityBoxLocked) {
  67648. this.mesh.refreshBoundingInfo();
  67649. }
  67650. return this;
  67651. };
  67652. /**
  67653. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  67654. * @param size the size (float) of the visibility box
  67655. * note : this doesn't lock the SPS mesh bounding box.
  67656. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67657. */
  67658. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  67659. var vis = size / 2;
  67660. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  67661. };
  67662. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  67663. /**
  67664. * Gets whether the SPS as always visible or not
  67665. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67666. */
  67667. get: function () {
  67668. return this._alwaysVisible;
  67669. },
  67670. /**
  67671. * Sets the SPS as always visible or not
  67672. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67673. */
  67674. set: function (val) {
  67675. this._alwaysVisible = val;
  67676. this.mesh.alwaysSelectAsActiveMesh = val;
  67677. },
  67678. enumerable: true,
  67679. configurable: true
  67680. });
  67681. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  67682. /**
  67683. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67684. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67685. */
  67686. get: function () {
  67687. return this._isVisibilityBoxLocked;
  67688. },
  67689. /**
  67690. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67691. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67692. */
  67693. set: function (val) {
  67694. this._isVisibilityBoxLocked = val;
  67695. var boundingInfo = this.mesh.getBoundingInfo();
  67696. boundingInfo.isLocked = val;
  67697. },
  67698. enumerable: true,
  67699. configurable: true
  67700. });
  67701. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  67702. /**
  67703. * Gets if `setParticles()` computes the particle rotations or not.
  67704. * Default value : true. The SPS is faster when it's set to false.
  67705. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67706. */
  67707. get: function () {
  67708. return this._computeParticleRotation;
  67709. },
  67710. /**
  67711. * Tells to `setParticles()` to compute the particle rotations or not.
  67712. * Default value : true. The SPS is faster when it's set to false.
  67713. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67714. */
  67715. set: function (val) {
  67716. this._computeParticleRotation = val;
  67717. },
  67718. enumerable: true,
  67719. configurable: true
  67720. });
  67721. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  67722. /**
  67723. * Gets if `setParticles()` computes the particle colors or not.
  67724. * Default value : true. The SPS is faster when it's set to false.
  67725. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67726. */
  67727. get: function () {
  67728. return this._computeParticleColor;
  67729. },
  67730. /**
  67731. * Tells to `setParticles()` to compute the particle colors or not.
  67732. * Default value : true. The SPS is faster when it's set to false.
  67733. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67734. */
  67735. set: function (val) {
  67736. this._computeParticleColor = val;
  67737. },
  67738. enumerable: true,
  67739. configurable: true
  67740. });
  67741. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  67742. /**
  67743. * Gets if `setParticles()` computes the particle textures or not.
  67744. * Default value : true. The SPS is faster when it's set to false.
  67745. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  67746. */
  67747. get: function () {
  67748. return this._computeParticleTexture;
  67749. },
  67750. set: function (val) {
  67751. this._computeParticleTexture = val;
  67752. },
  67753. enumerable: true,
  67754. configurable: true
  67755. });
  67756. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  67757. /**
  67758. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  67759. * Default value : false. The SPS is faster when it's set to false.
  67760. * Note : the particle custom vertex positions aren't stored values.
  67761. */
  67762. get: function () {
  67763. return this._computeParticleVertex;
  67764. },
  67765. /**
  67766. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  67767. * Default value : false. The SPS is faster when it's set to false.
  67768. * Note : the particle custom vertex positions aren't stored values.
  67769. */
  67770. set: function (val) {
  67771. this._computeParticleVertex = val;
  67772. },
  67773. enumerable: true,
  67774. configurable: true
  67775. });
  67776. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  67777. /**
  67778. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  67779. */
  67780. get: function () {
  67781. return this._computeBoundingBox;
  67782. },
  67783. /**
  67784. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  67785. */
  67786. set: function (val) {
  67787. this._computeBoundingBox = val;
  67788. },
  67789. enumerable: true,
  67790. configurable: true
  67791. });
  67792. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  67793. /**
  67794. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  67795. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67796. * Default : `true`
  67797. */
  67798. get: function () {
  67799. return this._depthSortParticles;
  67800. },
  67801. /**
  67802. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  67803. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67804. * Default : `true`
  67805. */
  67806. set: function (val) {
  67807. this._depthSortParticles = val;
  67808. },
  67809. enumerable: true,
  67810. configurable: true
  67811. });
  67812. // =======================================================================
  67813. // Particle behavior logic
  67814. // these following methods may be overwritten by the user to fit his needs
  67815. /**
  67816. * This function does nothing. It may be overwritten to set all the particle first values.
  67817. * The SPS doesn't call this function, you may have to call it by your own.
  67818. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67819. */
  67820. SolidParticleSystem.prototype.initParticles = function () {
  67821. };
  67822. /**
  67823. * This function does nothing. It may be overwritten to recycle a particle.
  67824. * The SPS doesn't call this function, you may have to call it by your own.
  67825. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67826. * @param particle The particle to recycle
  67827. * @returns the recycled particle
  67828. */
  67829. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  67830. return particle;
  67831. };
  67832. /**
  67833. * Updates a particle : this function should be overwritten by the user.
  67834. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  67835. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67836. * @example : just set a particle position or velocity and recycle conditions
  67837. * @param particle The particle to update
  67838. * @returns the updated particle
  67839. */
  67840. SolidParticleSystem.prototype.updateParticle = function (particle) {
  67841. return particle;
  67842. };
  67843. /**
  67844. * Updates a vertex of a particle : it can be overwritten by the user.
  67845. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  67846. * @param particle the current particle
  67847. * @param vertex the current index of the current particle
  67848. * @param pt the index of the current vertex in the particle shape
  67849. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  67850. * @example : just set a vertex particle position
  67851. * @returns the updated vertex
  67852. */
  67853. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  67854. return vertex;
  67855. };
  67856. /**
  67857. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  67858. * This does nothing and may be overwritten by the user.
  67859. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67860. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67861. * @param update the boolean update value actually passed to setParticles()
  67862. */
  67863. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  67864. };
  67865. /**
  67866. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  67867. * This will be passed three parameters.
  67868. * This does nothing and may be overwritten by the user.
  67869. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67870. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67871. * @param update the boolean update value actually passed to setParticles()
  67872. */
  67873. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  67874. };
  67875. return SolidParticleSystem;
  67876. }());
  67877. BABYLON.SolidParticleSystem = SolidParticleSystem;
  67878. })(BABYLON || (BABYLON = {}));
  67879. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  67880. var BABYLON;
  67881. (function (BABYLON) {
  67882. /**
  67883. * Class containing static functions to help procedurally build meshes
  67884. */
  67885. var MeshBuilder = /** @class */ (function () {
  67886. function MeshBuilder() {
  67887. }
  67888. MeshBuilder.updateSideOrientation = function (orientation) {
  67889. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  67890. return BABYLON.Mesh.DOUBLESIDE;
  67891. }
  67892. if (orientation === undefined || orientation === null) {
  67893. return BABYLON.Mesh.FRONTSIDE;
  67894. }
  67895. return orientation;
  67896. };
  67897. /**
  67898. * Creates a box mesh
  67899. * * The parameter `size` sets the size (float) of each box side (default 1)
  67900. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  67901. * * 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)
  67902. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67903. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67904. * * 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
  67905. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67906. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  67907. * @param name defines the name of the mesh
  67908. * @param options defines the options used to create the mesh
  67909. * @param scene defines the hosting scene
  67910. * @returns the box mesh
  67911. */
  67912. MeshBuilder.CreateBox = function (name, options, scene) {
  67913. if (scene === void 0) { scene = null; }
  67914. var box = new BABYLON.Mesh(name, scene);
  67915. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67916. box._originalBuilderSideOrientation = options.sideOrientation;
  67917. var vertexData = BABYLON.VertexData.CreateBox(options);
  67918. vertexData.applyToMesh(box, options.updatable);
  67919. return box;
  67920. };
  67921. /**
  67922. * Creates a sphere mesh
  67923. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  67924. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`)
  67925. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  67926. * * 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
  67927. * * 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)
  67928. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67929. * * 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
  67930. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67931. * @param name defines the name of the mesh
  67932. * @param options defines the options used to create the mesh
  67933. * @param scene defines the hosting scene
  67934. * @returns the sphere mesh
  67935. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  67936. */
  67937. MeshBuilder.CreateSphere = function (name, options, scene) {
  67938. var sphere = new BABYLON.Mesh(name, scene);
  67939. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67940. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67941. var vertexData = BABYLON.VertexData.CreateSphere(options);
  67942. vertexData.applyToMesh(sphere, options.updatable);
  67943. return sphere;
  67944. };
  67945. /**
  67946. * Creates a plane polygonal mesh. By default, this is a disc
  67947. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  67948. * * 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
  67949. * * 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
  67950. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67951. * * 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
  67952. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67953. * @param name defines the name of the mesh
  67954. * @param options defines the options used to create the mesh
  67955. * @param scene defines the hosting scene
  67956. * @returns the plane polygonal mesh
  67957. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  67958. */
  67959. MeshBuilder.CreateDisc = function (name, options, scene) {
  67960. if (scene === void 0) { scene = null; }
  67961. var disc = new BABYLON.Mesh(name, scene);
  67962. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67963. disc._originalBuilderSideOrientation = options.sideOrientation;
  67964. var vertexData = BABYLON.VertexData.CreateDisc(options);
  67965. vertexData.applyToMesh(disc, options.updatable);
  67966. return disc;
  67967. };
  67968. /**
  67969. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  67970. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  67971. * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`)
  67972. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  67973. * * 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
  67974. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67975. * * 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
  67976. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67977. * @param name defines the name of the mesh
  67978. * @param options defines the options used to create the mesh
  67979. * @param scene defines the hosting scene
  67980. * @returns the icosahedron mesh
  67981. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67982. */
  67983. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  67984. var sphere = new BABYLON.Mesh(name, scene);
  67985. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67986. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67987. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  67988. vertexData.applyToMesh(sphere, options.updatable);
  67989. return sphere;
  67990. };
  67991. /**
  67992. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67993. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  67994. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  67995. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  67996. * * 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
  67997. * * 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
  67998. * * 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
  67999. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68000. * * 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
  68001. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68002. * * 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
  68003. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  68004. * * 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
  68005. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  68006. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68007. * @param name defines the name of the mesh
  68008. * @param options defines the options used to create the mesh
  68009. * @param scene defines the hosting scene
  68010. * @returns the ribbon mesh
  68011. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  68012. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68013. */
  68014. MeshBuilder.CreateRibbon = function (name, options, scene) {
  68015. if (scene === void 0) { scene = null; }
  68016. var pathArray = options.pathArray;
  68017. var closeArray = options.closeArray;
  68018. var closePath = options.closePath;
  68019. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68020. var instance = options.instance;
  68021. var updatable = options.updatable;
  68022. if (instance) { // existing ribbon instance update
  68023. // positionFunction : ribbon case
  68024. // only pathArray and sideOrientation parameters are taken into account for positions update
  68025. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  68026. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  68027. var positionFunction = function (positions) {
  68028. var minlg = pathArray[0].length;
  68029. var mesh = instance;
  68030. var i = 0;
  68031. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  68032. for (var si = 1; si <= ns; si++) {
  68033. for (var p = 0; p < pathArray.length; p++) {
  68034. var path = pathArray[p];
  68035. var l = path.length;
  68036. minlg = (minlg < l) ? minlg : l;
  68037. var j = 0;
  68038. while (j < minlg) {
  68039. positions[i] = path[j].x;
  68040. positions[i + 1] = path[j].y;
  68041. positions[i + 2] = path[j].z;
  68042. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  68043. BABYLON.Tmp.Vector3[0].x = path[j].x;
  68044. }
  68045. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  68046. BABYLON.Tmp.Vector3[1].x = path[j].x;
  68047. }
  68048. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  68049. BABYLON.Tmp.Vector3[0].y = path[j].y;
  68050. }
  68051. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  68052. BABYLON.Tmp.Vector3[1].y = path[j].y;
  68053. }
  68054. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  68055. BABYLON.Tmp.Vector3[0].z = path[j].z;
  68056. }
  68057. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  68058. BABYLON.Tmp.Vector3[1].z = path[j].z;
  68059. }
  68060. j++;
  68061. i += 3;
  68062. }
  68063. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  68064. positions[i] = path[0].x;
  68065. positions[i + 1] = path[0].y;
  68066. positions[i + 2] = path[0].z;
  68067. i += 3;
  68068. }
  68069. }
  68070. }
  68071. };
  68072. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68073. positionFunction(positions);
  68074. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  68075. instance._boundingInfo.update(instance._worldMatrix);
  68076. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68077. if (options.colors) {
  68078. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68079. for (var c = 0; c < options.colors.length; c++) {
  68080. colors[c * 4] = options.colors[c].r;
  68081. colors[c * 4 + 1] = options.colors[c].g;
  68082. colors[c * 4 + 2] = options.colors[c].b;
  68083. colors[c * 4 + 3] = options.colors[c].a;
  68084. }
  68085. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  68086. }
  68087. if (options.uvs) {
  68088. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68089. for (var i = 0; i < options.uvs.length; i++) {
  68090. uvs[i * 2] = options.uvs[i].x;
  68091. uvs[i * 2 + 1] = options.uvs[i].y;
  68092. }
  68093. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  68094. }
  68095. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  68096. var indices = instance.getIndices();
  68097. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68098. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  68099. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  68100. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  68101. var indexFirst = 0;
  68102. var indexLast = 0;
  68103. for (var p = 0; p < pathArray.length; p++) {
  68104. indexFirst = instance._creationDataStorage.idx[p] * 3;
  68105. if (p + 1 < pathArray.length) {
  68106. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  68107. }
  68108. else {
  68109. indexLast = normals.length - 3;
  68110. }
  68111. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  68112. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  68113. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  68114. normals[indexLast] = normals[indexFirst];
  68115. normals[indexLast + 1] = normals[indexFirst + 1];
  68116. normals[indexLast + 2] = normals[indexFirst + 2];
  68117. }
  68118. }
  68119. if (!(instance.areNormalsFrozen)) {
  68120. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  68121. }
  68122. }
  68123. return instance;
  68124. }
  68125. else { // new ribbon creation
  68126. var ribbon = new BABYLON.Mesh(name, scene);
  68127. ribbon._originalBuilderSideOrientation = sideOrientation;
  68128. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  68129. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  68130. if (closePath) {
  68131. ribbon._creationDataStorage.idx = vertexData._idx;
  68132. }
  68133. ribbon._creationDataStorage.closePath = closePath;
  68134. ribbon._creationDataStorage.closeArray = closeArray;
  68135. vertexData.applyToMesh(ribbon, updatable);
  68136. return ribbon;
  68137. }
  68138. };
  68139. /**
  68140. * Creates a cylinder or a cone mesh
  68141. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  68142. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  68143. * * 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.
  68144. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  68145. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  68146. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  68147. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  68148. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  68149. * * 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).
  68150. * * 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
  68151. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  68152. * * 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
  68153. * * 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.
  68154. * * If `enclose` is false, a ring surface is one element.
  68155. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  68156. * * 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
  68157. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68158. * * 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
  68159. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68160. * @param name defines the name of the mesh
  68161. * @param options defines the options used to create the mesh
  68162. * @param scene defines the hosting scene
  68163. * @returns the cylinder mesh
  68164. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  68165. */
  68166. MeshBuilder.CreateCylinder = function (name, options, scene) {
  68167. var cylinder = new BABYLON.Mesh(name, scene);
  68168. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68169. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  68170. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  68171. vertexData.applyToMesh(cylinder, options.updatable);
  68172. return cylinder;
  68173. };
  68174. /**
  68175. * Creates a torus mesh
  68176. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  68177. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  68178. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  68179. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68180. * * 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
  68181. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68182. * @param name defines the name of the mesh
  68183. * @param options defines the options used to create the mesh
  68184. * @param scene defines the hosting scene
  68185. * @returns the torus mesh
  68186. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  68187. */
  68188. MeshBuilder.CreateTorus = function (name, options, scene) {
  68189. var torus = new BABYLON.Mesh(name, scene);
  68190. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68191. torus._originalBuilderSideOrientation = options.sideOrientation;
  68192. var vertexData = BABYLON.VertexData.CreateTorus(options);
  68193. vertexData.applyToMesh(torus, options.updatable);
  68194. return torus;
  68195. };
  68196. /**
  68197. * Creates a torus knot mesh
  68198. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  68199. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  68200. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  68201. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  68202. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68203. * * 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
  68204. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68205. * @param name defines the name of the mesh
  68206. * @param options defines the options used to create the mesh
  68207. * @param scene defines the hosting scene
  68208. * @returns the torus knot mesh
  68209. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  68210. */
  68211. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  68212. var torusKnot = new BABYLON.Mesh(name, scene);
  68213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68214. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  68215. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  68216. vertexData.applyToMesh(torusKnot, options.updatable);
  68217. return torusKnot;
  68218. };
  68219. /**
  68220. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  68221. * * 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
  68222. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  68223. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  68224. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  68225. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  68226. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  68227. * * 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
  68228. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  68229. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68230. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  68231. * @param name defines the name of the new line system
  68232. * @param options defines the options used to create the line system
  68233. * @param scene defines the hosting scene
  68234. * @returns a new line system mesh
  68235. */
  68236. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  68237. var instance = options.instance;
  68238. var lines = options.lines;
  68239. var colors = options.colors;
  68240. if (instance) { // lines update
  68241. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68242. var vertexColor;
  68243. var lineColors;
  68244. if (colors) {
  68245. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68246. }
  68247. var i = 0;
  68248. var c = 0;
  68249. for (var l = 0; l < lines.length; l++) {
  68250. var points = lines[l];
  68251. for (var p = 0; p < points.length; p++) {
  68252. positions[i] = points[p].x;
  68253. positions[i + 1] = points[p].y;
  68254. positions[i + 2] = points[p].z;
  68255. if (colors && vertexColor) {
  68256. lineColors = colors[l];
  68257. vertexColor[c] = lineColors[p].r;
  68258. vertexColor[c + 1] = lineColors[p].g;
  68259. vertexColor[c + 2] = lineColors[p].b;
  68260. vertexColor[c + 3] = lineColors[p].a;
  68261. c += 4;
  68262. }
  68263. i += 3;
  68264. }
  68265. }
  68266. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68267. if (colors && vertexColor) {
  68268. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  68269. }
  68270. return instance;
  68271. }
  68272. // line system creation
  68273. var useVertexColor = (colors) ? true : false;
  68274. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  68275. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  68276. vertexData.applyToMesh(lineSystem, options.updatable);
  68277. return lineSystem;
  68278. };
  68279. /**
  68280. * Creates a line mesh
  68281. * 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
  68282. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68283. * * The parameter `points` is an array successive Vector3
  68284. * * 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
  68285. * * The optional parameter `colors` is an array of successive Color4, one per line point
  68286. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  68287. * * When updating an instance, remember that only point positions can change, not the number of points
  68288. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68289. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  68290. * @param name defines the name of the new line system
  68291. * @param options defines the options used to create the line system
  68292. * @param scene defines the hosting scene
  68293. * @returns a new line mesh
  68294. */
  68295. MeshBuilder.CreateLines = function (name, options, scene) {
  68296. if (scene === void 0) { scene = null; }
  68297. var colors = (options.colors) ? [options.colors] : null;
  68298. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  68299. return lines;
  68300. };
  68301. /**
  68302. * Creates a dashed line mesh
  68303. * * 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
  68304. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68305. * * The parameter `points` is an array successive Vector3
  68306. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  68307. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  68308. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  68309. * * 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
  68310. * * When updating an instance, remember that only point positions can change, not the number of points
  68311. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68312. * @param name defines the name of the mesh
  68313. * @param options defines the options used to create the mesh
  68314. * @param scene defines the hosting scene
  68315. * @returns the dashed line mesh
  68316. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  68317. */
  68318. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  68319. if (scene === void 0) { scene = null; }
  68320. var points = options.points;
  68321. var instance = options.instance;
  68322. var gapSize = options.gapSize || 1;
  68323. var dashSize = options.dashSize || 3;
  68324. if (instance) { // dashed lines update
  68325. var positionFunction = function (positions) {
  68326. var curvect = BABYLON.Vector3.Zero();
  68327. var nbSeg = positions.length / 6;
  68328. var lg = 0;
  68329. var nb = 0;
  68330. var shft = 0;
  68331. var dashshft = 0;
  68332. var curshft = 0;
  68333. var p = 0;
  68334. var i = 0;
  68335. var j = 0;
  68336. for (i = 0; i < points.length - 1; i++) {
  68337. points[i + 1].subtractToRef(points[i], curvect);
  68338. lg += curvect.length();
  68339. }
  68340. shft = lg / nbSeg;
  68341. var dashSize = instance._creationDataStorage.dashSize;
  68342. var gapSize = instance._creationDataStorage.gapSize;
  68343. dashshft = dashSize * shft / (dashSize + gapSize);
  68344. for (i = 0; i < points.length - 1; i++) {
  68345. points[i + 1].subtractToRef(points[i], curvect);
  68346. nb = Math.floor(curvect.length() / shft);
  68347. curvect.normalize();
  68348. j = 0;
  68349. while (j < nb && p < positions.length) {
  68350. curshft = shft * j;
  68351. positions[p] = points[i].x + curshft * curvect.x;
  68352. positions[p + 1] = points[i].y + curshft * curvect.y;
  68353. positions[p + 2] = points[i].z + curshft * curvect.z;
  68354. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  68355. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  68356. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  68357. p += 6;
  68358. j++;
  68359. }
  68360. }
  68361. while (p < positions.length) {
  68362. positions[p] = points[i].x;
  68363. positions[p + 1] = points[i].y;
  68364. positions[p + 2] = points[i].z;
  68365. p += 3;
  68366. }
  68367. };
  68368. instance.updateMeshPositions(positionFunction, false);
  68369. return instance;
  68370. }
  68371. // dashed lines creation
  68372. var dashedLines = new BABYLON.LinesMesh(name, scene);
  68373. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  68374. vertexData.applyToMesh(dashedLines, options.updatable);
  68375. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  68376. dashedLines._creationDataStorage.dashSize = dashSize;
  68377. dashedLines._creationDataStorage.gapSize = gapSize;
  68378. return dashedLines;
  68379. };
  68380. /**
  68381. * 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.
  68382. * * 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.
  68383. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68384. * * 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.
  68385. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  68386. * * 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
  68387. * * 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
  68388. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  68389. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68390. * * 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
  68391. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  68392. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68393. * @param name defines the name of the mesh
  68394. * @param options defines the options used to create the mesh
  68395. * @param scene defines the hosting scene
  68396. * @returns the extruded shape mesh
  68397. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68398. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68399. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68400. */
  68401. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  68402. if (scene === void 0) { scene = null; }
  68403. var path = options.path;
  68404. var shape = options.shape;
  68405. var scale = options.scale || 1;
  68406. var rotation = options.rotation || 0;
  68407. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68408. var updatable = options.updatable;
  68409. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68410. var instance = options.instance || null;
  68411. var invertUV = options.invertUV || false;
  68412. 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);
  68413. };
  68414. /**
  68415. * Creates an custom extruded shape mesh.
  68416. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  68417. * * 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.
  68418. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68419. * * 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
  68420. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  68421. * * 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
  68422. * * It must returns a float value that will be the scale value applied to the shape on each path point
  68423. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  68424. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  68425. * * 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
  68426. * * 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
  68427. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  68428. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68429. * * 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
  68430. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68431. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68432. * @param name defines the name of the mesh
  68433. * @param options defines the options used to create the mesh
  68434. * @param scene defines the hosting scene
  68435. * @returns the custom extruded shape mesh
  68436. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  68437. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68438. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68439. */
  68440. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  68441. var path = options.path;
  68442. var shape = options.shape;
  68443. var scaleFunction = options.scaleFunction || (function () { return 1; });
  68444. var rotationFunction = options.rotationFunction || (function () { return 0; });
  68445. var ribbonCloseArray = options.ribbonCloseArray || false;
  68446. var ribbonClosePath = options.ribbonClosePath || false;
  68447. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68448. var updatable = options.updatable;
  68449. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68450. var instance = options.instance;
  68451. var invertUV = options.invertUV || false;
  68452. 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);
  68453. };
  68454. /**
  68455. * Creates lathe mesh.
  68456. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  68457. * * 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
  68458. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  68459. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  68460. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  68461. * * 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
  68462. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  68463. * * 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
  68464. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68465. * * 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
  68466. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68467. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68468. * @param name defines the name of the mesh
  68469. * @param options defines the options used to create the mesh
  68470. * @param scene defines the hosting scene
  68471. * @returns the lathe mesh
  68472. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  68473. */
  68474. MeshBuilder.CreateLathe = function (name, options, scene) {
  68475. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  68476. var closed = (options.closed === undefined) ? true : options.closed;
  68477. var shape = options.shape;
  68478. var radius = options.radius || 1;
  68479. var tessellation = options.tessellation || 64;
  68480. var clip = options.clip || 0;
  68481. var updatable = options.updatable;
  68482. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68483. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68484. var pi2 = Math.PI * 2;
  68485. var paths = new Array();
  68486. var invertUV = options.invertUV || false;
  68487. var i = 0;
  68488. var p = 0;
  68489. var step = pi2 / tessellation * arc;
  68490. var rotated;
  68491. var path = new Array();
  68492. for (i = 0; i <= tessellation - clip; i++) {
  68493. var path = [];
  68494. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  68495. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  68496. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  68497. }
  68498. for (p = 0; p < shape.length; p++) {
  68499. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  68500. path.push(rotated);
  68501. }
  68502. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  68503. 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));
  68504. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  68505. }
  68506. paths.push(path);
  68507. }
  68508. // lathe ribbon
  68509. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68510. return lathe;
  68511. };
  68512. /**
  68513. * Creates a plane mesh
  68514. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  68515. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  68516. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  68517. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68518. * * 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
  68519. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68520. * @param name defines the name of the mesh
  68521. * @param options defines the options used to create the mesh
  68522. * @param scene defines the hosting scene
  68523. * @returns the plane mesh
  68524. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68525. */
  68526. MeshBuilder.CreatePlane = function (name, options, scene) {
  68527. var plane = new BABYLON.Mesh(name, scene);
  68528. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68529. plane._originalBuilderSideOrientation = options.sideOrientation;
  68530. var vertexData = BABYLON.VertexData.CreatePlane(options);
  68531. vertexData.applyToMesh(plane, options.updatable);
  68532. if (options.sourcePlane) {
  68533. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  68534. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  68535. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  68536. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  68537. plane.rotate(vectorProduct, product);
  68538. }
  68539. }
  68540. return plane;
  68541. };
  68542. /**
  68543. * Creates a ground mesh
  68544. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  68545. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  68546. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68547. * @param name defines the name of the mesh
  68548. * @param options defines the options used to create the mesh
  68549. * @param scene defines the hosting scene
  68550. * @returns the ground mesh
  68551. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68552. */
  68553. MeshBuilder.CreateGround = function (name, options, scene) {
  68554. var ground = new BABYLON.GroundMesh(name, scene);
  68555. ground._setReady(false);
  68556. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  68557. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  68558. ground._width = options.width || 1;
  68559. ground._height = options.height || 1;
  68560. ground._maxX = ground._width / 2;
  68561. ground._maxZ = ground._height / 2;
  68562. ground._minX = -ground._maxX;
  68563. ground._minZ = -ground._maxZ;
  68564. var vertexData = BABYLON.VertexData.CreateGround(options);
  68565. vertexData.applyToMesh(ground, options.updatable);
  68566. ground._setReady(true);
  68567. return ground;
  68568. };
  68569. /**
  68570. * Creates a tiled ground mesh
  68571. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  68572. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  68573. * * 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
  68574. * * 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
  68575. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68576. * @param name defines the name of the mesh
  68577. * @param options defines the options used to create the mesh
  68578. * @param scene defines the hosting scene
  68579. * @returns the tiled ground mesh
  68580. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  68581. */
  68582. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  68583. var tiledGround = new BABYLON.Mesh(name, scene);
  68584. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  68585. vertexData.applyToMesh(tiledGround, options.updatable);
  68586. return tiledGround;
  68587. };
  68588. /**
  68589. * Creates a ground mesh from a height map
  68590. * * The parameter `url` sets the URL of the height map image resource.
  68591. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  68592. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  68593. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  68594. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  68595. * * 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.
  68596. * * 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).
  68597. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  68598. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68599. * @param name defines the name of the mesh
  68600. * @param url defines the url to the height map
  68601. * @param options defines the options used to create the mesh
  68602. * @param scene defines the hosting scene
  68603. * @returns the ground mesh
  68604. * @see http://doc.babylonjs.com/babylon101/height_map
  68605. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  68606. */
  68607. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  68608. var width = options.width || 10.0;
  68609. var height = options.height || 10.0;
  68610. var subdivisions = options.subdivisions || 1 | 0;
  68611. var minHeight = options.minHeight || 0.0;
  68612. var maxHeight = options.maxHeight || 1.0;
  68613. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  68614. var alphaFilter = options.alphaFilter || 0.0;
  68615. var updatable = options.updatable;
  68616. var onReady = options.onReady;
  68617. var ground = new BABYLON.GroundMesh(name, scene);
  68618. ground._subdivisionsX = subdivisions;
  68619. ground._subdivisionsY = subdivisions;
  68620. ground._width = width;
  68621. ground._height = height;
  68622. ground._maxX = ground._width / 2.0;
  68623. ground._maxZ = ground._height / 2.0;
  68624. ground._minX = -ground._maxX;
  68625. ground._minZ = -ground._maxZ;
  68626. ground._setReady(false);
  68627. var onload = function (img) {
  68628. // Getting height map data
  68629. var canvas = document.createElement("canvas");
  68630. var context = canvas.getContext("2d");
  68631. if (!context) {
  68632. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  68633. }
  68634. if (scene.isDisposed) {
  68635. return;
  68636. }
  68637. var bufferWidth = img.width;
  68638. var bufferHeight = img.height;
  68639. canvas.width = bufferWidth;
  68640. canvas.height = bufferHeight;
  68641. context.drawImage(img, 0, 0);
  68642. // Create VertexData from map data
  68643. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  68644. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  68645. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  68646. width: width, height: height,
  68647. subdivisions: subdivisions,
  68648. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  68649. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  68650. alphaFilter: alphaFilter
  68651. });
  68652. vertexData.applyToMesh(ground, updatable);
  68653. //execute ready callback, if set
  68654. if (onReady) {
  68655. onReady(ground);
  68656. }
  68657. ground._setReady(true);
  68658. };
  68659. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  68660. return ground;
  68661. };
  68662. /**
  68663. * Creates a polygon mesh
  68664. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  68665. * * 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
  68666. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68667. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68668. * * 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)
  68669. * * Remember you can only change the shape positions, not their number when updating a polygon
  68670. * @param name defines the name of the mesh
  68671. * @param options defines the options used to create the mesh
  68672. * @param scene defines the hosting scene
  68673. * @returns the polygon mesh
  68674. */
  68675. MeshBuilder.CreatePolygon = function (name, options, scene) {
  68676. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68677. var shape = options.shape;
  68678. var holes = options.holes || [];
  68679. var depth = options.depth || 0;
  68680. var contours = [];
  68681. var hole = [];
  68682. for (var i = 0; i < shape.length; i++) {
  68683. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  68684. }
  68685. var epsilon = 0.00000001;
  68686. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  68687. contours.pop();
  68688. }
  68689. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  68690. for (var hNb = 0; hNb < holes.length; hNb++) {
  68691. hole = [];
  68692. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  68693. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  68694. }
  68695. polygonTriangulation.addHole(hole);
  68696. }
  68697. var polygon = polygonTriangulation.build(options.updatable, depth);
  68698. polygon._originalBuilderSideOrientation = options.sideOrientation;
  68699. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  68700. vertexData.applyToMesh(polygon, options.updatable);
  68701. return polygon;
  68702. };
  68703. /**
  68704. * Creates an extruded polygon mesh, with depth in the Y direction.
  68705. * * 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)
  68706. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68707. * @param name defines the name of the mesh
  68708. * @param options defines the options used to create the mesh
  68709. * @param scene defines the hosting scene
  68710. * @returns the polygon mesh
  68711. */
  68712. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  68713. return MeshBuilder.CreatePolygon(name, options, scene);
  68714. };
  68715. /**
  68716. * Creates a tube mesh.
  68717. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  68718. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  68719. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  68720. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  68721. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  68722. * * 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)
  68723. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  68724. * * 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
  68725. * * 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
  68726. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68727. * * 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
  68728. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68729. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68730. * @param name defines the name of the mesh
  68731. * @param options defines the options used to create the mesh
  68732. * @param scene defines the hosting scene
  68733. * @returns the tube mesh
  68734. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68735. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  68736. */
  68737. MeshBuilder.CreateTube = function (name, options, scene) {
  68738. var path = options.path;
  68739. var instance = options.instance;
  68740. var radius = 1.0;
  68741. if (options.radius !== undefined) {
  68742. radius = options.radius;
  68743. }
  68744. else if (instance) {
  68745. radius = instance._creationDataStorage.radius;
  68746. }
  68747. var tessellation = options.tessellation || 64 | 0;
  68748. var radiusFunction = options.radiusFunction || null;
  68749. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68750. var invertUV = options.invertUV || false;
  68751. var updatable = options.updatable;
  68752. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68753. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  68754. // tube geometry
  68755. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  68756. var tangents = path3D.getTangents();
  68757. var normals = path3D.getNormals();
  68758. var distances = path3D.getDistances();
  68759. var pi2 = Math.PI * 2;
  68760. var step = pi2 / tessellation * arc;
  68761. var returnRadius = function () { return radius; };
  68762. var radiusFunctionFinal = radiusFunction || returnRadius;
  68763. var circlePath;
  68764. var rad;
  68765. var normal;
  68766. var rotated;
  68767. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68768. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68769. for (var i = 0; i < path.length; i++) {
  68770. rad = radiusFunctionFinal(i, distances[i]); // current radius
  68771. circlePath = Array(); // current circle array
  68772. normal = normals[i]; // current normal
  68773. for (var t = 0; t < tessellation; t++) {
  68774. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  68775. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  68776. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  68777. rotated.scaleInPlace(rad).addInPlace(path[i]);
  68778. circlePath[t] = rotated;
  68779. }
  68780. circlePaths[index] = circlePath;
  68781. index++;
  68782. }
  68783. // cap
  68784. var capPath = function (nbPoints, pathIndex) {
  68785. var pointCap = Array();
  68786. for (var i = 0; i < nbPoints; i++) {
  68787. pointCap.push(path[pathIndex]);
  68788. }
  68789. return pointCap;
  68790. };
  68791. switch (cap) {
  68792. case BABYLON.Mesh.NO_CAP:
  68793. break;
  68794. case BABYLON.Mesh.CAP_START:
  68795. circlePaths[0] = capPath(tessellation, 0);
  68796. circlePaths[1] = circlePaths[2].slice(0);
  68797. break;
  68798. case BABYLON.Mesh.CAP_END:
  68799. circlePaths[index] = circlePaths[index - 1].slice(0);
  68800. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68801. break;
  68802. case BABYLON.Mesh.CAP_ALL:
  68803. circlePaths[0] = capPath(tessellation, 0);
  68804. circlePaths[1] = circlePaths[2].slice(0);
  68805. circlePaths[index] = circlePaths[index - 1].slice(0);
  68806. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68807. break;
  68808. default:
  68809. break;
  68810. }
  68811. return circlePaths;
  68812. };
  68813. var path3D;
  68814. var pathArray;
  68815. if (instance) { // tube update
  68816. var storage = instance._creationDataStorage;
  68817. var arc = options.arc || storage.arc;
  68818. path3D = storage.path3D.update(path);
  68819. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  68820. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  68821. // Update mode, no need to recreate the storage.
  68822. storage.path3D = path3D;
  68823. storage.pathArray = pathArray;
  68824. storage.arc = arc;
  68825. storage.radius = radius;
  68826. return instance;
  68827. }
  68828. // tube creation
  68829. path3D = new BABYLON.Path3D(path);
  68830. var newPathArray = new Array();
  68831. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68832. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  68833. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68834. tube._creationDataStorage.pathArray = pathArray;
  68835. tube._creationDataStorage.path3D = path3D;
  68836. tube._creationDataStorage.tessellation = tessellation;
  68837. tube._creationDataStorage.cap = cap;
  68838. tube._creationDataStorage.arc = options.arc;
  68839. tube._creationDataStorage.radius = radius;
  68840. return tube;
  68841. };
  68842. /**
  68843. * Creates a polyhedron mesh
  68844. * * 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
  68845. * * The parameter `size` (positive float, default 1) sets the polygon size
  68846. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  68847. * * 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`
  68848. * * 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
  68849. * * 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)`)
  68850. * * 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
  68851. * * 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
  68852. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68853. * * 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
  68854. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68855. * @param name defines the name of the mesh
  68856. * @param options defines the options used to create the mesh
  68857. * @param scene defines the hosting scene
  68858. * @returns the polyhedron mesh
  68859. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  68860. */
  68861. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  68862. var polyhedron = new BABYLON.Mesh(name, scene);
  68863. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68864. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  68865. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  68866. vertexData.applyToMesh(polyhedron, options.updatable);
  68867. return polyhedron;
  68868. };
  68869. /**
  68870. * Creates a decal mesh.
  68871. * 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
  68872. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  68873. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  68874. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  68875. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  68876. * @param name defines the name of the mesh
  68877. * @param sourceMesh defines the mesh where the decal must be applied
  68878. * @param options defines the options used to create the mesh
  68879. * @param scene defines the hosting scene
  68880. * @returns the decal mesh
  68881. * @see http://doc.babylonjs.com/how_to/decals
  68882. */
  68883. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  68884. var indices = sourceMesh.getIndices();
  68885. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68886. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68887. var position = options.position || BABYLON.Vector3.Zero();
  68888. var normal = options.normal || BABYLON.Vector3.Up();
  68889. var size = options.size || BABYLON.Vector3.One();
  68890. var angle = options.angle || 0;
  68891. // Getting correct rotation
  68892. if (!normal) {
  68893. var target = new BABYLON.Vector3(0, 0, 1);
  68894. var camera = sourceMesh.getScene().activeCamera;
  68895. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  68896. normal = camera.globalPosition.subtract(cameraWorldTarget);
  68897. }
  68898. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  68899. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  68900. var pitch = Math.atan2(normal.y, len);
  68901. // Matrix
  68902. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  68903. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  68904. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  68905. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  68906. var vertexData = new BABYLON.VertexData();
  68907. vertexData.indices = [];
  68908. vertexData.positions = [];
  68909. vertexData.normals = [];
  68910. vertexData.uvs = [];
  68911. var currentVertexDataIndex = 0;
  68912. var extractDecalVector3 = function (indexId) {
  68913. var result = new BABYLON.PositionNormalVertex();
  68914. if (!indices || !positions || !normals) {
  68915. return result;
  68916. }
  68917. var vertexId = indices[indexId];
  68918. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  68919. // Send vector to decal local world
  68920. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  68921. // Get normal
  68922. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  68923. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  68924. return result;
  68925. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  68926. var clip = function (vertices, axis) {
  68927. if (vertices.length === 0) {
  68928. return vertices;
  68929. }
  68930. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  68931. var clipVertices = function (v0, v1) {
  68932. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  68933. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  68934. };
  68935. var result = new Array();
  68936. for (var index = 0; index < vertices.length; index += 3) {
  68937. var v1Out;
  68938. var v2Out;
  68939. var v3Out;
  68940. var total = 0;
  68941. var nV1 = null;
  68942. var nV2 = null;
  68943. var nV3 = null;
  68944. var nV4 = null;
  68945. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  68946. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  68947. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  68948. v1Out = d1 > 0;
  68949. v2Out = d2 > 0;
  68950. v3Out = d3 > 0;
  68951. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  68952. switch (total) {
  68953. case 0:
  68954. result.push(vertices[index]);
  68955. result.push(vertices[index + 1]);
  68956. result.push(vertices[index + 2]);
  68957. break;
  68958. case 1:
  68959. if (v1Out) {
  68960. nV1 = vertices[index + 1];
  68961. nV2 = vertices[index + 2];
  68962. nV3 = clipVertices(vertices[index], nV1);
  68963. nV4 = clipVertices(vertices[index], nV2);
  68964. }
  68965. if (v2Out) {
  68966. nV1 = vertices[index];
  68967. nV2 = vertices[index + 2];
  68968. nV3 = clipVertices(vertices[index + 1], nV1);
  68969. nV4 = clipVertices(vertices[index + 1], nV2);
  68970. result.push(nV3);
  68971. result.push(nV2.clone());
  68972. result.push(nV1.clone());
  68973. result.push(nV2.clone());
  68974. result.push(nV3.clone());
  68975. result.push(nV4);
  68976. break;
  68977. }
  68978. if (v3Out) {
  68979. nV1 = vertices[index];
  68980. nV2 = vertices[index + 1];
  68981. nV3 = clipVertices(vertices[index + 2], nV1);
  68982. nV4 = clipVertices(vertices[index + 2], nV2);
  68983. }
  68984. if (nV1 && nV2 && nV3 && nV4) {
  68985. result.push(nV1.clone());
  68986. result.push(nV2.clone());
  68987. result.push(nV3);
  68988. result.push(nV4);
  68989. result.push(nV3.clone());
  68990. result.push(nV2.clone());
  68991. }
  68992. break;
  68993. case 2:
  68994. if (!v1Out) {
  68995. nV1 = vertices[index].clone();
  68996. nV2 = clipVertices(nV1, vertices[index + 1]);
  68997. nV3 = clipVertices(nV1, vertices[index + 2]);
  68998. result.push(nV1);
  68999. result.push(nV2);
  69000. result.push(nV3);
  69001. }
  69002. if (!v2Out) {
  69003. nV1 = vertices[index + 1].clone();
  69004. nV2 = clipVertices(nV1, vertices[index + 2]);
  69005. nV3 = clipVertices(nV1, vertices[index]);
  69006. result.push(nV1);
  69007. result.push(nV2);
  69008. result.push(nV3);
  69009. }
  69010. if (!v3Out) {
  69011. nV1 = vertices[index + 2].clone();
  69012. nV2 = clipVertices(nV1, vertices[index]);
  69013. nV3 = clipVertices(nV1, vertices[index + 1]);
  69014. result.push(nV1);
  69015. result.push(nV2);
  69016. result.push(nV3);
  69017. }
  69018. break;
  69019. case 3:
  69020. break;
  69021. }
  69022. }
  69023. return result;
  69024. };
  69025. for (var index = 0; index < indices.length; index += 3) {
  69026. var faceVertices = new Array();
  69027. faceVertices.push(extractDecalVector3(index));
  69028. faceVertices.push(extractDecalVector3(index + 1));
  69029. faceVertices.push(extractDecalVector3(index + 2));
  69030. // Clip
  69031. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  69032. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  69033. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  69034. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  69035. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  69036. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  69037. if (faceVertices.length === 0) {
  69038. continue;
  69039. }
  69040. // Add UVs and get back to world
  69041. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  69042. var vertex = faceVertices[vIndex];
  69043. //TODO check for Int32Array | Uint32Array | Uint16Array
  69044. vertexData.indices.push(currentVertexDataIndex);
  69045. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  69046. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  69047. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  69048. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  69049. currentVertexDataIndex++;
  69050. }
  69051. }
  69052. // Return mesh
  69053. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  69054. vertexData.applyToMesh(decal);
  69055. decal.position = position.clone();
  69056. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  69057. return decal;
  69058. };
  69059. // Privates
  69060. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  69061. // extrusion geometry
  69062. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  69063. var tangents = path3D.getTangents();
  69064. var normals = path3D.getNormals();
  69065. var binormals = path3D.getBinormals();
  69066. var distances = path3D.getDistances();
  69067. var angle = 0;
  69068. var returnScale = function () { return scale !== null ? scale : 1; };
  69069. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  69070. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  69071. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  69072. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69073. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69074. for (var i = 0; i < curve.length; i++) {
  69075. var shapePath = new Array();
  69076. var angleStep = rotate(i, distances[i]);
  69077. var scaleRatio = scl(i, distances[i]);
  69078. for (var p = 0; p < shape.length; p++) {
  69079. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  69080. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  69081. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  69082. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  69083. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  69084. shapePath[p] = rotated;
  69085. }
  69086. shapePaths[index] = shapePath;
  69087. angle += angleStep;
  69088. index++;
  69089. }
  69090. // cap
  69091. var capPath = function (shapePath) {
  69092. var pointCap = Array();
  69093. var barycenter = BABYLON.Vector3.Zero();
  69094. var i;
  69095. for (i = 0; i < shapePath.length; i++) {
  69096. barycenter.addInPlace(shapePath[i]);
  69097. }
  69098. barycenter.scaleInPlace(1.0 / shapePath.length);
  69099. for (i = 0; i < shapePath.length; i++) {
  69100. pointCap.push(barycenter);
  69101. }
  69102. return pointCap;
  69103. };
  69104. switch (cap) {
  69105. case BABYLON.Mesh.NO_CAP:
  69106. break;
  69107. case BABYLON.Mesh.CAP_START:
  69108. shapePaths[0] = capPath(shapePaths[2]);
  69109. shapePaths[1] = shapePaths[2];
  69110. break;
  69111. case BABYLON.Mesh.CAP_END:
  69112. shapePaths[index] = shapePaths[index - 1];
  69113. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  69114. break;
  69115. case BABYLON.Mesh.CAP_ALL:
  69116. shapePaths[0] = capPath(shapePaths[2]);
  69117. shapePaths[1] = shapePaths[2];
  69118. shapePaths[index] = shapePaths[index - 1];
  69119. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  69120. break;
  69121. default:
  69122. break;
  69123. }
  69124. return shapePaths;
  69125. };
  69126. var path3D;
  69127. var pathArray;
  69128. if (instance) { // instance update
  69129. var storage = instance._creationDataStorage;
  69130. path3D = storage.path3D.update(curve);
  69131. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  69132. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  69133. return instance;
  69134. }
  69135. // extruded shape creation
  69136. path3D = new BABYLON.Path3D(curve);
  69137. var newShapePaths = new Array();
  69138. cap = (cap < 0 || cap > 3) ? 0 : cap;
  69139. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  69140. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  69141. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  69142. extrudedGeneric._creationDataStorage.path3D = path3D;
  69143. extrudedGeneric._creationDataStorage.cap = cap;
  69144. return extrudedGeneric;
  69145. };
  69146. return MeshBuilder;
  69147. }());
  69148. BABYLON.MeshBuilder = MeshBuilder;
  69149. })(BABYLON || (BABYLON = {}));
  69150. //# sourceMappingURL=babylon.meshBuilder.js.map
  69151. var BABYLON;
  69152. (function (BABYLON) {
  69153. /**
  69154. * Draco compression (https://google.github.io/draco/)
  69155. *
  69156. * This class wraps the Draco module.
  69157. *
  69158. * **Encoder**
  69159. *
  69160. * The encoder is not currently implemented.
  69161. *
  69162. * **Decoder**
  69163. *
  69164. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  69165. *
  69166. * To update the configuration, use the following code:
  69167. * ```javascript
  69168. * BABYLON.DracoCompression.Configuration = {
  69169. * decoder: {
  69170. * wasmUrl: "<url to the WebAssembly library>",
  69171. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  69172. * fallbackUrl: "<url to the fallback JavaScript library>",
  69173. * }
  69174. * };
  69175. * ```
  69176. *
  69177. * 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.
  69178. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  69179. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  69180. *
  69181. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  69182. * ```javascript
  69183. * var dracoCompression = new BABYLON.DracoCompression();
  69184. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  69185. * [BABYLON.VertexBuffer.PositionKind]: 0
  69186. * });
  69187. * ```
  69188. *
  69189. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  69190. */
  69191. var DracoCompression = /** @class */ (function () {
  69192. /**
  69193. * Constructor
  69194. */
  69195. function DracoCompression() {
  69196. }
  69197. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  69198. /**
  69199. * Returns true if the decoder is available.
  69200. */
  69201. get: function () {
  69202. if (typeof DracoDecoderModule !== "undefined") {
  69203. return true;
  69204. }
  69205. var decoder = DracoCompression.Configuration.decoder;
  69206. if (decoder) {
  69207. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69208. return true;
  69209. }
  69210. if (decoder.fallbackUrl) {
  69211. return true;
  69212. }
  69213. }
  69214. return false;
  69215. },
  69216. enumerable: true,
  69217. configurable: true
  69218. });
  69219. /**
  69220. * Stop all async operations and release resources.
  69221. */
  69222. DracoCompression.prototype.dispose = function () {
  69223. };
  69224. /**
  69225. * Decode Draco compressed mesh data to vertex data.
  69226. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  69227. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  69228. * @returns A promise that resolves with the decoded vertex data
  69229. */
  69230. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  69231. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  69232. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  69233. var module = wrappedModule.module;
  69234. var vertexData = new BABYLON.VertexData();
  69235. var buffer = new module.DecoderBuffer();
  69236. buffer.Init(dataView, dataView.byteLength);
  69237. var decoder = new module.Decoder();
  69238. var geometry;
  69239. var status;
  69240. try {
  69241. var type = decoder.GetEncodedGeometryType(buffer);
  69242. switch (type) {
  69243. case module.TRIANGULAR_MESH:
  69244. geometry = new module.Mesh();
  69245. status = decoder.DecodeBufferToMesh(buffer, geometry);
  69246. break;
  69247. case module.POINT_CLOUD:
  69248. geometry = new module.PointCloud();
  69249. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  69250. break;
  69251. default:
  69252. throw new Error("Invalid geometry type " + type);
  69253. }
  69254. if (!status.ok() || !geometry.ptr) {
  69255. throw new Error(status.error_msg());
  69256. }
  69257. var numPoints = geometry.num_points();
  69258. if (type === module.TRIANGULAR_MESH) {
  69259. var numFaces = geometry.num_faces();
  69260. var faceIndices = new module.DracoInt32Array();
  69261. try {
  69262. var indices = new Uint32Array(numFaces * 3);
  69263. for (var i = 0; i < numFaces; i++) {
  69264. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  69265. var offset = i * 3;
  69266. indices[offset + 0] = faceIndices.GetValue(0);
  69267. indices[offset + 1] = faceIndices.GetValue(1);
  69268. indices[offset + 2] = faceIndices.GetValue(2);
  69269. }
  69270. vertexData.indices = indices;
  69271. }
  69272. finally {
  69273. module.destroy(faceIndices);
  69274. }
  69275. }
  69276. for (var kind in attributes) {
  69277. var uniqueId = attributes[kind];
  69278. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  69279. var dracoData = new module.DracoFloat32Array();
  69280. try {
  69281. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  69282. var babylonData = new Float32Array(numPoints * attribute.num_components());
  69283. for (var i = 0; i < babylonData.length; i++) {
  69284. babylonData[i] = dracoData.GetValue(i);
  69285. }
  69286. vertexData.set(babylonData, kind);
  69287. }
  69288. finally {
  69289. module.destroy(dracoData);
  69290. }
  69291. }
  69292. }
  69293. finally {
  69294. if (geometry) {
  69295. module.destroy(geometry);
  69296. }
  69297. module.destroy(decoder);
  69298. module.destroy(buffer);
  69299. }
  69300. return vertexData;
  69301. });
  69302. };
  69303. DracoCompression._GetDecoderModule = function () {
  69304. if (!DracoCompression._DecoderModulePromise) {
  69305. var promise = null;
  69306. var config_1 = {};
  69307. if (typeof DracoDecoderModule !== "undefined") {
  69308. promise = Promise.resolve();
  69309. }
  69310. else {
  69311. var decoder = DracoCompression.Configuration.decoder;
  69312. if (decoder) {
  69313. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69314. promise = Promise.all([
  69315. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  69316. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  69317. config_1.wasmBinary = data;
  69318. })
  69319. ]);
  69320. }
  69321. else if (decoder.fallbackUrl) {
  69322. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  69323. }
  69324. }
  69325. }
  69326. if (!promise) {
  69327. throw new Error("Draco decoder module is not available");
  69328. }
  69329. DracoCompression._DecoderModulePromise = promise.then(function () {
  69330. return new Promise(function (resolve) {
  69331. config_1.onModuleLoaded = function (decoderModule) {
  69332. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  69333. resolve({ module: decoderModule });
  69334. };
  69335. DracoDecoderModule(config_1);
  69336. });
  69337. });
  69338. }
  69339. return DracoCompression._DecoderModulePromise;
  69340. };
  69341. DracoCompression._LoadScriptAsync = function (url) {
  69342. return new Promise(function (resolve, reject) {
  69343. BABYLON.Tools.LoadScript(url, function () {
  69344. resolve();
  69345. }, function (message) {
  69346. reject(new Error(message));
  69347. });
  69348. });
  69349. };
  69350. DracoCompression._LoadFileAsync = function (url) {
  69351. return new Promise(function (resolve, reject) {
  69352. BABYLON.Tools.LoadFile(url, function (data) {
  69353. resolve(data);
  69354. }, undefined, undefined, true, function (request, exception) {
  69355. reject(exception);
  69356. });
  69357. });
  69358. };
  69359. /**
  69360. * The configuration. Defaults to the following urls:
  69361. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  69362. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  69363. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69364. */
  69365. DracoCompression.Configuration = {
  69366. decoder: {
  69367. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  69368. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  69369. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69370. }
  69371. };
  69372. return DracoCompression;
  69373. }());
  69374. BABYLON.DracoCompression = DracoCompression;
  69375. })(BABYLON || (BABYLON = {}));
  69376. //# sourceMappingURL=babylon.dracoCompression.js.map
  69377. var BABYLON;
  69378. (function (BABYLON) {
  69379. // Sets the default audio engine to Babylon JS.
  69380. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  69381. /**
  69382. * This represents the default audio engine used in babylon.
  69383. * It is responsible to play, synchronize and analyse sounds throughout the application.
  69384. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69385. */
  69386. var AudioEngine = /** @class */ (function () {
  69387. /**
  69388. * Instantiates a new audio engine.
  69389. *
  69390. * There should be only one per page as some browsers restrict the number
  69391. * of audio contexts you can create.
  69392. * @param hostElement defines the host element where to display the mute icon if necessary
  69393. */
  69394. function AudioEngine(hostElement) {
  69395. if (hostElement === void 0) { hostElement = null; }
  69396. var _this = this;
  69397. this._audioContext = null;
  69398. this._audioContextInitialized = false;
  69399. this._muteButton = null;
  69400. /**
  69401. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  69402. */
  69403. this.canUseWebAudio = false;
  69404. /**
  69405. * Defines if Babylon should emit a warning if WebAudio is not supported.
  69406. * @ignoreNaming
  69407. */
  69408. this.WarnedWebAudioUnsupported = false;
  69409. /**
  69410. * Gets whether or not mp3 are supported by your browser.
  69411. */
  69412. this.isMP3supported = false;
  69413. /**
  69414. * Gets whether or not ogg are supported by your browser.
  69415. */
  69416. this.isOGGsupported = false;
  69417. /**
  69418. * Gets whether audio has been unlocked on the device.
  69419. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  69420. * a user interaction has happened.
  69421. */
  69422. this.unlocked = true;
  69423. /**
  69424. * Defines if the audio engine relies on a custom unlocked button.
  69425. * In this case, the embedded button will not be displayed.
  69426. */
  69427. this.useCustomUnlockedButton = false;
  69428. /**
  69429. * Event raised when audio has been unlocked on the browser.
  69430. */
  69431. this.onAudioUnlockedObservable = new BABYLON.Observable();
  69432. /**
  69433. * Event raised when audio has been locked on the browser.
  69434. */
  69435. this.onAudioLockedObservable = new BABYLON.Observable();
  69436. this._tryToRun = false;
  69437. this._onResize = function () {
  69438. _this._moveButtonToTopLeft();
  69439. };
  69440. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  69441. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  69442. this.canUseWebAudio = true;
  69443. }
  69444. var audioElem = document.createElement('audio');
  69445. this._hostElement = hostElement;
  69446. try {
  69447. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  69448. this.isMP3supported = true;
  69449. }
  69450. }
  69451. catch (e) {
  69452. // protect error during capability check.
  69453. }
  69454. try {
  69455. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  69456. this.isOGGsupported = true;
  69457. }
  69458. }
  69459. catch (e) {
  69460. // protect error during capability check.
  69461. }
  69462. }
  69463. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  69464. /**
  69465. * Gets the current AudioContext if available.
  69466. */
  69467. get: function () {
  69468. if (!this._audioContextInitialized) {
  69469. this._initializeAudioContext();
  69470. }
  69471. else {
  69472. if (!this.unlocked && !this._muteButton) {
  69473. this._displayMuteButton();
  69474. }
  69475. }
  69476. return this._audioContext;
  69477. },
  69478. enumerable: true,
  69479. configurable: true
  69480. });
  69481. /**
  69482. * Flags the audio engine in Locked state.
  69483. * This happens due to new browser policies preventing audio to autoplay.
  69484. */
  69485. AudioEngine.prototype.lock = function () {
  69486. this._triggerSuspendedState();
  69487. };
  69488. /**
  69489. * Unlocks the audio engine once a user action has been done on the dom.
  69490. * This is helpful to resume play once browser policies have been satisfied.
  69491. */
  69492. AudioEngine.prototype.unlock = function () {
  69493. this._triggerRunningState();
  69494. };
  69495. AudioEngine.prototype._resumeAudioContext = function () {
  69496. var result;
  69497. if (this._audioContext.resume) {
  69498. result = this._audioContext.resume();
  69499. }
  69500. return result || Promise.resolve();
  69501. };
  69502. AudioEngine.prototype._initializeAudioContext = function () {
  69503. try {
  69504. if (this.canUseWebAudio) {
  69505. this._audioContext = new AudioContext();
  69506. // create a global volume gain node
  69507. this.masterGain = this._audioContext.createGain();
  69508. this.masterGain.gain.value = 1;
  69509. this.masterGain.connect(this._audioContext.destination);
  69510. this._audioContextInitialized = true;
  69511. if (this._audioContext.state === "running") {
  69512. // Do not wait for the promise to unlock.
  69513. this._triggerRunningState();
  69514. }
  69515. }
  69516. }
  69517. catch (e) {
  69518. this.canUseWebAudio = false;
  69519. BABYLON.Tools.Error("Web Audio: " + e.message);
  69520. }
  69521. };
  69522. AudioEngine.prototype._triggerRunningState = function () {
  69523. var _this = this;
  69524. if (this._tryToRun) {
  69525. return;
  69526. }
  69527. this._tryToRun = true;
  69528. this._resumeAudioContext()
  69529. .then(function () {
  69530. _this._tryToRun = false;
  69531. if (_this._muteButton) {
  69532. _this._hideMuteButton();
  69533. }
  69534. }).catch(function () {
  69535. _this._tryToRun = false;
  69536. _this.unlocked = false;
  69537. });
  69538. // Notify users that the audio stack is unlocked/unmuted
  69539. this.unlocked = true;
  69540. this.onAudioUnlockedObservable.notifyObservers(this);
  69541. };
  69542. AudioEngine.prototype._triggerSuspendedState = function () {
  69543. this.unlocked = false;
  69544. this.onAudioLockedObservable.notifyObservers(this);
  69545. this._displayMuteButton();
  69546. };
  69547. AudioEngine.prototype._displayMuteButton = function () {
  69548. var _this = this;
  69549. if (this.useCustomUnlockedButton) {
  69550. return;
  69551. }
  69552. this._muteButton = document.createElement("BUTTON");
  69553. this._muteButton.className = "babylonUnmuteIcon";
  69554. this._muteButton.id = "babylonUnmuteIconBtn";
  69555. this._muteButton.title = "Unmute";
  69556. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  69557. var style = document.createElement('style');
  69558. style.appendChild(document.createTextNode(css));
  69559. document.getElementsByTagName('head')[0].appendChild(style);
  69560. document.body.appendChild(this._muteButton);
  69561. this._moveButtonToTopLeft();
  69562. this._muteButton.addEventListener('touchend', function () {
  69563. _this._triggerRunningState();
  69564. }, true);
  69565. this._muteButton.addEventListener('click', function () {
  69566. _this._triggerRunningState();
  69567. }, true);
  69568. window.addEventListener("resize", this._onResize);
  69569. };
  69570. AudioEngine.prototype._moveButtonToTopLeft = function () {
  69571. if (this._hostElement && this._muteButton) {
  69572. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  69573. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  69574. }
  69575. };
  69576. AudioEngine.prototype._hideMuteButton = function () {
  69577. if (this._muteButton) {
  69578. document.body.removeChild(this._muteButton);
  69579. this._muteButton = null;
  69580. }
  69581. };
  69582. /**
  69583. * Destroy and release the resources associated with the audio ccontext.
  69584. */
  69585. AudioEngine.prototype.dispose = function () {
  69586. if (this.canUseWebAudio && this._audioContextInitialized) {
  69587. if (this._connectedAnalyser && this._audioContext) {
  69588. this._connectedAnalyser.stopDebugCanvas();
  69589. this._connectedAnalyser.dispose();
  69590. this.masterGain.disconnect();
  69591. this.masterGain.connect(this._audioContext.destination);
  69592. this._connectedAnalyser = null;
  69593. }
  69594. this.masterGain.gain.value = 1;
  69595. }
  69596. this.WarnedWebAudioUnsupported = false;
  69597. this._hideMuteButton();
  69598. window.removeEventListener("resize", this._onResize);
  69599. this.onAudioUnlockedObservable.clear();
  69600. this.onAudioLockedObservable.clear();
  69601. };
  69602. /**
  69603. * Gets the global volume sets on the master gain.
  69604. * @returns the global volume if set or -1 otherwise
  69605. */
  69606. AudioEngine.prototype.getGlobalVolume = function () {
  69607. if (this.canUseWebAudio && this._audioContextInitialized) {
  69608. return this.masterGain.gain.value;
  69609. }
  69610. else {
  69611. return -1;
  69612. }
  69613. };
  69614. /**
  69615. * Sets the global volume of your experience (sets on the master gain).
  69616. * @param newVolume Defines the new global volume of the application
  69617. */
  69618. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  69619. if (this.canUseWebAudio && this._audioContextInitialized) {
  69620. this.masterGain.gain.value = newVolume;
  69621. }
  69622. };
  69623. /**
  69624. * Connect the audio engine to an audio analyser allowing some amazing
  69625. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69626. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69627. * @param analyser The analyser to connect to the engine
  69628. */
  69629. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  69630. if (this._connectedAnalyser) {
  69631. this._connectedAnalyser.stopDebugCanvas();
  69632. }
  69633. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  69634. this._connectedAnalyser = analyser;
  69635. this.masterGain.disconnect();
  69636. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  69637. }
  69638. };
  69639. return AudioEngine;
  69640. }());
  69641. BABYLON.AudioEngine = AudioEngine;
  69642. })(BABYLON || (BABYLON = {}));
  69643. //# sourceMappingURL=babylon.audioEngine.js.map
  69644. var BABYLON;
  69645. (function (BABYLON) {
  69646. /**
  69647. * Defines a sound that can be played in the application.
  69648. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  69649. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69650. */
  69651. var Sound = /** @class */ (function () {
  69652. /**
  69653. * Create a sound and attach it to a scene
  69654. * @param name Name of your sound
  69655. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  69656. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  69657. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  69658. */
  69659. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  69660. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  69661. var _this = this;
  69662. /**
  69663. * Does the sound autoplay once loaded.
  69664. */
  69665. this.autoplay = false;
  69666. /**
  69667. * Does the sound loop after it finishes playing once.
  69668. */
  69669. this.loop = false;
  69670. /**
  69671. * Does the sound use a custom attenuation curve to simulate the falloff
  69672. * happening when the source gets further away from the camera.
  69673. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69674. */
  69675. this.useCustomAttenuation = false;
  69676. /**
  69677. * Is this sound currently played.
  69678. */
  69679. this.isPlaying = false;
  69680. /**
  69681. * Is this sound currently paused.
  69682. */
  69683. this.isPaused = false;
  69684. /**
  69685. * Does this sound enables spatial sound.
  69686. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69687. */
  69688. this.spatialSound = false;
  69689. /**
  69690. * Define the reference distance the sound should be heard perfectly.
  69691. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69692. */
  69693. this.refDistance = 1;
  69694. /**
  69695. * Define the roll off factor of spatial sounds.
  69696. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69697. */
  69698. this.rolloffFactor = 1;
  69699. /**
  69700. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  69701. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69702. */
  69703. this.maxDistance = 100;
  69704. /**
  69705. * Define the distance attenuation model the sound will follow.
  69706. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69707. */
  69708. this.distanceModel = "linear";
  69709. /**
  69710. * Observable event when the current playing sound finishes.
  69711. */
  69712. this.onEndedObservable = new BABYLON.Observable();
  69713. this._panningModel = "equalpower";
  69714. this._playbackRate = 1;
  69715. this._streaming = false;
  69716. this._startTime = 0;
  69717. this._startOffset = 0;
  69718. this._position = BABYLON.Vector3.Zero();
  69719. /** @hidden */
  69720. this._positionInEmitterSpace = false;
  69721. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  69722. this._volume = 1;
  69723. this._isReadyToPlay = false;
  69724. this._isDirectional = false;
  69725. // Used if you'd like to create a directional sound.
  69726. // If not set, the sound will be omnidirectional
  69727. this._coneInnerAngle = 360;
  69728. this._coneOuterAngle = 360;
  69729. this._coneOuterGain = 0;
  69730. this._isOutputConnected = false;
  69731. this._urlType = "Unknown";
  69732. this.name = name;
  69733. this._scene = scene;
  69734. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69735. if (!compo) {
  69736. compo = new BABYLON.AudioSceneComponent(scene);
  69737. scene._addComponent(compo);
  69738. }
  69739. this._readyToPlayCallback = readyToPlayCallback;
  69740. // Default custom attenuation function is a linear attenuation
  69741. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  69742. if (currentDistance < maxDistance) {
  69743. return currentVolume * (1 - currentDistance / maxDistance);
  69744. }
  69745. else {
  69746. return 0;
  69747. }
  69748. };
  69749. if (options) {
  69750. this.autoplay = options.autoplay || false;
  69751. this.loop = options.loop || false;
  69752. // if volume === 0, we need another way to check this option
  69753. if (options.volume !== undefined) {
  69754. this._volume = options.volume;
  69755. }
  69756. this.spatialSound = options.spatialSound || false;
  69757. this.maxDistance = options.maxDistance || 100;
  69758. this.useCustomAttenuation = options.useCustomAttenuation || false;
  69759. this.rolloffFactor = options.rolloffFactor || 1;
  69760. this.refDistance = options.refDistance || 1;
  69761. this.distanceModel = options.distanceModel || "linear";
  69762. this._playbackRate = options.playbackRate || 1;
  69763. this._streaming = options.streaming || false;
  69764. }
  69765. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69766. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  69767. this._soundGain.gain.value = this._volume;
  69768. this._inputAudioNode = this._soundGain;
  69769. this._outputAudioNode = this._soundGain;
  69770. if (this.spatialSound) {
  69771. this._createSpatialParameters();
  69772. }
  69773. this._scene.mainSoundTrack.AddSound(this);
  69774. var validParameter = true;
  69775. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  69776. if (urlOrArrayBuffer) {
  69777. try {
  69778. if (typeof (urlOrArrayBuffer) === "string") {
  69779. this._urlType = "String";
  69780. }
  69781. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  69782. this._urlType = "ArrayBuffer";
  69783. }
  69784. else if (urlOrArrayBuffer instanceof MediaStream) {
  69785. this._urlType = "MediaStream";
  69786. }
  69787. else if (Array.isArray(urlOrArrayBuffer)) {
  69788. this._urlType = "Array";
  69789. }
  69790. var urls = [];
  69791. var codecSupportedFound = false;
  69792. switch (this._urlType) {
  69793. case "MediaStream":
  69794. this._streaming = true;
  69795. this._isReadyToPlay = true;
  69796. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  69797. if (this.autoplay) {
  69798. this.play();
  69799. }
  69800. if (this._readyToPlayCallback) {
  69801. this._readyToPlayCallback();
  69802. }
  69803. break;
  69804. case "ArrayBuffer":
  69805. if (urlOrArrayBuffer.byteLength > 0) {
  69806. codecSupportedFound = true;
  69807. this._soundLoaded(urlOrArrayBuffer);
  69808. }
  69809. break;
  69810. case "String":
  69811. urls.push(urlOrArrayBuffer);
  69812. case "Array":
  69813. if (urls.length === 0) {
  69814. urls = urlOrArrayBuffer;
  69815. }
  69816. // If we found a supported format, we load it immediately and stop the loop
  69817. for (var i = 0; i < urls.length; i++) {
  69818. var url = urls[i];
  69819. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  69820. codecSupportedFound = true;
  69821. }
  69822. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  69823. codecSupportedFound = true;
  69824. }
  69825. if (url.indexOf(".wav", url.length - 4) !== -1) {
  69826. codecSupportedFound = true;
  69827. }
  69828. if (url.indexOf("blob:") !== -1) {
  69829. codecSupportedFound = true;
  69830. }
  69831. if (codecSupportedFound) {
  69832. // Loading sound using XHR2
  69833. if (!this._streaming) {
  69834. this._scene._loadFile(url, function (data) {
  69835. _this._soundLoaded(data);
  69836. }, undefined, true, true, function (exception) {
  69837. if (exception) {
  69838. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  69839. }
  69840. BABYLON.Tools.Error("Sound creation aborted.");
  69841. _this._scene.mainSoundTrack.RemoveSound(_this);
  69842. });
  69843. }
  69844. // Streaming sound using HTML5 Audio tag
  69845. else {
  69846. this._htmlAudioElement = new Audio(url);
  69847. this._htmlAudioElement.controls = false;
  69848. this._htmlAudioElement.loop = this.loop;
  69849. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  69850. this._htmlAudioElement.preload = "auto";
  69851. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  69852. _this._isReadyToPlay = true;
  69853. if (_this.autoplay) {
  69854. _this.play();
  69855. }
  69856. if (_this._readyToPlayCallback) {
  69857. _this._readyToPlayCallback();
  69858. }
  69859. });
  69860. document.body.appendChild(this._htmlAudioElement);
  69861. this._htmlAudioElement.load();
  69862. }
  69863. break;
  69864. }
  69865. }
  69866. break;
  69867. default:
  69868. validParameter = false;
  69869. break;
  69870. }
  69871. if (!validParameter) {
  69872. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  69873. }
  69874. else {
  69875. if (!codecSupportedFound) {
  69876. this._isReadyToPlay = true;
  69877. // Simulating a ready to play event to avoid breaking code path
  69878. if (this._readyToPlayCallback) {
  69879. window.setTimeout(function () {
  69880. if (_this._readyToPlayCallback) {
  69881. _this._readyToPlayCallback();
  69882. }
  69883. }, 1000);
  69884. }
  69885. }
  69886. }
  69887. }
  69888. catch (ex) {
  69889. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  69890. this._scene.mainSoundTrack.RemoveSound(this);
  69891. }
  69892. }
  69893. }
  69894. else {
  69895. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  69896. this._scene.mainSoundTrack.AddSound(this);
  69897. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  69898. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  69899. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  69900. }
  69901. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  69902. if (this._readyToPlayCallback) {
  69903. window.setTimeout(function () {
  69904. if (_this._readyToPlayCallback) {
  69905. _this._readyToPlayCallback();
  69906. }
  69907. }, 1000);
  69908. }
  69909. }
  69910. }
  69911. /**
  69912. * Release the sound and its associated resources
  69913. */
  69914. Sound.prototype.dispose = function () {
  69915. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69916. if (this.isPlaying) {
  69917. this.stop();
  69918. }
  69919. this._isReadyToPlay = false;
  69920. if (this.soundTrackId === -1) {
  69921. this._scene.mainSoundTrack.RemoveSound(this);
  69922. }
  69923. else if (this._scene.soundTracks) {
  69924. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  69925. }
  69926. if (this._soundGain) {
  69927. this._soundGain.disconnect();
  69928. this._soundGain = null;
  69929. }
  69930. if (this._soundPanner) {
  69931. this._soundPanner.disconnect();
  69932. this._soundPanner = null;
  69933. }
  69934. if (this._soundSource) {
  69935. this._soundSource.disconnect();
  69936. this._soundSource = null;
  69937. }
  69938. this._audioBuffer = null;
  69939. if (this._htmlAudioElement) {
  69940. this._htmlAudioElement.pause();
  69941. this._htmlAudioElement.src = "";
  69942. document.body.removeChild(this._htmlAudioElement);
  69943. }
  69944. if (this._streamingSource) {
  69945. this._streamingSource.disconnect();
  69946. }
  69947. if (this._connectedMesh && this._registerFunc) {
  69948. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69949. this._connectedMesh = null;
  69950. }
  69951. }
  69952. };
  69953. /**
  69954. * Gets if the sounds is ready to be played or not.
  69955. * @returns true if ready, otherwise false
  69956. */
  69957. Sound.prototype.isReady = function () {
  69958. return this._isReadyToPlay;
  69959. };
  69960. Sound.prototype._soundLoaded = function (audioData) {
  69961. var _this = this;
  69962. if (!BABYLON.Engine.audioEngine.audioContext) {
  69963. return;
  69964. }
  69965. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69966. _this._audioBuffer = buffer;
  69967. _this._isReadyToPlay = true;
  69968. if (_this.autoplay) {
  69969. _this.play();
  69970. }
  69971. if (_this._readyToPlayCallback) {
  69972. _this._readyToPlayCallback();
  69973. }
  69974. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69975. };
  69976. /**
  69977. * Sets the data of the sound from an audiobuffer
  69978. * @param audioBuffer The audioBuffer containing the data
  69979. */
  69980. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69981. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69982. this._audioBuffer = audioBuffer;
  69983. this._isReadyToPlay = true;
  69984. }
  69985. };
  69986. /**
  69987. * Updates the current sounds options such as maxdistance, loop...
  69988. * @param options A JSON object containing values named as the object properties
  69989. */
  69990. Sound.prototype.updateOptions = function (options) {
  69991. if (options) {
  69992. this.loop = options.loop || this.loop;
  69993. this.maxDistance = options.maxDistance || this.maxDistance;
  69994. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69995. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69996. this.refDistance = options.refDistance || this.refDistance;
  69997. this.distanceModel = options.distanceModel || this.distanceModel;
  69998. this._playbackRate = options.playbackRate || this._playbackRate;
  69999. this._updateSpatialParameters();
  70000. if (this.isPlaying) {
  70001. if (this._streaming && this._htmlAudioElement) {
  70002. this._htmlAudioElement.playbackRate = this._playbackRate;
  70003. }
  70004. else {
  70005. if (this._soundSource) {
  70006. this._soundSource.playbackRate.value = this._playbackRate;
  70007. }
  70008. }
  70009. }
  70010. }
  70011. };
  70012. Sound.prototype._createSpatialParameters = function () {
  70013. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70014. if (this._scene.headphone) {
  70015. this._panningModel = "HRTF";
  70016. }
  70017. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  70018. this._updateSpatialParameters();
  70019. this._soundPanner.connect(this._outputAudioNode);
  70020. this._inputAudioNode = this._soundPanner;
  70021. }
  70022. };
  70023. Sound.prototype._updateSpatialParameters = function () {
  70024. if (this.spatialSound && this._soundPanner) {
  70025. if (this.useCustomAttenuation) {
  70026. // Tricks to disable in a way embedded Web Audio attenuation
  70027. this._soundPanner.distanceModel = "linear";
  70028. this._soundPanner.maxDistance = Number.MAX_VALUE;
  70029. this._soundPanner.refDistance = 1;
  70030. this._soundPanner.rolloffFactor = 1;
  70031. this._soundPanner.panningModel = this._panningModel;
  70032. }
  70033. else {
  70034. this._soundPanner.distanceModel = this.distanceModel;
  70035. this._soundPanner.maxDistance = this.maxDistance;
  70036. this._soundPanner.refDistance = this.refDistance;
  70037. this._soundPanner.rolloffFactor = this.rolloffFactor;
  70038. this._soundPanner.panningModel = this._panningModel;
  70039. }
  70040. }
  70041. };
  70042. /**
  70043. * Switch the panning model to HRTF:
  70044. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70045. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70046. */
  70047. Sound.prototype.switchPanningModelToHRTF = function () {
  70048. this._panningModel = "HRTF";
  70049. this._switchPanningModel();
  70050. };
  70051. /**
  70052. * Switch the panning model to Equal Power:
  70053. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70054. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70055. */
  70056. Sound.prototype.switchPanningModelToEqualPower = function () {
  70057. this._panningModel = "equalpower";
  70058. this._switchPanningModel();
  70059. };
  70060. Sound.prototype._switchPanningModel = function () {
  70061. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70062. this._soundPanner.panningModel = this._panningModel;
  70063. }
  70064. };
  70065. /**
  70066. * Connect this sound to a sound track audio node like gain...
  70067. * @param soundTrackAudioNode the sound track audio node to connect to
  70068. */
  70069. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  70070. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70071. if (this._isOutputConnected) {
  70072. this._outputAudioNode.disconnect();
  70073. }
  70074. this._outputAudioNode.connect(soundTrackAudioNode);
  70075. this._isOutputConnected = true;
  70076. }
  70077. };
  70078. /**
  70079. * Transform this sound into a directional source
  70080. * @param coneInnerAngle Size of the inner cone in degree
  70081. * @param coneOuterAngle Size of the outer cone in degree
  70082. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  70083. */
  70084. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  70085. if (coneOuterAngle < coneInnerAngle) {
  70086. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  70087. return;
  70088. }
  70089. this._coneInnerAngle = coneInnerAngle;
  70090. this._coneOuterAngle = coneOuterAngle;
  70091. this._coneOuterGain = coneOuterGain;
  70092. this._isDirectional = true;
  70093. if (this.isPlaying && this.loop) {
  70094. this.stop();
  70095. this.play();
  70096. }
  70097. };
  70098. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  70099. /**
  70100. * Gets or sets the inner angle for the directional cone.
  70101. */
  70102. get: function () {
  70103. return this._coneInnerAngle;
  70104. },
  70105. /**
  70106. * Gets or sets the inner angle for the directional cone.
  70107. */
  70108. set: function (value) {
  70109. if (value != this._coneInnerAngle) {
  70110. if (this._coneOuterAngle < value) {
  70111. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70112. return;
  70113. }
  70114. this._coneInnerAngle = value;
  70115. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70116. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  70117. }
  70118. }
  70119. },
  70120. enumerable: true,
  70121. configurable: true
  70122. });
  70123. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  70124. /**
  70125. * Gets or sets the outer angle for the directional cone.
  70126. */
  70127. get: function () {
  70128. return this._coneOuterAngle;
  70129. },
  70130. /**
  70131. * Gets or sets the outer angle for the directional cone.
  70132. */
  70133. set: function (value) {
  70134. if (value != this._coneOuterAngle) {
  70135. if (value < this._coneInnerAngle) {
  70136. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70137. return;
  70138. }
  70139. this._coneOuterAngle = value;
  70140. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  70141. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  70142. }
  70143. }
  70144. },
  70145. enumerable: true,
  70146. configurable: true
  70147. });
  70148. /**
  70149. * Sets the position of the emitter if spatial sound is enabled
  70150. * @param newPosition Defines the new posisiton
  70151. */
  70152. Sound.prototype.setPosition = function (newPosition) {
  70153. this._position = newPosition;
  70154. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  70155. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  70156. }
  70157. };
  70158. /**
  70159. * Sets the local direction of the emitter if spatial sound is enabled
  70160. * @param newLocalDirection Defines the new local direction
  70161. */
  70162. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  70163. this._localDirection = newLocalDirection;
  70164. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  70165. this._updateDirection();
  70166. }
  70167. };
  70168. Sound.prototype._updateDirection = function () {
  70169. if (!this._connectedMesh || !this._soundPanner) {
  70170. return;
  70171. }
  70172. var mat = this._connectedMesh.getWorldMatrix();
  70173. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  70174. direction.normalize();
  70175. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  70176. };
  70177. /** @hidden */
  70178. Sound.prototype.updateDistanceFromListener = function () {
  70179. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  70180. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  70181. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  70182. }
  70183. };
  70184. /**
  70185. * Sets a new custom attenuation function for the sound.
  70186. * @param callback Defines the function used for the attenuation
  70187. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70188. */
  70189. Sound.prototype.setAttenuationFunction = function (callback) {
  70190. this._customAttenuationFunction = callback;
  70191. };
  70192. /**
  70193. * Play the sound
  70194. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  70195. * @param offset (optional) Start the sound setting it at a specific time
  70196. */
  70197. Sound.prototype.play = function (time, offset) {
  70198. var _this = this;
  70199. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  70200. try {
  70201. if (this._startOffset < 0) {
  70202. time = -this._startOffset;
  70203. this._startOffset = 0;
  70204. }
  70205. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70206. if (!this._soundSource || !this._streamingSource) {
  70207. if (this.spatialSound && this._soundPanner) {
  70208. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  70209. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  70210. }
  70211. if (this._isDirectional) {
  70212. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  70213. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  70214. this._soundPanner.coneOuterGain = this._coneOuterGain;
  70215. if (this._connectedMesh) {
  70216. this._updateDirection();
  70217. }
  70218. else {
  70219. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  70220. }
  70221. }
  70222. }
  70223. }
  70224. if (this._streaming) {
  70225. if (!this._streamingSource) {
  70226. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  70227. this._htmlAudioElement.onended = function () { _this._onended(); };
  70228. this._htmlAudioElement.playbackRate = this._playbackRate;
  70229. }
  70230. this._streamingSource.disconnect();
  70231. this._streamingSource.connect(this._inputAudioNode);
  70232. if (this._htmlAudioElement) {
  70233. // required to manage properly the new suspended default state of Chrome
  70234. // When the option 'streaming: true' is used, we need first to wait for
  70235. // the audio engine to be unlocked by a user gesture before trying to play
  70236. // an HTML Audio elememt
  70237. var tryToPlay = function () {
  70238. if (BABYLON.Engine.audioEngine.unlocked) {
  70239. var playPromise = _this._htmlAudioElement.play();
  70240. // In browsers that don’t yet support this functionality,
  70241. // playPromise won’t be defined.
  70242. if (playPromise !== undefined) {
  70243. playPromise.catch(function (error) {
  70244. // Automatic playback failed.
  70245. // Waiting for the audio engine to be unlocked by user click on unmute
  70246. BABYLON.Engine.audioEngine.lock();
  70247. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70248. });
  70249. }
  70250. }
  70251. else {
  70252. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70253. }
  70254. };
  70255. tryToPlay();
  70256. }
  70257. }
  70258. else {
  70259. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  70260. this._soundSource.buffer = this._audioBuffer;
  70261. this._soundSource.connect(this._inputAudioNode);
  70262. this._soundSource.loop = this.loop;
  70263. this._soundSource.playbackRate.value = this._playbackRate;
  70264. this._soundSource.onended = function () { _this._onended(); };
  70265. if (this._soundSource.buffer) {
  70266. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  70267. }
  70268. }
  70269. this._startTime = startTime;
  70270. this.isPlaying = true;
  70271. this.isPaused = false;
  70272. }
  70273. catch (ex) {
  70274. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  70275. }
  70276. }
  70277. };
  70278. Sound.prototype._onended = function () {
  70279. this.isPlaying = false;
  70280. if (this.onended) {
  70281. this.onended();
  70282. }
  70283. this.onEndedObservable.notifyObservers(this);
  70284. };
  70285. /**
  70286. * Stop the sound
  70287. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  70288. */
  70289. Sound.prototype.stop = function (time) {
  70290. if (this.isPlaying) {
  70291. if (this._streaming) {
  70292. if (this._htmlAudioElement) {
  70293. this._htmlAudioElement.pause();
  70294. // Test needed for Firefox or it will generate an Invalid State Error
  70295. if (this._htmlAudioElement.currentTime > 0) {
  70296. this._htmlAudioElement.currentTime = 0;
  70297. }
  70298. }
  70299. else {
  70300. this._streamingSource.disconnect();
  70301. }
  70302. }
  70303. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  70304. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70305. this._soundSource.stop(stopTime);
  70306. this._soundSource.onended = function () { };
  70307. if (!this.isPaused) {
  70308. this._startOffset = 0;
  70309. }
  70310. }
  70311. this.isPlaying = false;
  70312. }
  70313. };
  70314. /**
  70315. * Put the sound in pause
  70316. */
  70317. Sound.prototype.pause = function () {
  70318. if (this.isPlaying) {
  70319. this.isPaused = true;
  70320. if (this._streaming) {
  70321. if (this._htmlAudioElement) {
  70322. this._htmlAudioElement.pause();
  70323. }
  70324. else {
  70325. this._streamingSource.disconnect();
  70326. }
  70327. }
  70328. else if (BABYLON.Engine.audioEngine.audioContext) {
  70329. this.stop(0);
  70330. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  70331. }
  70332. }
  70333. };
  70334. /**
  70335. * Sets a dedicated volume for this sounds
  70336. * @param newVolume Define the new volume of the sound
  70337. * @param time Define in how long the sound should be at this value
  70338. */
  70339. Sound.prototype.setVolume = function (newVolume, time) {
  70340. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  70341. if (time && BABYLON.Engine.audioEngine.audioContext) {
  70342. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  70343. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  70344. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  70345. }
  70346. else {
  70347. this._soundGain.gain.value = newVolume;
  70348. }
  70349. }
  70350. this._volume = newVolume;
  70351. };
  70352. /**
  70353. * Set the sound play back rate
  70354. * @param newPlaybackRate Define the playback rate the sound should be played at
  70355. */
  70356. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  70357. this._playbackRate = newPlaybackRate;
  70358. if (this.isPlaying) {
  70359. if (this._streaming && this._htmlAudioElement) {
  70360. this._htmlAudioElement.playbackRate = this._playbackRate;
  70361. }
  70362. else if (this._soundSource) {
  70363. this._soundSource.playbackRate.value = this._playbackRate;
  70364. }
  70365. }
  70366. };
  70367. /**
  70368. * Gets the volume of the sound.
  70369. * @returns the volume of the sound
  70370. */
  70371. Sound.prototype.getVolume = function () {
  70372. return this._volume;
  70373. };
  70374. /**
  70375. * Attach the sound to a dedicated mesh
  70376. * @param meshToConnectTo The mesh to connect the sound with
  70377. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70378. */
  70379. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  70380. var _this = this;
  70381. if (this._connectedMesh && this._registerFunc) {
  70382. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70383. this._registerFunc = null;
  70384. }
  70385. this._connectedMesh = meshToConnectTo;
  70386. if (!this.spatialSound) {
  70387. this.spatialSound = true;
  70388. this._createSpatialParameters();
  70389. if (this.isPlaying && this.loop) {
  70390. this.stop();
  70391. this.play();
  70392. }
  70393. }
  70394. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  70395. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  70396. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  70397. };
  70398. /**
  70399. * Detach the sound from the previously attached mesh
  70400. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70401. */
  70402. Sound.prototype.detachFromMesh = function () {
  70403. if (this._connectedMesh && this._registerFunc) {
  70404. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70405. this._registerFunc = null;
  70406. this._connectedMesh = null;
  70407. }
  70408. };
  70409. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  70410. if (!node.getBoundingInfo) {
  70411. return;
  70412. }
  70413. var mesh = node;
  70414. if (this._positionInEmitterSpace) {
  70415. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  70416. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  70417. }
  70418. else {
  70419. var boundingInfo = mesh.getBoundingInfo();
  70420. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  70421. }
  70422. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  70423. this._updateDirection();
  70424. }
  70425. };
  70426. /**
  70427. * Clone the current sound in the scene.
  70428. * @returns the new sound clone
  70429. */
  70430. Sound.prototype.clone = function () {
  70431. var _this = this;
  70432. if (!this._streaming) {
  70433. var setBufferAndRun = function () {
  70434. if (_this._isReadyToPlay) {
  70435. clonedSound._audioBuffer = _this.getAudioBuffer();
  70436. clonedSound._isReadyToPlay = true;
  70437. if (clonedSound.autoplay) {
  70438. clonedSound.play();
  70439. }
  70440. }
  70441. else {
  70442. window.setTimeout(setBufferAndRun, 300);
  70443. }
  70444. };
  70445. var currentOptions = {
  70446. autoplay: this.autoplay, loop: this.loop,
  70447. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  70448. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  70449. refDistance: this.refDistance, distanceModel: this.distanceModel
  70450. };
  70451. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  70452. if (this.useCustomAttenuation) {
  70453. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  70454. }
  70455. clonedSound.setPosition(this._position);
  70456. clonedSound.setPlaybackRate(this._playbackRate);
  70457. setBufferAndRun();
  70458. return clonedSound;
  70459. }
  70460. // Can't clone a streaming sound
  70461. else {
  70462. return null;
  70463. }
  70464. };
  70465. /**
  70466. * Gets the current underlying audio buffer containing the data
  70467. * @returns the audio buffer
  70468. */
  70469. Sound.prototype.getAudioBuffer = function () {
  70470. return this._audioBuffer;
  70471. };
  70472. /**
  70473. * Serializes the Sound in a JSON representation
  70474. * @returns the JSON representation of the sound
  70475. */
  70476. Sound.prototype.serialize = function () {
  70477. var serializationObject = {
  70478. name: this.name,
  70479. url: this.name,
  70480. autoplay: this.autoplay,
  70481. loop: this.loop,
  70482. volume: this._volume,
  70483. spatialSound: this.spatialSound,
  70484. maxDistance: this.maxDistance,
  70485. rolloffFactor: this.rolloffFactor,
  70486. refDistance: this.refDistance,
  70487. distanceModel: this.distanceModel,
  70488. playbackRate: this._playbackRate,
  70489. panningModel: this._panningModel,
  70490. soundTrackId: this.soundTrackId
  70491. };
  70492. if (this.spatialSound) {
  70493. if (this._connectedMesh) {
  70494. serializationObject.connectedMeshId = this._connectedMesh.id;
  70495. }
  70496. serializationObject.position = this._position.asArray();
  70497. serializationObject.refDistance = this.refDistance;
  70498. serializationObject.distanceModel = this.distanceModel;
  70499. serializationObject.isDirectional = this._isDirectional;
  70500. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  70501. serializationObject.coneInnerAngle = this._coneInnerAngle;
  70502. serializationObject.coneOuterAngle = this._coneOuterAngle;
  70503. serializationObject.coneOuterGain = this._coneOuterGain;
  70504. }
  70505. return serializationObject;
  70506. };
  70507. /**
  70508. * Parse a JSON representation of a sound to innstantiate in a given scene
  70509. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  70510. * @param scene Define the scene the new parsed sound should be created in
  70511. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  70512. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  70513. * @returns the newly parsed sound
  70514. */
  70515. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  70516. var soundName = parsedSound.name;
  70517. var soundUrl;
  70518. if (parsedSound.url) {
  70519. soundUrl = rootUrl + parsedSound.url;
  70520. }
  70521. else {
  70522. soundUrl = rootUrl + soundName;
  70523. }
  70524. var options = {
  70525. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  70526. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  70527. rolloffFactor: parsedSound.rolloffFactor,
  70528. refDistance: parsedSound.refDistance,
  70529. distanceModel: parsedSound.distanceModel,
  70530. playbackRate: parsedSound.playbackRate
  70531. };
  70532. var newSound;
  70533. if (!sourceSound) {
  70534. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  70535. scene._addPendingData(newSound);
  70536. }
  70537. else {
  70538. var setBufferAndRun = function () {
  70539. if (sourceSound._isReadyToPlay) {
  70540. newSound._audioBuffer = sourceSound.getAudioBuffer();
  70541. newSound._isReadyToPlay = true;
  70542. if (newSound.autoplay) {
  70543. newSound.play();
  70544. }
  70545. }
  70546. else {
  70547. window.setTimeout(setBufferAndRun, 300);
  70548. }
  70549. };
  70550. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  70551. setBufferAndRun();
  70552. }
  70553. if (parsedSound.position) {
  70554. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  70555. newSound.setPosition(soundPosition);
  70556. }
  70557. if (parsedSound.isDirectional) {
  70558. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  70559. if (parsedSound.localDirectionToMesh) {
  70560. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  70561. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  70562. }
  70563. }
  70564. if (parsedSound.connectedMeshId) {
  70565. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  70566. if (connectedMesh) {
  70567. newSound.attachToMesh(connectedMesh);
  70568. }
  70569. }
  70570. return newSound;
  70571. };
  70572. return Sound;
  70573. }());
  70574. BABYLON.Sound = Sound;
  70575. })(BABYLON || (BABYLON = {}));
  70576. //# sourceMappingURL=babylon.sound.js.map
  70577. var BABYLON;
  70578. (function (BABYLON) {
  70579. /**
  70580. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  70581. * It will be also used in a future release to apply effects on a specific track.
  70582. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70583. */
  70584. var SoundTrack = /** @class */ (function () {
  70585. /**
  70586. * Creates a new sound track.
  70587. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70588. * @param scene Define the scene the sound track belongs to
  70589. * @param options
  70590. */
  70591. function SoundTrack(scene, options) {
  70592. if (options === void 0) { options = {}; }
  70593. /**
  70594. * The unique identifier of the sound track in the scene.
  70595. */
  70596. this.id = -1;
  70597. this._isMainTrack = false;
  70598. this._isInitialized = false;
  70599. this._scene = scene;
  70600. this.soundCollection = new Array();
  70601. this._options = options;
  70602. if (!this._isMainTrack && this._scene.soundTracks) {
  70603. this._scene.soundTracks.push(this);
  70604. this.id = this._scene.soundTracks.length - 1;
  70605. }
  70606. }
  70607. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  70608. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70609. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  70610. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  70611. if (this._options) {
  70612. if (this._options.volume) {
  70613. this._outputAudioNode.gain.value = this._options.volume;
  70614. }
  70615. if (this._options.mainTrack) {
  70616. this._isMainTrack = this._options.mainTrack;
  70617. }
  70618. }
  70619. this._isInitialized = true;
  70620. }
  70621. };
  70622. /**
  70623. * Release the sound track and its associated resources
  70624. */
  70625. SoundTrack.prototype.dispose = function () {
  70626. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  70627. if (this._connectedAnalyser) {
  70628. this._connectedAnalyser.stopDebugCanvas();
  70629. }
  70630. while (this.soundCollection.length) {
  70631. this.soundCollection[0].dispose();
  70632. }
  70633. if (this._outputAudioNode) {
  70634. this._outputAudioNode.disconnect();
  70635. }
  70636. this._outputAudioNode = null;
  70637. }
  70638. };
  70639. /**
  70640. * Adds a sound to this sound track
  70641. * @param sound define the cound to add
  70642. * @ignoreNaming
  70643. */
  70644. SoundTrack.prototype.AddSound = function (sound) {
  70645. if (!this._isInitialized) {
  70646. this._initializeSoundTrackAudioGraph();
  70647. }
  70648. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70649. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  70650. }
  70651. if (sound.soundTrackId) {
  70652. if (sound.soundTrackId === -1) {
  70653. this._scene.mainSoundTrack.RemoveSound(sound);
  70654. }
  70655. else if (this._scene.soundTracks) {
  70656. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  70657. }
  70658. }
  70659. this.soundCollection.push(sound);
  70660. sound.soundTrackId = this.id;
  70661. };
  70662. /**
  70663. * Removes a sound to this sound track
  70664. * @param sound define the cound to remove
  70665. * @ignoreNaming
  70666. */
  70667. SoundTrack.prototype.RemoveSound = function (sound) {
  70668. var index = this.soundCollection.indexOf(sound);
  70669. if (index !== -1) {
  70670. this.soundCollection.splice(index, 1);
  70671. }
  70672. };
  70673. /**
  70674. * Set a global volume for the full sound track.
  70675. * @param newVolume Define the new volume of the sound track
  70676. */
  70677. SoundTrack.prototype.setVolume = function (newVolume) {
  70678. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70679. this._outputAudioNode.gain.value = newVolume;
  70680. }
  70681. };
  70682. /**
  70683. * Switch the panning model to HRTF:
  70684. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70685. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70686. */
  70687. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  70688. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70689. for (var i = 0; i < this.soundCollection.length; i++) {
  70690. this.soundCollection[i].switchPanningModelToHRTF();
  70691. }
  70692. }
  70693. };
  70694. /**
  70695. * Switch the panning model to Equal Power:
  70696. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70697. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70698. */
  70699. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  70700. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70701. for (var i = 0; i < this.soundCollection.length; i++) {
  70702. this.soundCollection[i].switchPanningModelToEqualPower();
  70703. }
  70704. }
  70705. };
  70706. /**
  70707. * Connect the sound track to an audio analyser allowing some amazing
  70708. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70709. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70710. * @param analyser The analyser to connect to the engine
  70711. */
  70712. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  70713. if (this._connectedAnalyser) {
  70714. this._connectedAnalyser.stopDebugCanvas();
  70715. }
  70716. this._connectedAnalyser = analyser;
  70717. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70718. this._outputAudioNode.disconnect();
  70719. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  70720. }
  70721. };
  70722. return SoundTrack;
  70723. }());
  70724. BABYLON.SoundTrack = SoundTrack;
  70725. })(BABYLON || (BABYLON = {}));
  70726. //# sourceMappingURL=babylon.soundtrack.js.map
  70727. var BABYLON;
  70728. (function (BABYLON) {
  70729. /**
  70730. * Class used to work with sound analyzer using fast fourier transform (FFT)
  70731. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70732. */
  70733. var Analyser = /** @class */ (function () {
  70734. /**
  70735. * Creates a new analyser
  70736. * @param scene defines hosting scene
  70737. */
  70738. function Analyser(scene) {
  70739. /**
  70740. * Gets or sets the smoothing
  70741. * @ignorenaming
  70742. */
  70743. this.SMOOTHING = 0.75;
  70744. /**
  70745. * Gets or sets the FFT table size
  70746. * @ignorenaming
  70747. */
  70748. this.FFT_SIZE = 512;
  70749. /**
  70750. * Gets or sets the bar graph amplitude
  70751. * @ignorenaming
  70752. */
  70753. this.BARGRAPHAMPLITUDE = 256;
  70754. /**
  70755. * Gets or sets the position of the debug canvas
  70756. * @ignorenaming
  70757. */
  70758. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  70759. /**
  70760. * Gets or sets the debug canvas size
  70761. * @ignorenaming
  70762. */
  70763. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  70764. this._scene = scene;
  70765. this._audioEngine = BABYLON.Engine.audioEngine;
  70766. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  70767. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  70768. this._webAudioAnalyser.minDecibels = -140;
  70769. this._webAudioAnalyser.maxDecibels = 0;
  70770. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70771. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70772. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  70773. }
  70774. }
  70775. /**
  70776. * Get the number of data values you will have to play with for the visualization
  70777. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  70778. * @returns a number
  70779. */
  70780. Analyser.prototype.getFrequencyBinCount = function () {
  70781. if (this._audioEngine.canUseWebAudio) {
  70782. return this._webAudioAnalyser.frequencyBinCount;
  70783. }
  70784. else {
  70785. return 0;
  70786. }
  70787. };
  70788. /**
  70789. * Gets the current frequency data as a byte array
  70790. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70791. * @returns a Uint8Array
  70792. */
  70793. Analyser.prototype.getByteFrequencyData = function () {
  70794. if (this._audioEngine.canUseWebAudio) {
  70795. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70796. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70797. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  70798. }
  70799. return this._byteFreqs;
  70800. };
  70801. /**
  70802. * Gets the current waveform as a byte array
  70803. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  70804. * @returns a Uint8Array
  70805. */
  70806. Analyser.prototype.getByteTimeDomainData = function () {
  70807. if (this._audioEngine.canUseWebAudio) {
  70808. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70809. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70810. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  70811. }
  70812. return this._byteTime;
  70813. };
  70814. /**
  70815. * Gets the current frequency data as a float array
  70816. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70817. * @returns a Float32Array
  70818. */
  70819. Analyser.prototype.getFloatFrequencyData = function () {
  70820. if (this._audioEngine.canUseWebAudio) {
  70821. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70822. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70823. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  70824. }
  70825. return this._floatFreqs;
  70826. };
  70827. /**
  70828. * Renders the debug canvas
  70829. */
  70830. Analyser.prototype.drawDebugCanvas = function () {
  70831. var _this = this;
  70832. if (this._audioEngine.canUseWebAudio) {
  70833. if (!this._debugCanvas) {
  70834. this._debugCanvas = document.createElement("canvas");
  70835. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  70836. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  70837. this._debugCanvas.style.position = "absolute";
  70838. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  70839. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  70840. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  70841. document.body.appendChild(this._debugCanvas);
  70842. this._registerFunc = function () {
  70843. _this.drawDebugCanvas();
  70844. };
  70845. this._scene.registerBeforeRender(this._registerFunc);
  70846. }
  70847. if (this._registerFunc && this._debugCanvasContext) {
  70848. var workingArray = this.getByteFrequencyData();
  70849. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  70850. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  70851. // Draw the frequency domain chart.
  70852. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  70853. var value = workingArray[i];
  70854. var percent = value / this.BARGRAPHAMPLITUDE;
  70855. var height = this.DEBUGCANVASSIZE.height * percent;
  70856. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  70857. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  70858. var hue = i / this.getFrequencyBinCount() * 360;
  70859. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  70860. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  70861. }
  70862. }
  70863. }
  70864. };
  70865. /**
  70866. * Stops rendering the debug canvas and removes it
  70867. */
  70868. Analyser.prototype.stopDebugCanvas = function () {
  70869. if (this._debugCanvas) {
  70870. if (this._registerFunc) {
  70871. this._scene.unregisterBeforeRender(this._registerFunc);
  70872. this._registerFunc = null;
  70873. }
  70874. document.body.removeChild(this._debugCanvas);
  70875. this._debugCanvas = null;
  70876. this._debugCanvasContext = null;
  70877. }
  70878. };
  70879. /**
  70880. * Connects two audio nodes
  70881. * @param inputAudioNode defines first node to connect
  70882. * @param outputAudioNode defines second node to connect
  70883. */
  70884. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  70885. if (this._audioEngine.canUseWebAudio) {
  70886. inputAudioNode.connect(this._webAudioAnalyser);
  70887. this._webAudioAnalyser.connect(outputAudioNode);
  70888. }
  70889. };
  70890. /**
  70891. * Releases all associated resources
  70892. */
  70893. Analyser.prototype.dispose = function () {
  70894. if (this._audioEngine.canUseWebAudio) {
  70895. this._webAudioAnalyser.disconnect();
  70896. }
  70897. };
  70898. return Analyser;
  70899. }());
  70900. BABYLON.Analyser = Analyser;
  70901. })(BABYLON || (BABYLON = {}));
  70902. //# sourceMappingURL=babylon.analyser.js.map
  70903. var BABYLON;
  70904. (function (BABYLON) {
  70905. /**
  70906. * Wraps one or more Sound objects and selects one with random weight for playback.
  70907. */
  70908. var WeightedSound = /** @class */ (function () {
  70909. /**
  70910. * Creates a new WeightedSound from the list of sounds given.
  70911. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  70912. * @param sounds Array of Sounds that will be selected from.
  70913. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  70914. */
  70915. function WeightedSound(loop, sounds, weights) {
  70916. var _this = this;
  70917. /** When true a Sound will be selected and played when the current playing Sound completes. */
  70918. this.loop = false;
  70919. this._coneInnerAngle = 360;
  70920. this._coneOuterAngle = 360;
  70921. this._volume = 1;
  70922. /** A Sound is currently playing. */
  70923. this.isPlaying = false;
  70924. /** A Sound is currently paused. */
  70925. this.isPaused = false;
  70926. this._sounds = [];
  70927. this._weights = [];
  70928. if (sounds.length !== weights.length) {
  70929. throw new Error('Sounds length does not equal weights length');
  70930. }
  70931. this.loop = loop;
  70932. this._weights = weights;
  70933. // Normalize the weights
  70934. var weightSum = 0;
  70935. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  70936. var weight = weights_1[_i];
  70937. weightSum += weight;
  70938. }
  70939. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  70940. for (var i = 0; i < this._weights.length; i++) {
  70941. this._weights[i] *= invWeightSum;
  70942. }
  70943. this._sounds = sounds;
  70944. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  70945. var sound = _b[_a];
  70946. sound.onEndedObservable.add(function () { _this._onended(); });
  70947. }
  70948. }
  70949. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  70950. /**
  70951. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  70952. */
  70953. get: function () {
  70954. return this._coneInnerAngle;
  70955. },
  70956. /**
  70957. * The size of cone in degress for a directional sound in which there will be no attenuation.
  70958. */
  70959. set: function (value) {
  70960. if (value !== this._coneInnerAngle) {
  70961. if (this._coneOuterAngle < value) {
  70962. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70963. return;
  70964. }
  70965. this._coneInnerAngle = value;
  70966. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70967. var sound = _a[_i];
  70968. sound.directionalConeInnerAngle = value;
  70969. }
  70970. }
  70971. },
  70972. enumerable: true,
  70973. configurable: true
  70974. });
  70975. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70976. /**
  70977. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70978. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70979. */
  70980. get: function () {
  70981. return this._coneOuterAngle;
  70982. },
  70983. /**
  70984. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70985. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70986. */
  70987. set: function (value) {
  70988. if (value !== this._coneOuterAngle) {
  70989. if (value < this._coneInnerAngle) {
  70990. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70991. return;
  70992. }
  70993. this._coneOuterAngle = value;
  70994. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70995. var sound = _a[_i];
  70996. sound.directionalConeOuterAngle = value;
  70997. }
  70998. }
  70999. },
  71000. enumerable: true,
  71001. configurable: true
  71002. });
  71003. Object.defineProperty(WeightedSound.prototype, "volume", {
  71004. /**
  71005. * Playback volume.
  71006. */
  71007. get: function () {
  71008. return this._volume;
  71009. },
  71010. /**
  71011. * Playback volume.
  71012. */
  71013. set: function (value) {
  71014. if (value !== this._volume) {
  71015. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  71016. var sound = _a[_i];
  71017. sound.setVolume(value);
  71018. }
  71019. }
  71020. },
  71021. enumerable: true,
  71022. configurable: true
  71023. });
  71024. WeightedSound.prototype._onended = function () {
  71025. if (this._currentIndex !== undefined) {
  71026. this._sounds[this._currentIndex].autoplay = false;
  71027. }
  71028. if (this.loop && this.isPlaying) {
  71029. this.play();
  71030. }
  71031. else {
  71032. this.isPlaying = false;
  71033. }
  71034. };
  71035. /**
  71036. * Suspend playback
  71037. */
  71038. WeightedSound.prototype.pause = function () {
  71039. this.isPaused = true;
  71040. if (this._currentIndex !== undefined) {
  71041. this._sounds[this._currentIndex].pause();
  71042. }
  71043. };
  71044. /**
  71045. * Stop playback
  71046. */
  71047. WeightedSound.prototype.stop = function () {
  71048. this.isPlaying = false;
  71049. if (this._currentIndex !== undefined) {
  71050. this._sounds[this._currentIndex].stop();
  71051. }
  71052. };
  71053. /**
  71054. * Start playback.
  71055. * @param startOffset Position the clip head at a specific time in seconds.
  71056. */
  71057. WeightedSound.prototype.play = function (startOffset) {
  71058. if (!this.isPaused) {
  71059. this.stop();
  71060. var randomValue = Math.random();
  71061. var total = 0;
  71062. for (var i = 0; i < this._weights.length; i++) {
  71063. total += this._weights[i];
  71064. if (randomValue <= total) {
  71065. this._currentIndex = i;
  71066. break;
  71067. }
  71068. }
  71069. }
  71070. var sound = this._sounds[this._currentIndex];
  71071. if (sound.isReady()) {
  71072. sound.play(0, this.isPaused ? undefined : startOffset);
  71073. }
  71074. else {
  71075. sound.autoplay = true;
  71076. }
  71077. this.isPlaying = true;
  71078. this.isPaused = false;
  71079. };
  71080. return WeightedSound;
  71081. }());
  71082. BABYLON.WeightedSound = WeightedSound;
  71083. })(BABYLON || (BABYLON = {}));
  71084. //# sourceMappingURL=babylon.weightedsound.js.map
  71085. var BABYLON;
  71086. (function (BABYLON) {
  71087. // Adds the parser to the scene parsers.
  71088. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  71089. // TODO: add sound
  71090. var loadedSounds = [];
  71091. var loadedSound;
  71092. container.sounds = container.sounds || [];
  71093. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71094. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71095. var parsedSound = parsedData.sounds[index];
  71096. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71097. if (!parsedSound.url) {
  71098. parsedSound.url = parsedSound.name;
  71099. }
  71100. if (!loadedSounds[parsedSound.url]) {
  71101. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71102. loadedSounds[parsedSound.url] = loadedSound;
  71103. container.sounds.push(loadedSound);
  71104. }
  71105. else {
  71106. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71107. }
  71108. }
  71109. else {
  71110. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71111. }
  71112. }
  71113. }
  71114. loadedSounds = [];
  71115. });
  71116. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  71117. get: function () {
  71118. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71119. if (!compo) {
  71120. compo = new AudioSceneComponent(this);
  71121. this._addComponent(compo);
  71122. }
  71123. if (!this._mainSoundTrack) {
  71124. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  71125. }
  71126. return this._mainSoundTrack;
  71127. },
  71128. enumerable: true,
  71129. configurable: true
  71130. });
  71131. BABYLON.Scene.prototype.getSoundByName = function (name) {
  71132. var index;
  71133. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  71134. if (this.mainSoundTrack.soundCollection[index].name === name) {
  71135. return this.mainSoundTrack.soundCollection[index];
  71136. }
  71137. }
  71138. if (this.soundTracks) {
  71139. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  71140. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  71141. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  71142. return this.soundTracks[sdIndex].soundCollection[index];
  71143. }
  71144. }
  71145. }
  71146. }
  71147. return null;
  71148. };
  71149. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  71150. get: function () {
  71151. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71152. if (!compo) {
  71153. compo = new AudioSceneComponent(this);
  71154. this._addComponent(compo);
  71155. }
  71156. return compo.audioEnabled;
  71157. },
  71158. set: function (value) {
  71159. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71160. if (!compo) {
  71161. compo = new AudioSceneComponent(this);
  71162. this._addComponent(compo);
  71163. }
  71164. if (value) {
  71165. compo.enableAudio();
  71166. }
  71167. else {
  71168. compo.disableAudio();
  71169. }
  71170. },
  71171. enumerable: true,
  71172. configurable: true
  71173. });
  71174. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  71175. get: function () {
  71176. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71177. if (!compo) {
  71178. compo = new AudioSceneComponent(this);
  71179. this._addComponent(compo);
  71180. }
  71181. return compo.headphone;
  71182. },
  71183. set: function (value) {
  71184. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  71185. if (!compo) {
  71186. compo = new AudioSceneComponent(this);
  71187. this._addComponent(compo);
  71188. }
  71189. if (value) {
  71190. compo.switchAudioModeForHeadphones();
  71191. }
  71192. else {
  71193. compo.switchAudioModeForNormalSpeakers();
  71194. }
  71195. },
  71196. enumerable: true,
  71197. configurable: true
  71198. });
  71199. /**
  71200. * Defines the sound scene component responsible to manage any sounds
  71201. * in a given scene.
  71202. */
  71203. var AudioSceneComponent = /** @class */ (function () {
  71204. /**
  71205. * Creates a new instance of the component for the given scene
  71206. * @param scene Defines the scene to register the component in
  71207. */
  71208. function AudioSceneComponent(scene) {
  71209. /**
  71210. * The component name helpfull to identify the component in the list of scene components.
  71211. */
  71212. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  71213. this._audioEnabled = true;
  71214. this._headphone = false;
  71215. this.scene = scene;
  71216. scene.soundTracks = new Array();
  71217. scene.sounds = new Array();
  71218. }
  71219. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  71220. /**
  71221. * Gets whether audio is enabled or not.
  71222. * Please use related enable/disable method to switch state.
  71223. */
  71224. get: function () {
  71225. return this._audioEnabled;
  71226. },
  71227. enumerable: true,
  71228. configurable: true
  71229. });
  71230. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  71231. /**
  71232. * Gets whether audio is outputing to headphone or not.
  71233. * Please use the according Switch methods to change output.
  71234. */
  71235. get: function () {
  71236. return this._headphone;
  71237. },
  71238. enumerable: true,
  71239. configurable: true
  71240. });
  71241. /**
  71242. * Registers the component in a given scene
  71243. */
  71244. AudioSceneComponent.prototype.register = function () {
  71245. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  71246. };
  71247. /**
  71248. * Rebuilds the elements related to this component in case of
  71249. * context lost for instance.
  71250. */
  71251. AudioSceneComponent.prototype.rebuild = function () {
  71252. // Nothing to do here. (Not rendering related)
  71253. };
  71254. /**
  71255. * Serializes the component data to the specified json object
  71256. * @param serializationObject The object to serialize to
  71257. */
  71258. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  71259. serializationObject.sounds = [];
  71260. if (this.scene.soundTracks) {
  71261. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  71262. var soundtrack = this.scene.soundTracks[index];
  71263. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71264. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71265. }
  71266. }
  71267. }
  71268. };
  71269. /**
  71270. * Adds all the element from the container to the scene
  71271. * @param container the container holding the elements
  71272. */
  71273. AudioSceneComponent.prototype.addFromContainer = function (container) {
  71274. var _this = this;
  71275. if (!container.sounds) {
  71276. return;
  71277. }
  71278. container.sounds.forEach(function (sound) {
  71279. sound.play();
  71280. sound.autoplay = true;
  71281. _this.scene.mainSoundTrack.AddSound(sound);
  71282. });
  71283. };
  71284. /**
  71285. * Removes all the elements in the container from the scene
  71286. * @param container contains the elements to remove
  71287. */
  71288. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  71289. var _this = this;
  71290. if (!container.sounds) {
  71291. return;
  71292. }
  71293. container.sounds.forEach(function (sound) {
  71294. sound.stop();
  71295. sound.autoplay = false;
  71296. _this.scene.mainSoundTrack.RemoveSound(sound);
  71297. });
  71298. };
  71299. /**
  71300. * Disposes the component and the associated ressources.
  71301. */
  71302. AudioSceneComponent.prototype.dispose = function () {
  71303. var scene = this.scene;
  71304. if (scene._mainSoundTrack) {
  71305. scene.mainSoundTrack.dispose();
  71306. }
  71307. if (scene.soundTracks) {
  71308. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  71309. scene.soundTracks[scIndex].dispose();
  71310. }
  71311. }
  71312. };
  71313. /**
  71314. * Disables audio in the associated scene.
  71315. */
  71316. AudioSceneComponent.prototype.disableAudio = function () {
  71317. var scene = this.scene;
  71318. this._audioEnabled = false;
  71319. var i;
  71320. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71321. scene.mainSoundTrack.soundCollection[i].pause();
  71322. }
  71323. if (scene.soundTracks) {
  71324. for (i = 0; i < scene.soundTracks.length; i++) {
  71325. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71326. scene.soundTracks[i].soundCollection[j].pause();
  71327. }
  71328. }
  71329. }
  71330. };
  71331. /**
  71332. * Enables audio in the associated scene.
  71333. */
  71334. AudioSceneComponent.prototype.enableAudio = function () {
  71335. var scene = this.scene;
  71336. this._audioEnabled = true;
  71337. var i;
  71338. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71339. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  71340. scene.mainSoundTrack.soundCollection[i].play();
  71341. }
  71342. }
  71343. if (scene.soundTracks) {
  71344. for (i = 0; i < scene.soundTracks.length; i++) {
  71345. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71346. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  71347. scene.soundTracks[i].soundCollection[j].play();
  71348. }
  71349. }
  71350. }
  71351. }
  71352. };
  71353. /**
  71354. * Switch audio to headphone output.
  71355. */
  71356. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  71357. var scene = this.scene;
  71358. this._headphone = true;
  71359. scene.mainSoundTrack.switchPanningModelToHRTF();
  71360. if (scene.soundTracks) {
  71361. for (var i = 0; i < scene.soundTracks.length; i++) {
  71362. scene.soundTracks[i].switchPanningModelToHRTF();
  71363. }
  71364. }
  71365. };
  71366. /**
  71367. * Switch audio to normal speakers.
  71368. */
  71369. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  71370. var scene = this.scene;
  71371. this._headphone = false;
  71372. scene.mainSoundTrack.switchPanningModelToEqualPower();
  71373. if (scene.soundTracks) {
  71374. for (var i = 0; i < scene.soundTracks.length; i++) {
  71375. scene.soundTracks[i].switchPanningModelToEqualPower();
  71376. }
  71377. }
  71378. };
  71379. AudioSceneComponent.prototype._afterRender = function () {
  71380. var scene = this.scene;
  71381. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  71382. return;
  71383. }
  71384. var listeningCamera;
  71385. var audioEngine = BABYLON.Engine.audioEngine;
  71386. if (scene.activeCameras.length > 0) {
  71387. listeningCamera = scene.activeCameras[0];
  71388. }
  71389. else {
  71390. listeningCamera = scene.activeCamera;
  71391. }
  71392. if (listeningCamera && audioEngine.audioContext) {
  71393. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  71394. // for VR cameras
  71395. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  71396. listeningCamera = listeningCamera.rigCameras[0];
  71397. }
  71398. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  71399. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  71400. cameraDirection.normalize();
  71401. // To avoid some errors on GearVR
  71402. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  71403. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  71404. }
  71405. var i;
  71406. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71407. var sound = scene.mainSoundTrack.soundCollection[i];
  71408. if (sound.useCustomAttenuation) {
  71409. sound.updateDistanceFromListener();
  71410. }
  71411. }
  71412. if (scene.soundTracks) {
  71413. for (i = 0; i < scene.soundTracks.length; i++) {
  71414. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71415. sound = scene.soundTracks[i].soundCollection[j];
  71416. if (sound.useCustomAttenuation) {
  71417. sound.updateDistanceFromListener();
  71418. }
  71419. }
  71420. }
  71421. }
  71422. }
  71423. };
  71424. return AudioSceneComponent;
  71425. }());
  71426. BABYLON.AudioSceneComponent = AudioSceneComponent;
  71427. })(BABYLON || (BABYLON = {}));
  71428. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  71429. var BABYLON;
  71430. (function (BABYLON) {
  71431. /**
  71432. * This defines an action helpful to play a defined sound on a triggered action.
  71433. */
  71434. var PlaySoundAction = /** @class */ (function (_super) {
  71435. __extends(PlaySoundAction, _super);
  71436. /**
  71437. * Instantiate the action
  71438. * @param triggerOptions defines the trigger options
  71439. * @param sound defines the sound to play
  71440. * @param condition defines the trigger related conditions
  71441. */
  71442. function PlaySoundAction(triggerOptions, sound, condition) {
  71443. var _this = _super.call(this, triggerOptions, condition) || this;
  71444. _this._sound = sound;
  71445. return _this;
  71446. }
  71447. /** @hidden */
  71448. PlaySoundAction.prototype._prepare = function () {
  71449. };
  71450. /**
  71451. * Execute the action and play the sound.
  71452. */
  71453. PlaySoundAction.prototype.execute = function () {
  71454. if (this._sound !== undefined) {
  71455. this._sound.play();
  71456. }
  71457. };
  71458. /**
  71459. * Serializes the actions and its related information.
  71460. * @param parent defines the object to serialize in
  71461. * @returns the serialized object
  71462. */
  71463. PlaySoundAction.prototype.serialize = function (parent) {
  71464. return _super.prototype._serialize.call(this, {
  71465. name: "PlaySoundAction",
  71466. properties: [{ name: "sound", value: this._sound.name }]
  71467. }, parent);
  71468. };
  71469. return PlaySoundAction;
  71470. }(BABYLON.Action));
  71471. BABYLON.PlaySoundAction = PlaySoundAction;
  71472. /**
  71473. * This defines an action helpful to stop a defined sound on a triggered action.
  71474. */
  71475. var StopSoundAction = /** @class */ (function (_super) {
  71476. __extends(StopSoundAction, _super);
  71477. /**
  71478. * Instantiate the action
  71479. * @param triggerOptions defines the trigger options
  71480. * @param sound defines the sound to stop
  71481. * @param condition defines the trigger related conditions
  71482. */
  71483. function StopSoundAction(triggerOptions, sound, condition) {
  71484. var _this = _super.call(this, triggerOptions, condition) || this;
  71485. _this._sound = sound;
  71486. return _this;
  71487. }
  71488. /** @hidden */
  71489. StopSoundAction.prototype._prepare = function () {
  71490. };
  71491. /**
  71492. * Execute the action and stop the sound.
  71493. */
  71494. StopSoundAction.prototype.execute = function () {
  71495. if (this._sound !== undefined) {
  71496. this._sound.stop();
  71497. }
  71498. };
  71499. /**
  71500. * Serializes the actions and its related information.
  71501. * @param parent defines the object to serialize in
  71502. * @returns the serialized object
  71503. */
  71504. StopSoundAction.prototype.serialize = function (parent) {
  71505. return _super.prototype._serialize.call(this, {
  71506. name: "StopSoundAction",
  71507. properties: [{ name: "sound", value: this._sound.name }]
  71508. }, parent);
  71509. };
  71510. return StopSoundAction;
  71511. }(BABYLON.Action));
  71512. BABYLON.StopSoundAction = StopSoundAction;
  71513. })(BABYLON || (BABYLON = {}));
  71514. //# sourceMappingURL=babylon.directAudioActions.js.map
  71515. var BABYLON;
  71516. (function (BABYLON) {
  71517. /**
  71518. * Class for creating a cube texture
  71519. */
  71520. var CubeTexture = /** @class */ (function (_super) {
  71521. __extends(CubeTexture, _super);
  71522. /**
  71523. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  71524. * as prefiltered data.
  71525. * @param rootUrl defines the url of the texture or the root name of the six images
  71526. * @param scene defines the scene the texture is attached to
  71527. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  71528. * @param noMipmap defines if mipmaps should be created or not
  71529. * @param files defines the six files to load for the different faces
  71530. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  71531. * @param onError defines a callback triggered in case of error during load
  71532. * @param format defines the internal format to use for the texture once loaded
  71533. * @param prefiltered defines whether or not the texture is created from prefiltered data
  71534. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  71535. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71536. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71537. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71538. * @return the cube texture
  71539. */
  71540. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  71541. if (extensions === void 0) { extensions = null; }
  71542. if (noMipmap === void 0) { noMipmap = false; }
  71543. if (files === void 0) { files = null; }
  71544. if (onLoad === void 0) { onLoad = null; }
  71545. if (onError === void 0) { onError = null; }
  71546. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71547. if (prefiltered === void 0) { prefiltered = false; }
  71548. if (forcedExtension === void 0) { forcedExtension = null; }
  71549. if (createPolynomials === void 0) { createPolynomials = false; }
  71550. if (lodScale === void 0) { lodScale = 0.8; }
  71551. if (lodOffset === void 0) { lodOffset = 0; }
  71552. var _this = _super.call(this, scene) || this;
  71553. /**
  71554. * Gets or sets the center of the bounding box associated with the cube texture.
  71555. * It must define where the camera used to render the texture was set
  71556. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71557. */
  71558. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71559. _this._rotationY = 0;
  71560. /** @hidden */
  71561. _this._prefiltered = false;
  71562. _this.name = rootUrl;
  71563. _this.url = rootUrl;
  71564. _this._noMipmap = noMipmap;
  71565. _this.hasAlpha = false;
  71566. _this._format = format;
  71567. _this.isCube = true;
  71568. _this._textureMatrix = BABYLON.Matrix.Identity();
  71569. _this._createPolynomials = createPolynomials;
  71570. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71571. if (!rootUrl && !files) {
  71572. return _this;
  71573. }
  71574. var lastDot = rootUrl.lastIndexOf(".");
  71575. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  71576. var isDDS = (extension === ".dds");
  71577. var isEnv = (extension === ".env");
  71578. if (isEnv) {
  71579. _this.gammaSpace = false;
  71580. _this._prefiltered = false;
  71581. }
  71582. else {
  71583. _this._prefiltered = prefiltered;
  71584. if (prefiltered) {
  71585. _this.gammaSpace = false;
  71586. }
  71587. }
  71588. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  71589. if (!files) {
  71590. if (!isEnv && !isDDS && !extensions) {
  71591. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  71592. }
  71593. files = [];
  71594. if (extensions) {
  71595. for (var index = 0; index < extensions.length; index++) {
  71596. files.push(rootUrl + extensions[index]);
  71597. }
  71598. }
  71599. }
  71600. _this._files = files;
  71601. if (!_this._texture) {
  71602. if (!scene.useDelayedTextureLoading) {
  71603. if (prefiltered) {
  71604. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  71605. }
  71606. else {
  71607. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  71608. }
  71609. }
  71610. else {
  71611. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71612. }
  71613. }
  71614. else if (onLoad) {
  71615. if (_this._texture.isReady) {
  71616. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  71617. }
  71618. else {
  71619. _this._texture.onLoadedObservable.add(onLoad);
  71620. }
  71621. }
  71622. return _this;
  71623. }
  71624. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  71625. /**
  71626. * Returns the bounding box size
  71627. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71628. */
  71629. get: function () {
  71630. return this._boundingBoxSize;
  71631. },
  71632. /**
  71633. * Gets or sets the size of the bounding box associated with the cube texture
  71634. * When defined, the cubemap will switch to local mode
  71635. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71636. * @example https://www.babylonjs-playground.com/#RNASML
  71637. */
  71638. set: function (value) {
  71639. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71640. return;
  71641. }
  71642. this._boundingBoxSize = value;
  71643. var scene = this.getScene();
  71644. if (scene) {
  71645. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71646. }
  71647. },
  71648. enumerable: true,
  71649. configurable: true
  71650. });
  71651. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  71652. /**
  71653. * Gets texture matrix rotation angle around Y axis radians.
  71654. */
  71655. get: function () {
  71656. return this._rotationY;
  71657. },
  71658. /**
  71659. * Sets texture matrix rotation angle around Y axis in radians.
  71660. */
  71661. set: function (value) {
  71662. this._rotationY = value;
  71663. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  71664. },
  71665. enumerable: true,
  71666. configurable: true
  71667. });
  71668. /**
  71669. * Creates a cube texture from an array of image urls
  71670. * @param files defines an array of image urls
  71671. * @param scene defines the hosting scene
  71672. * @param noMipmap specifies if mip maps are not used
  71673. * @returns a cube texture
  71674. */
  71675. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  71676. var rootUrlKey = "";
  71677. files.forEach(function (url) { return rootUrlKey += url; });
  71678. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  71679. };
  71680. /**
  71681. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  71682. * @param url defines the url of the prefiltered texture
  71683. * @param scene defines the scene the texture is attached to
  71684. * @param forcedExtension defines the extension of the file if different from the url
  71685. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71686. * @return the prefiltered texture
  71687. */
  71688. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  71689. if (forcedExtension === void 0) { forcedExtension = null; }
  71690. if (createPolynomials === void 0) { createPolynomials = true; }
  71691. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  71692. };
  71693. /**
  71694. * Delays loading of the cube texture
  71695. */
  71696. CubeTexture.prototype.delayLoad = function () {
  71697. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71698. return;
  71699. }
  71700. var scene = this.getScene();
  71701. if (!scene) {
  71702. return;
  71703. }
  71704. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71705. this._texture = this._getFromCache(this.url, this._noMipmap);
  71706. if (!this._texture) {
  71707. if (this._prefiltered) {
  71708. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  71709. }
  71710. else {
  71711. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  71712. }
  71713. }
  71714. };
  71715. /**
  71716. * Returns the reflection texture matrix
  71717. * @returns the reflection texture matrix
  71718. */
  71719. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  71720. return this._textureMatrix;
  71721. };
  71722. /**
  71723. * Sets the reflection texture matrix
  71724. * @param value Reflection texture matrix
  71725. */
  71726. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71727. this._textureMatrix = value;
  71728. };
  71729. /**
  71730. * Parses text to create a cube texture
  71731. * @param parsedTexture define the serialized text to read from
  71732. * @param scene defines the hosting scene
  71733. * @param rootUrl defines the root url of the cube texture
  71734. * @returns a cube texture
  71735. */
  71736. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71737. var texture = BABYLON.SerializationHelper.Parse(function () {
  71738. var prefiltered = false;
  71739. if (parsedTexture.prefiltered) {
  71740. prefiltered = parsedTexture.prefiltered;
  71741. }
  71742. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  71743. }, parsedTexture, scene);
  71744. // Local Cubemaps
  71745. if (parsedTexture.boundingBoxPosition) {
  71746. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  71747. }
  71748. if (parsedTexture.boundingBoxSize) {
  71749. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  71750. }
  71751. // Animations
  71752. if (parsedTexture.animations) {
  71753. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  71754. var parsedAnimation = parsedTexture.animations[animationIndex];
  71755. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71756. }
  71757. }
  71758. return texture;
  71759. };
  71760. /**
  71761. * Makes a clone, or deep copy, of the cube texture
  71762. * @returns a new cube texture
  71763. */
  71764. CubeTexture.prototype.clone = function () {
  71765. var _this = this;
  71766. return BABYLON.SerializationHelper.Clone(function () {
  71767. var scene = _this.getScene();
  71768. if (!scene) {
  71769. return _this;
  71770. }
  71771. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  71772. }, this);
  71773. };
  71774. __decorate([
  71775. BABYLON.serialize("rotationY")
  71776. ], CubeTexture.prototype, "rotationY", null);
  71777. return CubeTexture;
  71778. }(BABYLON.BaseTexture));
  71779. BABYLON.CubeTexture = CubeTexture;
  71780. })(BABYLON || (BABYLON = {}));
  71781. //# sourceMappingURL=babylon.cubeTexture.js.map
  71782. var BABYLON;
  71783. (function (BABYLON) {
  71784. /**
  71785. * Raw cube texture where the raw buffers are passed in
  71786. */
  71787. var RawCubeTexture = /** @class */ (function (_super) {
  71788. __extends(RawCubeTexture, _super);
  71789. /**
  71790. * Creates a cube texture where the raw buffers are passed in.
  71791. * @param scene defines the scene the texture is attached to
  71792. * @param data defines the array of data to use to create each face
  71793. * @param size defines the size of the textures
  71794. * @param format defines the format of the data
  71795. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  71796. * @param generateMipMaps defines if the engine should generate the mip levels
  71797. * @param invertY defines if data must be stored with Y axis inverted
  71798. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  71799. * @param compression defines the compression used (null by default)
  71800. */
  71801. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  71802. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71803. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71804. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71805. if (invertY === void 0) { invertY = false; }
  71806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71807. if (compression === void 0) { compression = null; }
  71808. var _this = _super.call(this, "", scene) || this;
  71809. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  71810. return _this;
  71811. }
  71812. /**
  71813. * Updates the raw cube texture.
  71814. * @param data defines the data to store
  71815. * @param format defines the data format
  71816. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  71817. * @param invertY defines if data must be stored with Y axis inverted
  71818. * @param compression defines the compression used (null by default)
  71819. * @param level defines which level of the texture to update
  71820. */
  71821. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  71822. if (compression === void 0) { compression = null; }
  71823. if (level === void 0) { level = 0; }
  71824. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  71825. };
  71826. /**
  71827. * Updates a raw cube texture with RGBD encoded data.
  71828. * @param data defines the array of data [mipmap][face] to use to create each face
  71829. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  71830. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71831. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71832. * @returns a promsie that resolves when the operation is complete
  71833. */
  71834. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  71835. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  71836. if (lodScale === void 0) { lodScale = 0.8; }
  71837. if (lodOffset === void 0) { lodOffset = 0; }
  71838. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  71839. };
  71840. /**
  71841. * Clones the raw cube texture.
  71842. * @return a new cube texture
  71843. */
  71844. RawCubeTexture.prototype.clone = function () {
  71845. var _this = this;
  71846. return BABYLON.SerializationHelper.Clone(function () {
  71847. var scene = _this.getScene();
  71848. var internalTexture = _this._texture;
  71849. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  71850. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  71851. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  71852. }
  71853. return texture;
  71854. }, this);
  71855. };
  71856. /** @hidden */
  71857. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  71858. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  71859. internalTexture._bufferViewArrayArray = data;
  71860. internalTexture._lodGenerationScale = lodScale;
  71861. internalTexture._lodGenerationOffset = lodOffset;
  71862. internalTexture._sphericalPolynomial = sphericalPolynomial;
  71863. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  71864. internalTexture.isReady = true;
  71865. });
  71866. };
  71867. return RawCubeTexture;
  71868. }(BABYLON.CubeTexture));
  71869. BABYLON.RawCubeTexture = RawCubeTexture;
  71870. })(BABYLON || (BABYLON = {}));
  71871. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  71872. var BABYLON;
  71873. (function (BABYLON) {
  71874. /**
  71875. * This Helps creating a texture that will be created from a camera in your scene.
  71876. * It is basically a dynamic texture that could be used to create special effects for instance.
  71877. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  71878. */
  71879. var RenderTargetTexture = /** @class */ (function (_super) {
  71880. __extends(RenderTargetTexture, _super);
  71881. /**
  71882. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  71883. * or used a shadow, depth texture...
  71884. * @param name The friendly name of the texture
  71885. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  71886. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  71887. * @param generateMipMaps True if mip maps need to be generated after render.
  71888. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  71889. * @param type The type of the buffer in the RTT (int, half float, float...)
  71890. * @param isCube True if a cube texture needs to be created
  71891. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  71892. * @param generateDepthBuffer True to generate a depth buffer
  71893. * @param generateStencilBuffer True to generate a stencil buffer
  71894. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  71895. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  71896. */
  71897. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  71898. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  71899. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71900. if (isCube === void 0) { isCube = false; }
  71901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71902. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71903. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  71904. if (isMulti === void 0) { isMulti = false; }
  71905. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71906. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71907. _this.isCube = isCube;
  71908. /**
  71909. * Define if particles should be rendered in your texture.
  71910. */
  71911. _this.renderParticles = true;
  71912. /**
  71913. * Define if sprites should be rendered in your texture.
  71914. */
  71915. _this.renderSprites = false;
  71916. /**
  71917. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  71918. */
  71919. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  71920. /**
  71921. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  71922. */
  71923. _this.ignoreCameraViewport = false;
  71924. /**
  71925. * An event triggered when the texture is unbind.
  71926. */
  71927. _this.onBeforeBindObservable = new BABYLON.Observable();
  71928. /**
  71929. * An event triggered when the texture is unbind.
  71930. */
  71931. _this.onAfterUnbindObservable = new BABYLON.Observable();
  71932. /**
  71933. * An event triggered before rendering the texture
  71934. */
  71935. _this.onBeforeRenderObservable = new BABYLON.Observable();
  71936. /**
  71937. * An event triggered after rendering the texture
  71938. */
  71939. _this.onAfterRenderObservable = new BABYLON.Observable();
  71940. /**
  71941. * An event triggered after the texture clear
  71942. */
  71943. _this.onClearObservable = new BABYLON.Observable();
  71944. _this._currentRefreshId = -1;
  71945. _this._refreshRate = 1;
  71946. _this._samples = 1;
  71947. /**
  71948. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  71949. * It must define where the camera used to render the texture is set
  71950. */
  71951. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71952. scene = _this.getScene();
  71953. if (!scene) {
  71954. return _this;
  71955. }
  71956. _this.renderList = new Array();
  71957. _this._engine = scene.getEngine();
  71958. _this.name = name;
  71959. _this.isRenderTarget = true;
  71960. _this._initialSizeParameter = size;
  71961. _this._processSizeParameter(size);
  71962. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  71963. });
  71964. _this._generateMipMaps = generateMipMaps ? true : false;
  71965. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  71966. // Rendering groups
  71967. _this._renderingManager = new BABYLON.RenderingManager(scene);
  71968. _this._renderingManager._useSceneAutoClearSetup = true;
  71969. if (isMulti) {
  71970. return _this;
  71971. }
  71972. _this._renderTargetOptions = {
  71973. generateMipMaps: generateMipMaps,
  71974. type: type,
  71975. format: format,
  71976. samplingMode: samplingMode,
  71977. generateDepthBuffer: generateDepthBuffer,
  71978. generateStencilBuffer: generateStencilBuffer
  71979. };
  71980. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  71981. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71982. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71983. }
  71984. if (isCube) {
  71985. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  71986. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  71987. _this._textureMatrix = BABYLON.Matrix.Identity();
  71988. }
  71989. else {
  71990. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  71991. }
  71992. return _this;
  71993. }
  71994. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71995. /**
  71996. * Use this list to define the list of mesh you want to render.
  71997. */
  71998. get: function () {
  71999. return this._renderList;
  72000. },
  72001. set: function (value) {
  72002. this._renderList = value;
  72003. if (this._renderList) {
  72004. this._hookArray(this._renderList);
  72005. }
  72006. },
  72007. enumerable: true,
  72008. configurable: true
  72009. });
  72010. RenderTargetTexture.prototype._hookArray = function (array) {
  72011. var _this = this;
  72012. var oldPush = array.push;
  72013. array.push = function () {
  72014. var items = [];
  72015. for (var _i = 0; _i < arguments.length; _i++) {
  72016. items[_i] = arguments[_i];
  72017. }
  72018. var wasEmpty = array.length === 0;
  72019. var result = oldPush.apply(array, items);
  72020. if (wasEmpty) {
  72021. _this.getScene().meshes.forEach(function (mesh) {
  72022. mesh._markSubMeshesAsLightDirty();
  72023. });
  72024. }
  72025. return result;
  72026. };
  72027. var oldSplice = array.splice;
  72028. array.splice = function (index, deleteCount) {
  72029. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72030. if (array.length === 0) {
  72031. _this.getScene().meshes.forEach(function (mesh) {
  72032. mesh._markSubMeshesAsLightDirty();
  72033. });
  72034. }
  72035. return deleted;
  72036. };
  72037. };
  72038. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  72039. /**
  72040. * Set a after unbind callback in the texture.
  72041. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  72042. */
  72043. set: function (callback) {
  72044. if (this._onAfterUnbindObserver) {
  72045. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  72046. }
  72047. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  72048. },
  72049. enumerable: true,
  72050. configurable: true
  72051. });
  72052. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  72053. /**
  72054. * Set a before render callback in the texture.
  72055. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  72056. */
  72057. set: function (callback) {
  72058. if (this._onBeforeRenderObserver) {
  72059. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  72060. }
  72061. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  72062. },
  72063. enumerable: true,
  72064. configurable: true
  72065. });
  72066. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  72067. /**
  72068. * Set a after render callback in the texture.
  72069. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  72070. */
  72071. set: function (callback) {
  72072. if (this._onAfterRenderObserver) {
  72073. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  72074. }
  72075. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  72076. },
  72077. enumerable: true,
  72078. configurable: true
  72079. });
  72080. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  72081. /**
  72082. * Set a clear callback in the texture.
  72083. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  72084. */
  72085. set: function (callback) {
  72086. if (this._onClearObserver) {
  72087. this.onClearObservable.remove(this._onClearObserver);
  72088. }
  72089. this._onClearObserver = this.onClearObservable.add(callback);
  72090. },
  72091. enumerable: true,
  72092. configurable: true
  72093. });
  72094. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  72095. /**
  72096. * Gets render target creation options that were used.
  72097. */
  72098. get: function () {
  72099. return this._renderTargetOptions;
  72100. },
  72101. enumerable: true,
  72102. configurable: true
  72103. });
  72104. RenderTargetTexture.prototype._onRatioRescale = function () {
  72105. if (this._sizeRatio) {
  72106. this.resize(this._initialSizeParameter);
  72107. }
  72108. };
  72109. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  72110. get: function () {
  72111. return this._boundingBoxSize;
  72112. },
  72113. /**
  72114. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  72115. * When defined, the cubemap will switch to local mode
  72116. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72117. * @example https://www.babylonjs-playground.com/#RNASML
  72118. */
  72119. set: function (value) {
  72120. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72121. return;
  72122. }
  72123. this._boundingBoxSize = value;
  72124. var scene = this.getScene();
  72125. if (scene) {
  72126. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72127. }
  72128. },
  72129. enumerable: true,
  72130. configurable: true
  72131. });
  72132. /**
  72133. * Creates a depth stencil texture.
  72134. * This is only available in WebGL 2 or with the depth texture extension available.
  72135. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  72136. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  72137. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  72138. */
  72139. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  72140. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  72141. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  72142. if (generateStencil === void 0) { generateStencil = false; }
  72143. if (!this.getScene()) {
  72144. return;
  72145. }
  72146. var engine = this.getScene().getEngine();
  72147. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  72148. bilinearFiltering: bilinearFiltering,
  72149. comparisonFunction: comparisonFunction,
  72150. generateStencil: generateStencil,
  72151. isCube: this.isCube
  72152. });
  72153. engine.setFrameBufferDepthStencilTexture(this);
  72154. };
  72155. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  72156. if (size.ratio) {
  72157. this._sizeRatio = size.ratio;
  72158. this._size = {
  72159. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  72160. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  72161. };
  72162. }
  72163. else {
  72164. this._size = size;
  72165. }
  72166. };
  72167. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  72168. /**
  72169. * Define the number of samples to use in case of MSAA.
  72170. * It defaults to one meaning no MSAA has been enabled.
  72171. */
  72172. get: function () {
  72173. return this._samples;
  72174. },
  72175. set: function (value) {
  72176. if (this._samples === value) {
  72177. return;
  72178. }
  72179. var scene = this.getScene();
  72180. if (!scene) {
  72181. return;
  72182. }
  72183. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  72184. },
  72185. enumerable: true,
  72186. configurable: true
  72187. });
  72188. /**
  72189. * Resets the refresh counter of the texture and start bak from scratch.
  72190. * Could be usefull to regenerate the texture if it is setup to render only once.
  72191. */
  72192. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  72193. this._currentRefreshId = -1;
  72194. };
  72195. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  72196. /**
  72197. * Define the refresh rate of the texture or the rendering frequency.
  72198. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72199. */
  72200. get: function () {
  72201. return this._refreshRate;
  72202. },
  72203. set: function (value) {
  72204. this._refreshRate = value;
  72205. this.resetRefreshCounter();
  72206. },
  72207. enumerable: true,
  72208. configurable: true
  72209. });
  72210. /**
  72211. * Adds a post process to the render target rendering passes.
  72212. * @param postProcess define the post process to add
  72213. */
  72214. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  72215. if (!this._postProcessManager) {
  72216. var scene = this.getScene();
  72217. if (!scene) {
  72218. return;
  72219. }
  72220. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  72221. this._postProcesses = new Array();
  72222. }
  72223. this._postProcesses.push(postProcess);
  72224. this._postProcesses[0].autoClear = false;
  72225. };
  72226. /**
  72227. * Clear all the post processes attached to the render target
  72228. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  72229. */
  72230. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  72231. if (dispose === void 0) { dispose = false; }
  72232. if (!this._postProcesses) {
  72233. return;
  72234. }
  72235. if (dispose) {
  72236. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  72237. var postProcess = _a[_i];
  72238. postProcess.dispose();
  72239. }
  72240. }
  72241. this._postProcesses = [];
  72242. };
  72243. /**
  72244. * Remove one of the post process from the list of attached post processes to the texture
  72245. * @param postProcess define the post process to remove from the list
  72246. */
  72247. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  72248. if (!this._postProcesses) {
  72249. return;
  72250. }
  72251. var index = this._postProcesses.indexOf(postProcess);
  72252. if (index === -1) {
  72253. return;
  72254. }
  72255. this._postProcesses.splice(index, 1);
  72256. if (this._postProcesses.length > 0) {
  72257. this._postProcesses[0].autoClear = false;
  72258. }
  72259. };
  72260. /** @hidden */
  72261. RenderTargetTexture.prototype._shouldRender = function () {
  72262. if (this._currentRefreshId === -1) { // At least render once
  72263. this._currentRefreshId = 1;
  72264. return true;
  72265. }
  72266. if (this.refreshRate === this._currentRefreshId) {
  72267. this._currentRefreshId = 1;
  72268. return true;
  72269. }
  72270. this._currentRefreshId++;
  72271. return false;
  72272. };
  72273. /**
  72274. * Gets the actual render size of the texture.
  72275. * @returns the width of the render size
  72276. */
  72277. RenderTargetTexture.prototype.getRenderSize = function () {
  72278. return this.getRenderWidth();
  72279. };
  72280. /**
  72281. * Gets the actual render width of the texture.
  72282. * @returns the width of the render size
  72283. */
  72284. RenderTargetTexture.prototype.getRenderWidth = function () {
  72285. if (this._size.width) {
  72286. return this._size.width;
  72287. }
  72288. return this._size;
  72289. };
  72290. /**
  72291. * Gets the actual render height of the texture.
  72292. * @returns the height of the render size
  72293. */
  72294. RenderTargetTexture.prototype.getRenderHeight = function () {
  72295. if (this._size.width) {
  72296. return this._size.height;
  72297. }
  72298. return this._size;
  72299. };
  72300. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  72301. /**
  72302. * Get if the texture can be rescaled or not.
  72303. */
  72304. get: function () {
  72305. return true;
  72306. },
  72307. enumerable: true,
  72308. configurable: true
  72309. });
  72310. /**
  72311. * Resize the texture using a ratio.
  72312. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  72313. */
  72314. RenderTargetTexture.prototype.scale = function (ratio) {
  72315. var newSize = this.getRenderSize() * ratio;
  72316. this.resize(newSize);
  72317. };
  72318. /**
  72319. * Get the texture reflection matrix used to rotate/transform the reflection.
  72320. * @returns the reflection matrix
  72321. */
  72322. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  72323. if (this.isCube) {
  72324. return this._textureMatrix;
  72325. }
  72326. return _super.prototype.getReflectionTextureMatrix.call(this);
  72327. };
  72328. /**
  72329. * Resize the texture to a new desired size.
  72330. * Be carrefull as it will recreate all the data in the new texture.
  72331. * @param size Define the new size. It can be:
  72332. * - a number for squared texture,
  72333. * - an object containing { width: number, height: number }
  72334. * - or an object containing a ratio { ratio: number }
  72335. */
  72336. RenderTargetTexture.prototype.resize = function (size) {
  72337. this.releaseInternalTexture();
  72338. var scene = this.getScene();
  72339. if (!scene) {
  72340. return;
  72341. }
  72342. this._processSizeParameter(size);
  72343. if (this.isCube) {
  72344. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  72345. }
  72346. else {
  72347. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  72348. }
  72349. };
  72350. /**
  72351. * Renders all the objects from the render list into the texture.
  72352. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  72353. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  72354. */
  72355. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  72356. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  72357. if (dumpForDebug === void 0) { dumpForDebug = false; }
  72358. var scene = this.getScene();
  72359. if (!scene) {
  72360. return;
  72361. }
  72362. var engine = scene.getEngine();
  72363. if (this.useCameraPostProcesses !== undefined) {
  72364. useCameraPostProcess = this.useCameraPostProcesses;
  72365. }
  72366. if (this._waitingRenderList) {
  72367. this.renderList = [];
  72368. for (var index = 0; index < this._waitingRenderList.length; index++) {
  72369. var id = this._waitingRenderList[index];
  72370. var mesh_1 = scene.getMeshByID(id);
  72371. if (mesh_1) {
  72372. this.renderList.push(mesh_1);
  72373. }
  72374. }
  72375. delete this._waitingRenderList;
  72376. }
  72377. // Is predicate defined?
  72378. if (this.renderListPredicate) {
  72379. if (this.renderList) {
  72380. this.renderList.splice(0); // Clear previous renderList
  72381. }
  72382. else {
  72383. this.renderList = [];
  72384. }
  72385. var scene = this.getScene();
  72386. if (!scene) {
  72387. return;
  72388. }
  72389. var sceneMeshes = scene.meshes;
  72390. for (var index = 0; index < sceneMeshes.length; index++) {
  72391. var mesh = sceneMeshes[index];
  72392. if (this.renderListPredicate(mesh)) {
  72393. this.renderList.push(mesh);
  72394. }
  72395. }
  72396. }
  72397. this.onBeforeBindObservable.notifyObservers(this);
  72398. // Set custom projection.
  72399. // Needs to be before binding to prevent changing the aspect ratio.
  72400. var camera;
  72401. if (this.activeCamera) {
  72402. camera = this.activeCamera;
  72403. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72404. if (this.activeCamera !== scene.activeCamera) {
  72405. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  72406. }
  72407. }
  72408. else {
  72409. camera = scene.activeCamera;
  72410. if (camera) {
  72411. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72412. }
  72413. }
  72414. // Prepare renderingManager
  72415. this._renderingManager.reset();
  72416. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  72417. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  72418. var sceneRenderId = scene.getRenderId();
  72419. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  72420. var mesh = currentRenderList[meshIndex];
  72421. if (mesh) {
  72422. if (!mesh.isReady(this.refreshRate === 0)) {
  72423. this.resetRefreshCounter();
  72424. continue;
  72425. }
  72426. mesh._preActivateForIntermediateRendering(sceneRenderId);
  72427. var isMasked = void 0;
  72428. if (!this.renderList && camera) {
  72429. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  72430. }
  72431. else {
  72432. isMasked = false;
  72433. }
  72434. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  72435. mesh._activate(sceneRenderId);
  72436. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  72437. var subMesh = mesh.subMeshes[subIndex];
  72438. scene._activeIndices.addCount(subMesh.indexCount, false);
  72439. this._renderingManager.dispatch(subMesh, mesh);
  72440. }
  72441. }
  72442. }
  72443. }
  72444. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  72445. var particleSystem = scene.particleSystems[particleIndex];
  72446. var emitter = particleSystem.emitter;
  72447. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  72448. continue;
  72449. }
  72450. if (currentRenderList.indexOf(emitter) >= 0) {
  72451. this._renderingManager.dispatchParticles(particleSystem);
  72452. }
  72453. }
  72454. if (this.isCube) {
  72455. for (var face = 0; face < 6; face++) {
  72456. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72457. scene.incrementRenderId();
  72458. scene.resetCachedMaterial();
  72459. }
  72460. }
  72461. else {
  72462. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72463. }
  72464. this.onAfterUnbindObservable.notifyObservers(this);
  72465. if (scene.activeCamera) {
  72466. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  72467. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  72468. }
  72469. engine.setViewport(scene.activeCamera.viewport);
  72470. }
  72471. scene.resetCachedMaterial();
  72472. };
  72473. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  72474. var minimum = 128;
  72475. var x = renderDimension * scale;
  72476. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  72477. // Ensure we don't exceed the render dimension (while staying POT)
  72478. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  72479. };
  72480. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72481. var _this = this;
  72482. if (!this._texture) {
  72483. return;
  72484. }
  72485. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  72486. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72487. });
  72488. };
  72489. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  72490. var scene = this.getScene();
  72491. if (!scene) {
  72492. return;
  72493. }
  72494. var engine = scene.getEngine();
  72495. if (!this._texture) {
  72496. return;
  72497. }
  72498. // Bind
  72499. if (this._postProcessManager) {
  72500. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  72501. }
  72502. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  72503. if (this._texture) {
  72504. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  72505. }
  72506. }
  72507. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  72508. // Clear
  72509. if (this.onClearObservable.hasObservers()) {
  72510. this.onClearObservable.notifyObservers(engine);
  72511. }
  72512. else {
  72513. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  72514. }
  72515. if (!this._doNotChangeAspectRatio) {
  72516. scene.updateTransformMatrix(true);
  72517. }
  72518. // Render
  72519. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  72520. if (this._postProcessManager) {
  72521. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  72522. }
  72523. else if (useCameraPostProcess) {
  72524. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  72525. }
  72526. if (!this._doNotChangeAspectRatio) {
  72527. scene.updateTransformMatrix(true);
  72528. }
  72529. // Dump ?
  72530. if (dumpForDebug) {
  72531. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  72532. }
  72533. // Unbind
  72534. if (!this.isCube || faceIndex === 5) {
  72535. if (this.isCube) {
  72536. if (faceIndex === 5) {
  72537. engine.generateMipMapsForCubemap(this._texture);
  72538. }
  72539. }
  72540. this.unbindFrameBuffer(engine, faceIndex);
  72541. }
  72542. else {
  72543. this.onAfterRenderObservable.notifyObservers(faceIndex);
  72544. }
  72545. };
  72546. /**
  72547. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  72548. * This allowed control for front to back rendering or reversly depending of the special needs.
  72549. *
  72550. * @param renderingGroupId The rendering group id corresponding to its index
  72551. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  72552. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  72553. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  72554. */
  72555. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  72556. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  72557. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  72558. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  72559. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  72560. };
  72561. /**
  72562. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72563. *
  72564. * @param renderingGroupId The rendering group id corresponding to its index
  72565. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72566. */
  72567. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72568. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72569. this._renderingManager._useSceneAutoClearSetup = false;
  72570. };
  72571. /**
  72572. * Clones the texture.
  72573. * @returns the cloned texture
  72574. */
  72575. RenderTargetTexture.prototype.clone = function () {
  72576. var textureSize = this.getSize();
  72577. 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);
  72578. // Base texture
  72579. newTexture.hasAlpha = this.hasAlpha;
  72580. newTexture.level = this.level;
  72581. // RenderTarget Texture
  72582. newTexture.coordinatesMode = this.coordinatesMode;
  72583. if (this.renderList) {
  72584. newTexture.renderList = this.renderList.slice(0);
  72585. }
  72586. return newTexture;
  72587. };
  72588. /**
  72589. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  72590. * @returns The JSON representation of the texture
  72591. */
  72592. RenderTargetTexture.prototype.serialize = function () {
  72593. if (!this.name) {
  72594. return null;
  72595. }
  72596. var serializationObject = _super.prototype.serialize.call(this);
  72597. serializationObject.renderTargetSize = this.getRenderSize();
  72598. serializationObject.renderList = [];
  72599. if (this.renderList) {
  72600. for (var index = 0; index < this.renderList.length; index++) {
  72601. serializationObject.renderList.push(this.renderList[index].id);
  72602. }
  72603. }
  72604. return serializationObject;
  72605. };
  72606. /**
  72607. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  72608. */
  72609. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  72610. var objBuffer = this.getInternalTexture();
  72611. var scene = this.getScene();
  72612. if (objBuffer && scene) {
  72613. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  72614. }
  72615. };
  72616. /**
  72617. * Dispose the texture and release its associated resources.
  72618. */
  72619. RenderTargetTexture.prototype.dispose = function () {
  72620. if (this._postProcessManager) {
  72621. this._postProcessManager.dispose();
  72622. this._postProcessManager = null;
  72623. }
  72624. this.clearPostProcesses(true);
  72625. if (this._resizeObserver) {
  72626. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  72627. this._resizeObserver = null;
  72628. }
  72629. this.renderList = null;
  72630. // Remove from custom render targets
  72631. var scene = this.getScene();
  72632. if (!scene) {
  72633. return;
  72634. }
  72635. var index = scene.customRenderTargets.indexOf(this);
  72636. if (index >= 0) {
  72637. scene.customRenderTargets.splice(index, 1);
  72638. }
  72639. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  72640. var camera = _a[_i];
  72641. index = camera.customRenderTargets.indexOf(this);
  72642. if (index >= 0) {
  72643. camera.customRenderTargets.splice(index, 1);
  72644. }
  72645. }
  72646. _super.prototype.dispose.call(this);
  72647. };
  72648. /** @hidden */
  72649. RenderTargetTexture.prototype._rebuild = function () {
  72650. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72651. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72652. }
  72653. if (this._postProcessManager) {
  72654. this._postProcessManager._rebuild();
  72655. }
  72656. };
  72657. /**
  72658. * Clear the info related to rendering groups preventing retention point in material dispose.
  72659. */
  72660. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  72661. if (this._renderingManager) {
  72662. this._renderingManager.freeRenderingGroups();
  72663. }
  72664. };
  72665. /**
  72666. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  72667. */
  72668. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  72669. /**
  72670. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  72671. */
  72672. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  72673. /**
  72674. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  72675. * the central point of your effect and can save a lot of performances.
  72676. */
  72677. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  72678. return RenderTargetTexture;
  72679. }(BABYLON.Texture));
  72680. BABYLON.RenderTargetTexture = RenderTargetTexture;
  72681. })(BABYLON || (BABYLON = {}));
  72682. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  72683. var BABYLON;
  72684. (function (BABYLON) {
  72685. /**
  72686. * A multi render target, like a render target provides the ability to render to a texture.
  72687. * Unlike the render target, it can render to several draw buffers in one draw.
  72688. * This is specially interesting in deferred rendering or for any effects requiring more than
  72689. * just one color from a single pass.
  72690. */
  72691. var MultiRenderTarget = /** @class */ (function (_super) {
  72692. __extends(MultiRenderTarget, _super);
  72693. /**
  72694. * Instantiate a new multi render target texture.
  72695. * A multi render target, like a render target provides the ability to render to a texture.
  72696. * Unlike the render target, it can render to several draw buffers in one draw.
  72697. * This is specially interesting in deferred rendering or for any effects requiring more than
  72698. * just one color from a single pass.
  72699. * @param name Define the name of the texture
  72700. * @param size Define the size of the buffers to render to
  72701. * @param count Define the number of target we are rendering into
  72702. * @param scene Define the scene the texture belongs to
  72703. * @param options Define the options used to create the multi render target
  72704. */
  72705. function MultiRenderTarget(name, size, count, scene, options) {
  72706. var _this = this;
  72707. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  72708. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  72709. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  72710. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  72711. _this._engine = scene.getEngine();
  72712. if (!_this.isSupported) {
  72713. _this.dispose();
  72714. return;
  72715. }
  72716. var types = [];
  72717. var samplingModes = [];
  72718. for (var i = 0; i < count; i++) {
  72719. if (options && options.types && options.types[i] !== undefined) {
  72720. types.push(options.types[i]);
  72721. }
  72722. else {
  72723. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72724. }
  72725. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  72726. samplingModes.push(options.samplingModes[i]);
  72727. }
  72728. else {
  72729. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72730. }
  72731. }
  72732. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  72733. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  72734. _this._size = size;
  72735. _this._multiRenderTargetOptions = {
  72736. samplingModes: samplingModes,
  72737. generateMipMaps: generateMipMaps,
  72738. generateDepthBuffer: generateDepthBuffer,
  72739. generateStencilBuffer: generateStencilBuffer,
  72740. generateDepthTexture: generateDepthTexture,
  72741. types: types,
  72742. textureCount: count
  72743. };
  72744. _this._createInternalTextures();
  72745. _this._createTextures();
  72746. return _this;
  72747. }
  72748. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  72749. /**
  72750. * Get if draw buffers are currently supported by the used hardware and browser.
  72751. */
  72752. get: function () {
  72753. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  72754. },
  72755. enumerable: true,
  72756. configurable: true
  72757. });
  72758. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  72759. /**
  72760. * Get the list of textures generated by the multi render target.
  72761. */
  72762. get: function () {
  72763. return this._textures;
  72764. },
  72765. enumerable: true,
  72766. configurable: true
  72767. });
  72768. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  72769. /**
  72770. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  72771. */
  72772. get: function () {
  72773. return this._textures[this._textures.length - 1];
  72774. },
  72775. enumerable: true,
  72776. configurable: true
  72777. });
  72778. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  72779. /**
  72780. * Set the wrapping mode on U of all the textures we are rendering to.
  72781. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72782. */
  72783. set: function (wrap) {
  72784. if (this._textures) {
  72785. for (var i = 0; i < this._textures.length; i++) {
  72786. this._textures[i].wrapU = wrap;
  72787. }
  72788. }
  72789. },
  72790. enumerable: true,
  72791. configurable: true
  72792. });
  72793. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  72794. /**
  72795. * Set the wrapping mode on V of all the textures we are rendering to.
  72796. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72797. */
  72798. set: function (wrap) {
  72799. if (this._textures) {
  72800. for (var i = 0; i < this._textures.length; i++) {
  72801. this._textures[i].wrapV = wrap;
  72802. }
  72803. }
  72804. },
  72805. enumerable: true,
  72806. configurable: true
  72807. });
  72808. /** @hidden */
  72809. MultiRenderTarget.prototype._rebuild = function () {
  72810. this.releaseInternalTextures();
  72811. this._createInternalTextures();
  72812. for (var i = 0; i < this._internalTextures.length; i++) {
  72813. var texture = this._textures[i];
  72814. texture._texture = this._internalTextures[i];
  72815. }
  72816. // Keeps references to frame buffer and stencil/depth buffer
  72817. this._texture = this._internalTextures[0];
  72818. };
  72819. MultiRenderTarget.prototype._createInternalTextures = function () {
  72820. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  72821. };
  72822. MultiRenderTarget.prototype._createTextures = function () {
  72823. this._textures = [];
  72824. for (var i = 0; i < this._internalTextures.length; i++) {
  72825. var texture = new BABYLON.Texture(null, this.getScene());
  72826. texture._texture = this._internalTextures[i];
  72827. this._textures.push(texture);
  72828. }
  72829. // Keeps references to frame buffer and stencil/depth buffer
  72830. this._texture = this._internalTextures[0];
  72831. };
  72832. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  72833. /**
  72834. * Define the number of samples used if MSAA is enabled.
  72835. */
  72836. get: function () {
  72837. return this._samples;
  72838. },
  72839. set: function (value) {
  72840. if (this._samples === value) {
  72841. return;
  72842. }
  72843. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  72844. },
  72845. enumerable: true,
  72846. configurable: true
  72847. });
  72848. /**
  72849. * Resize all the textures in the multi render target.
  72850. * Be carrefull as it will recreate all the data in the new texture.
  72851. * @param size Define the new size
  72852. */
  72853. MultiRenderTarget.prototype.resize = function (size) {
  72854. this.releaseInternalTextures();
  72855. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  72856. this._createInternalTextures();
  72857. };
  72858. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72859. var _this = this;
  72860. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  72861. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72862. });
  72863. };
  72864. /**
  72865. * Dispose the render targets and their associated resources
  72866. */
  72867. MultiRenderTarget.prototype.dispose = function () {
  72868. this.releaseInternalTextures();
  72869. _super.prototype.dispose.call(this);
  72870. };
  72871. /**
  72872. * Release all the underlying texture used as draw buffers.
  72873. */
  72874. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  72875. if (!this._internalTextures) {
  72876. return;
  72877. }
  72878. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  72879. if (this._internalTextures[i] !== undefined) {
  72880. this._internalTextures[i].dispose();
  72881. this._internalTextures.splice(i, 1);
  72882. }
  72883. }
  72884. };
  72885. return MultiRenderTarget;
  72886. }(BABYLON.RenderTargetTexture));
  72887. BABYLON.MultiRenderTarget = MultiRenderTarget;
  72888. })(BABYLON || (BABYLON = {}));
  72889. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  72890. var BABYLON;
  72891. (function (BABYLON) {
  72892. /**
  72893. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72894. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72895. * You can then easily use it as a reflectionTexture on a flat surface.
  72896. * In case the surface is not a plane, please consider relying on reflection probes.
  72897. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72898. */
  72899. var MirrorTexture = /** @class */ (function (_super) {
  72900. __extends(MirrorTexture, _super);
  72901. /**
  72902. * Instantiates a Mirror Texture.
  72903. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72904. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72905. * You can then easily use it as a reflectionTexture on a flat surface.
  72906. * In case the surface is not a plane, please consider relying on reflection probes.
  72907. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72908. * @param name
  72909. * @param size
  72910. * @param scene
  72911. * @param generateMipMaps
  72912. * @param type
  72913. * @param samplingMode
  72914. * @param generateDepthBuffer
  72915. */
  72916. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  72917. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72918. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72919. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72920. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  72921. _this.scene = scene;
  72922. /**
  72923. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  72924. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  72925. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72926. */
  72927. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  72928. _this._transformMatrix = BABYLON.Matrix.Zero();
  72929. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  72930. _this._adaptiveBlurKernel = 0;
  72931. _this._blurKernelX = 0;
  72932. _this._blurKernelY = 0;
  72933. _this._blurRatio = 1.0;
  72934. _this.ignoreCameraViewport = true;
  72935. _this._updateGammaSpace();
  72936. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  72937. _this._updateGammaSpace;
  72938. });
  72939. _this.onBeforeRenderObservable.add(function () {
  72940. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  72941. _this._savedViewMatrix = scene.getViewMatrix();
  72942. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  72943. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  72944. scene.clipPlane = _this.mirrorPlane;
  72945. scene.getEngine().cullBackFaces = false;
  72946. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  72947. });
  72948. _this.onAfterRenderObservable.add(function () {
  72949. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  72950. scene.getEngine().cullBackFaces = true;
  72951. scene._mirroredCameraPosition = null;
  72952. delete scene.clipPlane;
  72953. });
  72954. return _this;
  72955. }
  72956. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  72957. get: function () {
  72958. return this._blurRatio;
  72959. },
  72960. /**
  72961. * Define the blur ratio used to blur the reflection if needed.
  72962. */
  72963. set: function (value) {
  72964. if (this._blurRatio === value) {
  72965. return;
  72966. }
  72967. this._blurRatio = value;
  72968. this._preparePostProcesses();
  72969. },
  72970. enumerable: true,
  72971. configurable: true
  72972. });
  72973. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  72974. /**
  72975. * Define the adaptive blur kernel used to blur the reflection if needed.
  72976. * This will autocompute the closest best match for the `blurKernel`
  72977. */
  72978. set: function (value) {
  72979. this._adaptiveBlurKernel = value;
  72980. this._autoComputeBlurKernel();
  72981. },
  72982. enumerable: true,
  72983. configurable: true
  72984. });
  72985. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  72986. /**
  72987. * Define the blur kernel used to blur the reflection if needed.
  72988. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72989. */
  72990. set: function (value) {
  72991. this.blurKernelX = value;
  72992. this.blurKernelY = value;
  72993. },
  72994. enumerable: true,
  72995. configurable: true
  72996. });
  72997. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  72998. get: function () {
  72999. return this._blurKernelX;
  73000. },
  73001. /**
  73002. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  73003. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  73004. */
  73005. set: function (value) {
  73006. if (this._blurKernelX === value) {
  73007. return;
  73008. }
  73009. this._blurKernelX = value;
  73010. this._preparePostProcesses();
  73011. },
  73012. enumerable: true,
  73013. configurable: true
  73014. });
  73015. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  73016. get: function () {
  73017. return this._blurKernelY;
  73018. },
  73019. /**
  73020. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  73021. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  73022. */
  73023. set: function (value) {
  73024. if (this._blurKernelY === value) {
  73025. return;
  73026. }
  73027. this._blurKernelY = value;
  73028. this._preparePostProcesses();
  73029. },
  73030. enumerable: true,
  73031. configurable: true
  73032. });
  73033. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  73034. var engine = this.getScene().getEngine();
  73035. var dw = this.getRenderWidth() / engine.getRenderWidth();
  73036. var dh = this.getRenderHeight() / engine.getRenderHeight();
  73037. this.blurKernelX = this._adaptiveBlurKernel * dw;
  73038. this.blurKernelY = this._adaptiveBlurKernel * dh;
  73039. };
  73040. MirrorTexture.prototype._onRatioRescale = function () {
  73041. if (this._sizeRatio) {
  73042. this.resize(this._initialSizeParameter);
  73043. if (!this._adaptiveBlurKernel) {
  73044. this._preparePostProcesses();
  73045. }
  73046. }
  73047. if (this._adaptiveBlurKernel) {
  73048. this._autoComputeBlurKernel();
  73049. }
  73050. };
  73051. MirrorTexture.prototype._updateGammaSpace = function () {
  73052. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  73053. };
  73054. MirrorTexture.prototype._preparePostProcesses = function () {
  73055. this.clearPostProcesses(true);
  73056. if (this._blurKernelX && this._blurKernelY) {
  73057. var engine = this.getScene().getEngine();
  73058. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73059. 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);
  73060. this._blurX.autoClear = false;
  73061. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  73062. this._blurX.inputTexture = this._texture;
  73063. }
  73064. else {
  73065. this._blurX.alwaysForcePOT = true;
  73066. }
  73067. 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);
  73068. this._blurY.autoClear = false;
  73069. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  73070. this.addPostProcess(this._blurX);
  73071. this.addPostProcess(this._blurY);
  73072. }
  73073. else {
  73074. if (this._blurY) {
  73075. this.removePostProcess(this._blurY);
  73076. this._blurY.dispose();
  73077. this._blurY = null;
  73078. }
  73079. if (this._blurX) {
  73080. this.removePostProcess(this._blurX);
  73081. this._blurX.dispose();
  73082. this._blurX = null;
  73083. }
  73084. }
  73085. };
  73086. /**
  73087. * Clone the mirror texture.
  73088. * @returns the cloned texture
  73089. */
  73090. MirrorTexture.prototype.clone = function () {
  73091. var scene = this.getScene();
  73092. if (!scene) {
  73093. return this;
  73094. }
  73095. var textureSize = this.getSize();
  73096. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  73097. // Base texture
  73098. newTexture.hasAlpha = this.hasAlpha;
  73099. newTexture.level = this.level;
  73100. // Mirror Texture
  73101. newTexture.mirrorPlane = this.mirrorPlane.clone();
  73102. if (this.renderList) {
  73103. newTexture.renderList = this.renderList.slice(0);
  73104. }
  73105. return newTexture;
  73106. };
  73107. /**
  73108. * Serialize the texture to a JSON representation you could use in Parse later on
  73109. * @returns the serialized JSON representation
  73110. */
  73111. MirrorTexture.prototype.serialize = function () {
  73112. if (!this.name) {
  73113. return null;
  73114. }
  73115. var serializationObject = _super.prototype.serialize.call(this);
  73116. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  73117. return serializationObject;
  73118. };
  73119. /**
  73120. * Dispose the texture and release its associated resources.
  73121. */
  73122. MirrorTexture.prototype.dispose = function () {
  73123. _super.prototype.dispose.call(this);
  73124. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  73125. };
  73126. return MirrorTexture;
  73127. }(BABYLON.RenderTargetTexture));
  73128. BABYLON.MirrorTexture = MirrorTexture;
  73129. })(BABYLON || (BABYLON = {}));
  73130. //# sourceMappingURL=babylon.mirrorTexture.js.map
  73131. var BABYLON;
  73132. (function (BABYLON) {
  73133. /**
  73134. * Creates a refraction texture used by refraction channel of the standard material.
  73135. * It is like a mirror but to see through a material.
  73136. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73137. */
  73138. var RefractionTexture = /** @class */ (function (_super) {
  73139. __extends(RefractionTexture, _super);
  73140. /**
  73141. * Creates a refraction texture used by refraction channel of the standard material.
  73142. * It is like a mirror but to see through a material.
  73143. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73144. * @param name Define the texture name
  73145. * @param size Define the size of the underlying texture
  73146. * @param scene Define the scene the refraction belongs to
  73147. * @param generateMipMaps Define if we need to generate mips level for the refraction
  73148. */
  73149. function RefractionTexture(name, size, scene, generateMipMaps) {
  73150. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  73151. /**
  73152. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  73153. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  73154. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  73155. */
  73156. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  73157. /**
  73158. * Define how deep under the surface we should see.
  73159. */
  73160. _this.depth = 2.0;
  73161. _this.onBeforeRenderObservable.add(function () {
  73162. scene.clipPlane = _this.refractionPlane;
  73163. });
  73164. _this.onAfterRenderObservable.add(function () {
  73165. delete scene.clipPlane;
  73166. });
  73167. return _this;
  73168. }
  73169. /**
  73170. * Clone the refraction texture.
  73171. * @returns the cloned texture
  73172. */
  73173. RefractionTexture.prototype.clone = function () {
  73174. var scene = this.getScene();
  73175. if (!scene) {
  73176. return this;
  73177. }
  73178. var textureSize = this.getSize();
  73179. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  73180. // Base texture
  73181. newTexture.hasAlpha = this.hasAlpha;
  73182. newTexture.level = this.level;
  73183. // Refraction Texture
  73184. newTexture.refractionPlane = this.refractionPlane.clone();
  73185. if (this.renderList) {
  73186. newTexture.renderList = this.renderList.slice(0);
  73187. }
  73188. newTexture.depth = this.depth;
  73189. return newTexture;
  73190. };
  73191. /**
  73192. * Serialize the texture to a JSON representation you could use in Parse later on
  73193. * @returns the serialized JSON representation
  73194. */
  73195. RefractionTexture.prototype.serialize = function () {
  73196. if (!this.name) {
  73197. return null;
  73198. }
  73199. var serializationObject = _super.prototype.serialize.call(this);
  73200. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  73201. serializationObject.depth = this.depth;
  73202. return serializationObject;
  73203. };
  73204. return RefractionTexture;
  73205. }(BABYLON.RenderTargetTexture));
  73206. BABYLON.RefractionTexture = RefractionTexture;
  73207. })(BABYLON || (BABYLON = {}));
  73208. //# sourceMappingURL=babylon.refractionTexture.js.map
  73209. var BABYLON;
  73210. (function (BABYLON) {
  73211. /**
  73212. * A class extending Texture allowing drawing on a texture
  73213. * @see http://doc.babylonjs.com/how_to/dynamictexture
  73214. */
  73215. var DynamicTexture = /** @class */ (function (_super) {
  73216. __extends(DynamicTexture, _super);
  73217. /**
  73218. * Creates a DynamicTexture
  73219. * @param name defines the name of the texture
  73220. * @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
  73221. * @param scene defines the scene where you want the texture
  73222. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  73223. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  73224. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  73225. */
  73226. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  73227. if (scene === void 0) { scene = null; }
  73228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73229. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73230. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  73231. _this.name = name;
  73232. _this._engine = _this.getScene().getEngine();
  73233. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73234. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73235. _this._generateMipMaps = generateMipMaps;
  73236. if (options.getContext) {
  73237. _this._canvas = options;
  73238. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  73239. }
  73240. else {
  73241. _this._canvas = document.createElement("canvas");
  73242. if (options.width || options.width === 0) {
  73243. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  73244. }
  73245. else {
  73246. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  73247. }
  73248. }
  73249. var textureSize = _this.getSize();
  73250. _this._canvas.width = textureSize.width;
  73251. _this._canvas.height = textureSize.height;
  73252. _this._context = _this._canvas.getContext("2d");
  73253. return _this;
  73254. }
  73255. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  73256. /**
  73257. * Gets the current state of canRescale
  73258. */
  73259. get: function () {
  73260. return true;
  73261. },
  73262. enumerable: true,
  73263. configurable: true
  73264. });
  73265. DynamicTexture.prototype._recreate = function (textureSize) {
  73266. this._canvas.width = textureSize.width;
  73267. this._canvas.height = textureSize.height;
  73268. this.releaseInternalTexture();
  73269. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  73270. };
  73271. /**
  73272. * Scales the texture
  73273. * @param ratio the scale factor to apply to both width and height
  73274. */
  73275. DynamicTexture.prototype.scale = function (ratio) {
  73276. var textureSize = this.getSize();
  73277. textureSize.width *= ratio;
  73278. textureSize.height *= ratio;
  73279. this._recreate(textureSize);
  73280. };
  73281. /**
  73282. * Resizes the texture
  73283. * @param width the new width
  73284. * @param height the new height
  73285. */
  73286. DynamicTexture.prototype.scaleTo = function (width, height) {
  73287. var textureSize = this.getSize();
  73288. textureSize.width = width;
  73289. textureSize.height = height;
  73290. this._recreate(textureSize);
  73291. };
  73292. /**
  73293. * Gets the context of the canvas used by the texture
  73294. * @returns the canvas context of the dynamic texture
  73295. */
  73296. DynamicTexture.prototype.getContext = function () {
  73297. return this._context;
  73298. };
  73299. /**
  73300. * Clears the texture
  73301. */
  73302. DynamicTexture.prototype.clear = function () {
  73303. var size = this.getSize();
  73304. this._context.fillRect(0, 0, size.width, size.height);
  73305. };
  73306. /**
  73307. * Updates the texture
  73308. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73309. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  73310. */
  73311. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  73312. if (premulAlpha === void 0) { premulAlpha = false; }
  73313. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  73314. };
  73315. /**
  73316. * Draws text onto the texture
  73317. * @param text defines the text to be drawn
  73318. * @param x defines the placement of the text from the left
  73319. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  73320. * @param font defines the font to be used with font-style, font-size, font-name
  73321. * @param color defines the color used for the text
  73322. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  73323. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73324. * @param update defines whether texture is immediately update (default is true)
  73325. */
  73326. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  73327. if (update === void 0) { update = true; }
  73328. var size = this.getSize();
  73329. if (clearColor) {
  73330. this._context.fillStyle = clearColor;
  73331. this._context.fillRect(0, 0, size.width, size.height);
  73332. }
  73333. this._context.font = font;
  73334. if (x === null || x === undefined) {
  73335. var textSize = this._context.measureText(text);
  73336. x = (size.width - textSize.width) / 2;
  73337. }
  73338. if (y === null || y === undefined) {
  73339. var fontSize = parseInt((font.replace(/\D/g, '')));
  73340. y = (size.height / 2) + (fontSize / 3.65);
  73341. }
  73342. this._context.fillStyle = color;
  73343. this._context.fillText(text, x, y);
  73344. if (update) {
  73345. this.update(invertY);
  73346. }
  73347. };
  73348. /**
  73349. * Clones the texture
  73350. * @returns the clone of the texture.
  73351. */
  73352. DynamicTexture.prototype.clone = function () {
  73353. var scene = this.getScene();
  73354. if (!scene) {
  73355. return this;
  73356. }
  73357. var textureSize = this.getSize();
  73358. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  73359. // Base texture
  73360. newTexture.hasAlpha = this.hasAlpha;
  73361. newTexture.level = this.level;
  73362. // Dynamic Texture
  73363. newTexture.wrapU = this.wrapU;
  73364. newTexture.wrapV = this.wrapV;
  73365. return newTexture;
  73366. };
  73367. /**
  73368. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  73369. * @returns a serialized dynamic texture object
  73370. */
  73371. DynamicTexture.prototype.serialize = function () {
  73372. var scene = this.getScene();
  73373. if (scene && !scene.isReady()) {
  73374. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  73375. }
  73376. var serializationObject = _super.prototype.serialize.call(this);
  73377. serializationObject.base64String = this._canvas.toDataURL();
  73378. serializationObject.invertY = this._invertY;
  73379. serializationObject.samplingMode = this.samplingMode;
  73380. return serializationObject;
  73381. };
  73382. /** @hidden */
  73383. DynamicTexture.prototype._rebuild = function () {
  73384. this.update();
  73385. };
  73386. return DynamicTexture;
  73387. }(BABYLON.Texture));
  73388. BABYLON.DynamicTexture = DynamicTexture;
  73389. })(BABYLON || (BABYLON = {}));
  73390. //# sourceMappingURL=babylon.dynamicTexture.js.map
  73391. var BABYLON;
  73392. (function (BABYLON) {
  73393. /**
  73394. * If you want to display a video in your scene, this is the special texture for that.
  73395. * This special texture works similar to other textures, with the exception of a few parameters.
  73396. * @see https://doc.babylonjs.com/how_to/video_texture
  73397. */
  73398. var VideoTexture = /** @class */ (function (_super) {
  73399. __extends(VideoTexture, _super);
  73400. /**
  73401. * Creates a video texture.
  73402. * If you want to display a video in your scene, this is the special texture for that.
  73403. * This special texture works similar to other textures, with the exception of a few parameters.
  73404. * @see https://doc.babylonjs.com/how_to/video_texture
  73405. * @param name optional name, will detect from video source, if not defined
  73406. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  73407. * @param scene is obviously the current scene.
  73408. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  73409. * @param invertY is false by default but can be used to invert video on Y axis
  73410. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  73411. * @param settings allows finer control over video usage
  73412. */
  73413. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  73414. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73415. if (invertY === void 0) { invertY = false; }
  73416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73417. if (settings === void 0) { settings = {
  73418. autoPlay: true,
  73419. loop: true,
  73420. autoUpdateTexture: true,
  73421. }; }
  73422. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73423. _this._onUserActionRequestedObservable = null;
  73424. _this._stillImageCaptured = false;
  73425. _this._poster = false;
  73426. _this._createInternalTexture = function () {
  73427. if (_this._texture != null) {
  73428. if (_this._poster) {
  73429. _this._texture.dispose();
  73430. _this._poster = false;
  73431. }
  73432. else {
  73433. return;
  73434. }
  73435. }
  73436. if (!_this._engine.needPOTTextures ||
  73437. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  73438. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73439. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73440. }
  73441. else {
  73442. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73443. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73444. _this._generateMipMaps = false;
  73445. }
  73446. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  73447. if (!_this.video.autoplay) {
  73448. var oldHandler_1 = _this.video.onplaying;
  73449. var error_1 = false;
  73450. _this.video.onplaying = function () {
  73451. _this.video.onplaying = oldHandler_1;
  73452. _this._texture.isReady = true;
  73453. _this._updateInternalTexture();
  73454. if (!error_1) {
  73455. _this.video.pause();
  73456. }
  73457. if (_this.onLoadObservable.hasObservers()) {
  73458. _this.onLoadObservable.notifyObservers(_this);
  73459. }
  73460. };
  73461. var playing = _this.video.play();
  73462. if (playing) {
  73463. playing.then(function () {
  73464. // Everything is good.
  73465. })
  73466. .catch(function () {
  73467. error_1 = true;
  73468. // On Chrome for instance, new policies might prevent playing without user interaction.
  73469. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  73470. _this._onUserActionRequestedObservable.notifyObservers(_this);
  73471. }
  73472. });
  73473. }
  73474. else {
  73475. _this.video.onplaying = oldHandler_1;
  73476. _this._texture.isReady = true;
  73477. _this._updateInternalTexture();
  73478. if (_this.onLoadObservable.hasObservers()) {
  73479. _this.onLoadObservable.notifyObservers(_this);
  73480. }
  73481. }
  73482. }
  73483. else {
  73484. _this._texture.isReady = true;
  73485. _this._updateInternalTexture();
  73486. if (_this.onLoadObservable.hasObservers()) {
  73487. _this.onLoadObservable.notifyObservers(_this);
  73488. }
  73489. }
  73490. };
  73491. _this.reset = function () {
  73492. if (_this._texture == null) {
  73493. return;
  73494. }
  73495. if (!_this._poster) {
  73496. _this._texture.dispose();
  73497. _this._texture = null;
  73498. }
  73499. };
  73500. _this._updateInternalTexture = function (e) {
  73501. if (_this._texture == null || !_this._texture.isReady) {
  73502. return;
  73503. }
  73504. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  73505. return;
  73506. }
  73507. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  73508. };
  73509. _this._engine = _this.getScene().getEngine();
  73510. _this._generateMipMaps = generateMipMaps;
  73511. _this._samplingMode = samplingMode;
  73512. _this.autoUpdateTexture = settings.autoUpdateTexture;
  73513. _this.name = name || _this._getName(src);
  73514. _this.video = _this._getVideo(src);
  73515. if (settings.poster) {
  73516. _this.video.poster = settings.poster;
  73517. }
  73518. if (settings.autoPlay !== undefined) {
  73519. _this.video.autoplay = settings.autoPlay;
  73520. }
  73521. if (settings.loop !== undefined) {
  73522. _this.video.loop = settings.loop;
  73523. }
  73524. _this.video.setAttribute("playsinline", "");
  73525. _this.video.addEventListener("canplay", _this._createInternalTexture);
  73526. _this.video.addEventListener("paused", _this._updateInternalTexture);
  73527. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  73528. _this.video.addEventListener("emptied", _this.reset);
  73529. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  73530. _this._createInternalTexture();
  73531. }
  73532. if (settings.poster) {
  73533. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  73534. _this._poster = true;
  73535. }
  73536. return _this;
  73537. }
  73538. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  73539. /**
  73540. * Event triggerd when a dom action is required by the user to play the video.
  73541. * This happens due to recent changes in browser policies preventing video to auto start.
  73542. */
  73543. get: function () {
  73544. if (!this._onUserActionRequestedObservable) {
  73545. this._onUserActionRequestedObservable = new BABYLON.Observable();
  73546. }
  73547. return this._onUserActionRequestedObservable;
  73548. },
  73549. enumerable: true,
  73550. configurable: true
  73551. });
  73552. VideoTexture.prototype._getName = function (src) {
  73553. if (src instanceof HTMLVideoElement) {
  73554. return src.currentSrc;
  73555. }
  73556. if (typeof src === "object") {
  73557. return src.toString();
  73558. }
  73559. return src;
  73560. };
  73561. VideoTexture.prototype._getVideo = function (src) {
  73562. if (src instanceof HTMLVideoElement) {
  73563. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  73564. return src;
  73565. }
  73566. var video = document.createElement("video");
  73567. if (typeof src === "string") {
  73568. BABYLON.Tools.SetCorsBehavior(src, video);
  73569. video.src = src;
  73570. }
  73571. else {
  73572. BABYLON.Tools.SetCorsBehavior(src[0], video);
  73573. src.forEach(function (url) {
  73574. var source = document.createElement("source");
  73575. source.src = url;
  73576. video.appendChild(source);
  73577. });
  73578. }
  73579. return video;
  73580. };
  73581. /**
  73582. * @hidden Internal method to initiate `update`.
  73583. */
  73584. VideoTexture.prototype._rebuild = function () {
  73585. this.update();
  73586. };
  73587. /**
  73588. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  73589. */
  73590. VideoTexture.prototype.update = function () {
  73591. if (!this.autoUpdateTexture) {
  73592. // Expecting user to call `updateTexture` manually
  73593. return;
  73594. }
  73595. this.updateTexture(true);
  73596. };
  73597. /**
  73598. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  73599. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  73600. */
  73601. VideoTexture.prototype.updateTexture = function (isVisible) {
  73602. if (!isVisible) {
  73603. return;
  73604. }
  73605. if (this.video.paused && this._stillImageCaptured) {
  73606. return;
  73607. }
  73608. this._stillImageCaptured = true;
  73609. this._updateInternalTexture();
  73610. };
  73611. /**
  73612. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  73613. * @param url New url.
  73614. */
  73615. VideoTexture.prototype.updateURL = function (url) {
  73616. this.video.src = url;
  73617. };
  73618. /**
  73619. * Dispose the texture and release its associated resources.
  73620. */
  73621. VideoTexture.prototype.dispose = function () {
  73622. _super.prototype.dispose.call(this);
  73623. if (this._onUserActionRequestedObservable) {
  73624. this._onUserActionRequestedObservable.clear();
  73625. this._onUserActionRequestedObservable = null;
  73626. }
  73627. this.video.removeEventListener("canplay", this._createInternalTexture);
  73628. this.video.removeEventListener("paused", this._updateInternalTexture);
  73629. this.video.removeEventListener("seeked", this._updateInternalTexture);
  73630. this.video.removeEventListener("emptied", this.reset);
  73631. this.video.pause();
  73632. };
  73633. /**
  73634. * Creates a video texture straight from your WebCam video feed.
  73635. * @param scene Define the scene the texture should be created in
  73636. * @param onReady Define a callback to triggered once the texture will be ready
  73637. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  73638. */
  73639. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  73640. var video = document.createElement("video");
  73641. video.setAttribute('autoplay', '');
  73642. video.setAttribute('muted', '');
  73643. video.setAttribute('playsinline', '');
  73644. var constraintsDeviceId;
  73645. if (constraints && constraints.deviceId) {
  73646. constraintsDeviceId = {
  73647. exact: constraints.deviceId,
  73648. };
  73649. }
  73650. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  73651. if (navigator.mediaDevices) {
  73652. navigator.mediaDevices.getUserMedia({ video: constraints })
  73653. .then(function (stream) {
  73654. if (video.mozSrcObject !== undefined) {
  73655. // hack for Firefox < 19
  73656. video.mozSrcObject = stream;
  73657. }
  73658. else {
  73659. video.srcObject = stream;
  73660. }
  73661. var onPlaying = function () {
  73662. if (onReady) {
  73663. onReady(new VideoTexture("video", video, scene, true, true));
  73664. }
  73665. video.removeEventListener("playing", onPlaying);
  73666. };
  73667. video.addEventListener("playing", onPlaying);
  73668. video.play();
  73669. })
  73670. .catch(function (err) {
  73671. BABYLON.Tools.Error(err.name);
  73672. });
  73673. }
  73674. else {
  73675. navigator.getUserMedia =
  73676. navigator.getUserMedia ||
  73677. navigator.webkitGetUserMedia ||
  73678. navigator.mozGetUserMedia ||
  73679. navigator.msGetUserMedia;
  73680. if (navigator.getUserMedia) {
  73681. navigator.getUserMedia({
  73682. video: {
  73683. deviceId: constraintsDeviceId,
  73684. width: {
  73685. min: (constraints && constraints.minWidth) || 256,
  73686. max: (constraints && constraints.maxWidth) || 640,
  73687. },
  73688. height: {
  73689. min: (constraints && constraints.minHeight) || 256,
  73690. max: (constraints && constraints.maxHeight) || 480,
  73691. },
  73692. },
  73693. }, function (stream) {
  73694. if (video.mozSrcObject !== undefined) {
  73695. // hack for Firefox < 19
  73696. video.mozSrcObject = stream;
  73697. }
  73698. else {
  73699. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  73700. }
  73701. video.play();
  73702. if (onReady) {
  73703. onReady(new VideoTexture("video", video, scene, true, true));
  73704. }
  73705. }, function (e) {
  73706. BABYLON.Tools.Error(e.name);
  73707. });
  73708. }
  73709. }
  73710. };
  73711. return VideoTexture;
  73712. }(BABYLON.Texture));
  73713. BABYLON.VideoTexture = VideoTexture;
  73714. })(BABYLON || (BABYLON = {}));
  73715. //# sourceMappingURL=babylon.videoTexture.js.map
  73716. var BABYLON;
  73717. (function (BABYLON) {
  73718. /**
  73719. * Raw texture can help creating a texture directly from an array of data.
  73720. * This can be super useful if you either get the data from an uncompressed source or
  73721. * if you wish to create your texture pixel by pixel.
  73722. */
  73723. var RawTexture = /** @class */ (function (_super) {
  73724. __extends(RawTexture, _super);
  73725. /**
  73726. * Instantiates a new RawTexture.
  73727. * Raw texture can help creating a texture directly from an array of data.
  73728. * This can be super useful if you either get the data from an uncompressed source or
  73729. * if you wish to create your texture pixel by pixel.
  73730. * @param data define the array of data to use to create the texture
  73731. * @param width define the width of the texture
  73732. * @param height define the height of the texture
  73733. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73734. * @param scene define the scene the texture belongs to
  73735. * @param generateMipMaps define whether mip maps should be generated or not
  73736. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73737. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73738. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73739. */
  73740. function RawTexture(data, width, height,
  73741. /**
  73742. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73743. */
  73744. format, scene, generateMipMaps, invertY, samplingMode, type) {
  73745. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73746. if (invertY === void 0) { invertY = false; }
  73747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73748. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73749. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73750. _this.format = format;
  73751. _this._engine = scene.getEngine();
  73752. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  73753. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73754. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73755. return _this;
  73756. }
  73757. /**
  73758. * Updates the texture underlying data.
  73759. * @param data Define the new data of the texture
  73760. */
  73761. RawTexture.prototype.update = function (data) {
  73762. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73763. };
  73764. /**
  73765. * Creates a luminance texture from some data.
  73766. * @param data Define the texture data
  73767. * @param width Define the width of the texture
  73768. * @param height Define the height of the texture
  73769. * @param scene Define the scene the texture belongs to
  73770. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73771. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73772. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73773. * @returns the luminance texture
  73774. */
  73775. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73776. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73777. if (invertY === void 0) { invertY = false; }
  73778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73779. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  73780. };
  73781. /**
  73782. * Creates a luminance alpha texture from some data.
  73783. * @param data Define the texture data
  73784. * @param width Define the width of the texture
  73785. * @param height Define the height of the texture
  73786. * @param scene Define the scene the texture belongs to
  73787. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73788. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73789. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73790. * @returns the luminance alpha texture
  73791. */
  73792. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73793. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73794. if (invertY === void 0) { invertY = false; }
  73795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73796. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73797. };
  73798. /**
  73799. * Creates an alpha texture from some data.
  73800. * @param data Define the texture data
  73801. * @param width Define the width of the texture
  73802. * @param height Define the height of the texture
  73803. * @param scene Define the scene the texture belongs to
  73804. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73805. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73806. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73807. * @returns the alpha texture
  73808. */
  73809. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73810. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73811. if (invertY === void 0) { invertY = false; }
  73812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73813. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73814. };
  73815. /**
  73816. * Creates a RGB texture from some data.
  73817. * @param data Define the texture data
  73818. * @param width Define the width of the texture
  73819. * @param height Define the height of the texture
  73820. * @param scene Define the scene the texture belongs to
  73821. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73822. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73823. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73824. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73825. * @returns the RGB alpha texture
  73826. */
  73827. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73828. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73829. if (invertY === void 0) { invertY = false; }
  73830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73831. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73832. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  73833. };
  73834. /**
  73835. * Creates a RGBA texture from some data.
  73836. * @param data Define the texture data
  73837. * @param width Define the width of the texture
  73838. * @param height Define the height of the texture
  73839. * @param scene Define the scene the texture belongs to
  73840. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73841. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73842. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73843. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73844. * @returns the RGBA texture
  73845. */
  73846. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73847. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73848. if (invertY === void 0) { invertY = false; }
  73849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73850. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73851. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  73852. };
  73853. /**
  73854. * Creates a R texture from some data.
  73855. * @param data Define the texture data
  73856. * @param width Define the width of the texture
  73857. * @param height Define the height of the texture
  73858. * @param scene Define the scene the texture belongs to
  73859. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73860. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73861. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73862. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73863. * @returns the R texture
  73864. */
  73865. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73866. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73867. if (invertY === void 0) { invertY = false; }
  73868. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73869. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73870. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  73871. };
  73872. return RawTexture;
  73873. }(BABYLON.Texture));
  73874. BABYLON.RawTexture = RawTexture;
  73875. })(BABYLON || (BABYLON = {}));
  73876. //# sourceMappingURL=babylon.rawTexture.js.map
  73877. var BABYLON;
  73878. (function (BABYLON) {
  73879. /**
  73880. * Class used to store 3D textures containing user data
  73881. */
  73882. var RawTexture3D = /** @class */ (function (_super) {
  73883. __extends(RawTexture3D, _super);
  73884. /**
  73885. * Create a new RawTexture3D
  73886. * @param data defines the data of the texture
  73887. * @param width defines the width of the texture
  73888. * @param height defines the height of the texture
  73889. * @param depth defines the depth of the texture
  73890. * @param format defines the texture format to use
  73891. * @param scene defines the hosting scene
  73892. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  73893. * @param invertY defines if texture must be stored with Y axis inverted
  73894. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  73895. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  73896. */
  73897. function RawTexture3D(data, width, height, depth,
  73898. /** Gets or sets the texture format to use */
  73899. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  73900. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73901. if (invertY === void 0) { invertY = false; }
  73902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73904. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73905. _this.format = format;
  73906. _this._engine = scene.getEngine();
  73907. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  73908. _this.is3D = true;
  73909. return _this;
  73910. }
  73911. /**
  73912. * Update the texture with new data
  73913. * @param data defines the data to store in the texture
  73914. */
  73915. RawTexture3D.prototype.update = function (data) {
  73916. if (!this._texture) {
  73917. return;
  73918. }
  73919. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73920. };
  73921. return RawTexture3D;
  73922. }(BABYLON.Texture));
  73923. BABYLON.RawTexture3D = RawTexture3D;
  73924. })(BABYLON || (BABYLON = {}));
  73925. //# sourceMappingURL=babylon.rawTexture3D.js.map
  73926. var BABYLON;
  73927. (function (BABYLON) {
  73928. /**
  73929. * PostProcessManager is used to manage one or more post processes or post process pipelines
  73930. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73931. */
  73932. var PostProcessManager = /** @class */ (function () {
  73933. /**
  73934. * Creates a new instance PostProcess
  73935. * @param scene The scene that the post process is associated with.
  73936. */
  73937. function PostProcessManager(scene) {
  73938. this._vertexBuffers = {};
  73939. this._scene = scene;
  73940. }
  73941. PostProcessManager.prototype._prepareBuffers = function () {
  73942. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  73943. return;
  73944. }
  73945. // VBO
  73946. var vertices = [];
  73947. vertices.push(1, 1);
  73948. vertices.push(-1, 1);
  73949. vertices.push(-1, -1);
  73950. vertices.push(1, -1);
  73951. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73952. this._buildIndexBuffer();
  73953. };
  73954. PostProcessManager.prototype._buildIndexBuffer = function () {
  73955. // Indices
  73956. var indices = [];
  73957. indices.push(0);
  73958. indices.push(1);
  73959. indices.push(2);
  73960. indices.push(0);
  73961. indices.push(2);
  73962. indices.push(3);
  73963. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  73964. };
  73965. /**
  73966. * Rebuilds the vertex buffers of the manager.
  73967. * @hidden
  73968. */
  73969. PostProcessManager.prototype._rebuild = function () {
  73970. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73971. if (!vb) {
  73972. return;
  73973. }
  73974. vb._rebuild();
  73975. this._buildIndexBuffer();
  73976. };
  73977. // Methods
  73978. /**
  73979. * Prepares a frame to be run through a post process.
  73980. * @param sourceTexture The input texture to the post procesess. (default: null)
  73981. * @param postProcesses An array of post processes to be run. (default: null)
  73982. * @returns True if the post processes were able to be run.
  73983. * @hidden
  73984. */
  73985. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  73986. if (sourceTexture === void 0) { sourceTexture = null; }
  73987. if (postProcesses === void 0) { postProcesses = null; }
  73988. var camera = this._scene.activeCamera;
  73989. if (!camera) {
  73990. return false;
  73991. }
  73992. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73993. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73994. return false;
  73995. }
  73996. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  73997. return true;
  73998. };
  73999. /**
  74000. * Manually render a set of post processes to a texture.
  74001. * @param postProcesses An array of post processes to be run.
  74002. * @param targetTexture The target texture to render to.
  74003. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  74004. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  74005. * @param lodLevel defines which lod of the texture to render to
  74006. */
  74007. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  74008. if (targetTexture === void 0) { targetTexture = null; }
  74009. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  74010. if (faceIndex === void 0) { faceIndex = 0; }
  74011. if (lodLevel === void 0) { lodLevel = 0; }
  74012. var engine = this._scene.getEngine();
  74013. for (var index = 0; index < postProcesses.length; index++) {
  74014. if (index < postProcesses.length - 1) {
  74015. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  74016. }
  74017. else {
  74018. if (targetTexture) {
  74019. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  74020. }
  74021. else {
  74022. engine.restoreDefaultFramebuffer();
  74023. }
  74024. }
  74025. var pp = postProcesses[index];
  74026. var effect = pp.apply();
  74027. if (effect) {
  74028. pp.onBeforeRenderObservable.notifyObservers(effect);
  74029. // VBOs
  74030. this._prepareBuffers();
  74031. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  74032. // Draw order
  74033. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74034. pp.onAfterRenderObservable.notifyObservers(effect);
  74035. }
  74036. }
  74037. // Restore depth buffer
  74038. engine.setDepthBuffer(true);
  74039. engine.setDepthWrite(true);
  74040. };
  74041. /**
  74042. * Finalize the result of the output of the postprocesses.
  74043. * @param doNotPresent If true the result will not be displayed to the screen.
  74044. * @param targetTexture The target texture to render to.
  74045. * @param faceIndex The index of the face to bind the target texture to.
  74046. * @param postProcesses The array of post processes to render.
  74047. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  74048. * @hidden
  74049. */
  74050. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  74051. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  74052. var camera = this._scene.activeCamera;
  74053. if (!camera) {
  74054. return;
  74055. }
  74056. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  74057. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  74058. return;
  74059. }
  74060. var engine = this._scene.getEngine();
  74061. for (var index = 0, len = postProcesses.length; index < len; index++) {
  74062. var pp = postProcesses[index];
  74063. if (index < len - 1) {
  74064. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  74065. }
  74066. else {
  74067. if (targetTexture) {
  74068. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  74069. pp._outputTexture = targetTexture;
  74070. }
  74071. else {
  74072. engine.restoreDefaultFramebuffer();
  74073. pp._outputTexture = null;
  74074. }
  74075. }
  74076. if (doNotPresent) {
  74077. break;
  74078. }
  74079. var effect = pp.apply();
  74080. if (effect) {
  74081. pp.onBeforeRenderObservable.notifyObservers(effect);
  74082. // VBOs
  74083. this._prepareBuffers();
  74084. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  74085. // Draw order
  74086. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74087. pp.onAfterRenderObservable.notifyObservers(effect);
  74088. }
  74089. }
  74090. // Restore states
  74091. engine.setDepthBuffer(true);
  74092. engine.setDepthWrite(true);
  74093. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74094. };
  74095. /**
  74096. * Disposes of the post process manager.
  74097. */
  74098. PostProcessManager.prototype.dispose = function () {
  74099. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74100. if (buffer) {
  74101. buffer.dispose();
  74102. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74103. }
  74104. if (this._indexBuffer) {
  74105. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74106. this._indexBuffer = null;
  74107. }
  74108. };
  74109. return PostProcessManager;
  74110. }());
  74111. BABYLON.PostProcessManager = PostProcessManager;
  74112. })(BABYLON || (BABYLON = {}));
  74113. //# sourceMappingURL=babylon.postProcessManager.js.map
  74114. var BABYLON;
  74115. (function (BABYLON) {
  74116. /**
  74117. * PostProcess can be used to apply a shader to a texture after it has been rendered
  74118. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  74119. */
  74120. var PostProcess = /** @class */ (function () {
  74121. /**
  74122. * Creates a new instance PostProcess
  74123. * @param name The name of the PostProcess.
  74124. * @param fragmentUrl The url of the fragment shader to be used.
  74125. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  74126. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  74127. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74128. * @param camera The camera to apply the render pass to.
  74129. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74130. * @param engine The engine which the post process will be applied. (default: current engine)
  74131. * @param reusable If the post process can be reused on the same frame. (default: false)
  74132. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  74133. * @param textureType Type of textures used when performing the post process. (default: 0)
  74134. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  74135. * @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
  74136. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  74137. */
  74138. function PostProcess(
  74139. /** Name of the PostProcess. */
  74140. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  74141. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  74142. if (defines === void 0) { defines = null; }
  74143. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74144. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  74145. if (blockCompilation === void 0) { blockCompilation = false; }
  74146. this.name = name;
  74147. /**
  74148. * Width of the texture to apply the post process on
  74149. */
  74150. this.width = -1;
  74151. /**
  74152. * Height of the texture to apply the post process on
  74153. */
  74154. this.height = -1;
  74155. /**
  74156. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  74157. * @hidden
  74158. */
  74159. this._outputTexture = null;
  74160. /**
  74161. * If the buffer needs to be cleared before applying the post process. (default: true)
  74162. * Should be set to false if shader will overwrite all previous pixels.
  74163. */
  74164. this.autoClear = true;
  74165. /**
  74166. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  74167. */
  74168. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  74169. /**
  74170. * Animations to be used for the post processing
  74171. */
  74172. this.animations = new Array();
  74173. /**
  74174. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  74175. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  74176. */
  74177. this.enablePixelPerfectMode = false;
  74178. /**
  74179. * Force the postprocess to be applied without taking in account viewport
  74180. */
  74181. this.forceFullscreenViewport = true;
  74182. /**
  74183. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  74184. *
  74185. * | Value | Type | Description |
  74186. * | ----- | ----------------------------------- | ----------- |
  74187. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  74188. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  74189. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  74190. *
  74191. */
  74192. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  74193. /**
  74194. * Force textures to be a power of two (default: false)
  74195. */
  74196. this.alwaysForcePOT = false;
  74197. this._samples = 1;
  74198. /**
  74199. * Modify the scale of the post process to be the same as the viewport (default: false)
  74200. */
  74201. this.adaptScaleToCurrentViewport = false;
  74202. this._reusable = false;
  74203. /**
  74204. * Smart array of input and output textures for the post process.
  74205. * @hidden
  74206. */
  74207. this._textures = new BABYLON.SmartArray(2);
  74208. /**
  74209. * The index in _textures that corresponds to the output texture.
  74210. * @hidden
  74211. */
  74212. this._currentRenderTextureInd = 0;
  74213. this._scaleRatio = new BABYLON.Vector2(1, 1);
  74214. this._texelSize = BABYLON.Vector2.Zero();
  74215. // Events
  74216. /**
  74217. * An event triggered when the postprocess is activated.
  74218. */
  74219. this.onActivateObservable = new BABYLON.Observable();
  74220. /**
  74221. * An event triggered when the postprocess changes its size.
  74222. */
  74223. this.onSizeChangedObservable = new BABYLON.Observable();
  74224. /**
  74225. * An event triggered when the postprocess applies its effect.
  74226. */
  74227. this.onApplyObservable = new BABYLON.Observable();
  74228. /**
  74229. * An event triggered before rendering the postprocess
  74230. */
  74231. this.onBeforeRenderObservable = new BABYLON.Observable();
  74232. /**
  74233. * An event triggered after rendering the postprocess
  74234. */
  74235. this.onAfterRenderObservable = new BABYLON.Observable();
  74236. if (camera != null) {
  74237. this._camera = camera;
  74238. this._scene = camera.getScene();
  74239. camera.attachPostProcess(this);
  74240. this._engine = this._scene.getEngine();
  74241. this._scene.postProcesses.push(this);
  74242. }
  74243. else if (engine) {
  74244. this._engine = engine;
  74245. this._engine.postProcesses.push(this);
  74246. }
  74247. this._options = options;
  74248. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74249. this._reusable = reusable || false;
  74250. this._textureType = textureType;
  74251. this._samplers = samplers || [];
  74252. this._samplers.push("textureSampler");
  74253. this._fragmentUrl = fragmentUrl;
  74254. this._vertexUrl = vertexUrl;
  74255. this._parameters = parameters || [];
  74256. this._parameters.push("scale");
  74257. this._indexParameters = indexParameters;
  74258. if (!blockCompilation) {
  74259. this.updateEffect(defines);
  74260. }
  74261. }
  74262. Object.defineProperty(PostProcess.prototype, "samples", {
  74263. /**
  74264. * Number of sample textures (default: 1)
  74265. */
  74266. get: function () {
  74267. return this._samples;
  74268. },
  74269. set: function (n) {
  74270. var _this = this;
  74271. this._samples = n;
  74272. this._textures.forEach(function (texture) {
  74273. if (texture.samples !== _this._samples) {
  74274. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  74275. }
  74276. });
  74277. },
  74278. enumerable: true,
  74279. configurable: true
  74280. });
  74281. Object.defineProperty(PostProcess.prototype, "onActivate", {
  74282. /**
  74283. * A function that is added to the onActivateObservable
  74284. */
  74285. set: function (callback) {
  74286. if (this._onActivateObserver) {
  74287. this.onActivateObservable.remove(this._onActivateObserver);
  74288. }
  74289. if (callback) {
  74290. this._onActivateObserver = this.onActivateObservable.add(callback);
  74291. }
  74292. },
  74293. enumerable: true,
  74294. configurable: true
  74295. });
  74296. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  74297. /**
  74298. * A function that is added to the onSizeChangedObservable
  74299. */
  74300. set: function (callback) {
  74301. if (this._onSizeChangedObserver) {
  74302. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  74303. }
  74304. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  74305. },
  74306. enumerable: true,
  74307. configurable: true
  74308. });
  74309. Object.defineProperty(PostProcess.prototype, "onApply", {
  74310. /**
  74311. * A function that is added to the onApplyObservable
  74312. */
  74313. set: function (callback) {
  74314. if (this._onApplyObserver) {
  74315. this.onApplyObservable.remove(this._onApplyObserver);
  74316. }
  74317. this._onApplyObserver = this.onApplyObservable.add(callback);
  74318. },
  74319. enumerable: true,
  74320. configurable: true
  74321. });
  74322. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  74323. /**
  74324. * A function that is added to the onBeforeRenderObservable
  74325. */
  74326. set: function (callback) {
  74327. if (this._onBeforeRenderObserver) {
  74328. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74329. }
  74330. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74331. },
  74332. enumerable: true,
  74333. configurable: true
  74334. });
  74335. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  74336. /**
  74337. * A function that is added to the onAfterRenderObservable
  74338. */
  74339. set: function (callback) {
  74340. if (this._onAfterRenderObserver) {
  74341. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74342. }
  74343. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74344. },
  74345. enumerable: true,
  74346. configurable: true
  74347. });
  74348. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  74349. /**
  74350. * 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
  74351. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  74352. */
  74353. get: function () {
  74354. return this._textures.data[this._currentRenderTextureInd];
  74355. },
  74356. set: function (value) {
  74357. this._forcedOutputTexture = value;
  74358. },
  74359. enumerable: true,
  74360. configurable: true
  74361. });
  74362. /**
  74363. * Gets the camera which post process is applied to.
  74364. * @returns The camera the post process is applied to.
  74365. */
  74366. PostProcess.prototype.getCamera = function () {
  74367. return this._camera;
  74368. };
  74369. Object.defineProperty(PostProcess.prototype, "texelSize", {
  74370. /**
  74371. * Gets the texel size of the postprocess.
  74372. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  74373. */
  74374. get: function () {
  74375. if (this._shareOutputWithPostProcess) {
  74376. return this._shareOutputWithPostProcess.texelSize;
  74377. }
  74378. if (this._forcedOutputTexture) {
  74379. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  74380. }
  74381. return this._texelSize;
  74382. },
  74383. enumerable: true,
  74384. configurable: true
  74385. });
  74386. /**
  74387. * Gets the engine which this post process belongs to.
  74388. * @returns The engine the post process was enabled with.
  74389. */
  74390. PostProcess.prototype.getEngine = function () {
  74391. return this._engine;
  74392. };
  74393. /**
  74394. * The effect that is created when initializing the post process.
  74395. * @returns The created effect corrisponding the the postprocess.
  74396. */
  74397. PostProcess.prototype.getEffect = function () {
  74398. return this._effect;
  74399. };
  74400. /**
  74401. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  74402. * @param postProcess The post process to share the output with.
  74403. * @returns This post process.
  74404. */
  74405. PostProcess.prototype.shareOutputWith = function (postProcess) {
  74406. this._disposeTextures();
  74407. this._shareOutputWithPostProcess = postProcess;
  74408. return this;
  74409. };
  74410. /**
  74411. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  74412. * This should be called if the post process that shares output with this post process is disabled/disposed.
  74413. */
  74414. PostProcess.prototype.useOwnOutput = function () {
  74415. if (this._textures.length == 0) {
  74416. this._textures = new BABYLON.SmartArray(2);
  74417. }
  74418. this._shareOutputWithPostProcess = null;
  74419. };
  74420. /**
  74421. * Updates the effect with the current post process compile time values and recompiles the shader.
  74422. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74423. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74424. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74425. * @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
  74426. * @param onCompiled Called when the shader has been compiled.
  74427. * @param onError Called if there is an error when compiling a shader.
  74428. */
  74429. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74430. if (defines === void 0) { defines = null; }
  74431. if (uniforms === void 0) { uniforms = null; }
  74432. if (samplers === void 0) { samplers = null; }
  74433. 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);
  74434. };
  74435. /**
  74436. * The post process is reusable if it can be used multiple times within one frame.
  74437. * @returns If the post process is reusable
  74438. */
  74439. PostProcess.prototype.isReusable = function () {
  74440. return this._reusable;
  74441. };
  74442. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  74443. PostProcess.prototype.markTextureDirty = function () {
  74444. this.width = -1;
  74445. };
  74446. /**
  74447. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  74448. * 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.
  74449. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  74450. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  74451. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  74452. * @returns The target texture that was bound to be written to.
  74453. */
  74454. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  74455. var _this = this;
  74456. if (sourceTexture === void 0) { sourceTexture = null; }
  74457. camera = camera || this._camera;
  74458. var scene = camera.getScene();
  74459. var engine = scene.getEngine();
  74460. var maxSize = engine.getCaps().maxTextureSize;
  74461. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  74462. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  74463. // 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
  74464. var webVRCamera = camera.parent;
  74465. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  74466. requiredWidth /= 2;
  74467. }
  74468. var desiredWidth = (this._options.width || requiredWidth);
  74469. var desiredHeight = this._options.height || requiredHeight;
  74470. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  74471. if (this.adaptScaleToCurrentViewport) {
  74472. var currentViewport = engine.currentViewport;
  74473. if (currentViewport) {
  74474. desiredWidth *= currentViewport.width;
  74475. desiredHeight *= currentViewport.height;
  74476. }
  74477. }
  74478. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  74479. if (!this._options.width) {
  74480. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  74481. }
  74482. if (!this._options.height) {
  74483. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  74484. }
  74485. }
  74486. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  74487. if (this._textures.length > 0) {
  74488. for (var i = 0; i < this._textures.length; i++) {
  74489. this._engine._releaseTexture(this._textures.data[i]);
  74490. }
  74491. this._textures.reset();
  74492. }
  74493. this.width = desiredWidth;
  74494. this.height = desiredHeight;
  74495. var textureSize = { width: this.width, height: this.height };
  74496. var textureOptions = {
  74497. generateMipMaps: false,
  74498. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  74499. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  74500. samplingMode: this.renderTargetSamplingMode,
  74501. type: this._textureType
  74502. };
  74503. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74504. if (this._reusable) {
  74505. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74506. }
  74507. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  74508. this.onSizeChangedObservable.notifyObservers(this);
  74509. }
  74510. this._textures.forEach(function (texture) {
  74511. if (texture.samples !== _this.samples) {
  74512. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  74513. }
  74514. });
  74515. }
  74516. var target;
  74517. if (this._shareOutputWithPostProcess) {
  74518. target = this._shareOutputWithPostProcess.inputTexture;
  74519. }
  74520. else if (this._forcedOutputTexture) {
  74521. target = this._forcedOutputTexture;
  74522. this.width = this._forcedOutputTexture.width;
  74523. this.height = this._forcedOutputTexture.height;
  74524. }
  74525. else {
  74526. target = this.inputTexture;
  74527. }
  74528. // Bind the input of this post process to be used as the output of the previous post process.
  74529. if (this.enablePixelPerfectMode) {
  74530. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  74531. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  74532. }
  74533. else {
  74534. this._scaleRatio.copyFromFloats(1, 1);
  74535. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  74536. }
  74537. this.onActivateObservable.notifyObservers(camera);
  74538. // Clear
  74539. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  74540. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  74541. }
  74542. if (this._reusable) {
  74543. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  74544. }
  74545. return target;
  74546. };
  74547. Object.defineProperty(PostProcess.prototype, "isSupported", {
  74548. /**
  74549. * If the post process is supported.
  74550. */
  74551. get: function () {
  74552. return this._effect.isSupported;
  74553. },
  74554. enumerable: true,
  74555. configurable: true
  74556. });
  74557. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  74558. /**
  74559. * The aspect ratio of the output texture.
  74560. */
  74561. get: function () {
  74562. if (this._shareOutputWithPostProcess) {
  74563. return this._shareOutputWithPostProcess.aspectRatio;
  74564. }
  74565. if (this._forcedOutputTexture) {
  74566. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  74567. }
  74568. return this.width / this.height;
  74569. },
  74570. enumerable: true,
  74571. configurable: true
  74572. });
  74573. /**
  74574. * Get a value indicating if the post-process is ready to be used
  74575. * @returns true if the post-process is ready (shader is compiled)
  74576. */
  74577. PostProcess.prototype.isReady = function () {
  74578. return this._effect && this._effect.isReady();
  74579. };
  74580. /**
  74581. * Binds all textures and uniforms to the shader, this will be run on every pass.
  74582. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  74583. */
  74584. PostProcess.prototype.apply = function () {
  74585. // Check
  74586. if (!this._effect || !this._effect.isReady()) {
  74587. return null;
  74588. }
  74589. // States
  74590. this._engine.enableEffect(this._effect);
  74591. this._engine.setState(false);
  74592. this._engine.setDepthBuffer(false);
  74593. this._engine.setDepthWrite(false);
  74594. // Alpha
  74595. this._engine.setAlphaMode(this.alphaMode);
  74596. if (this.alphaConstants) {
  74597. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  74598. }
  74599. // Bind the output texture of the preivous post process as the input to this post process.
  74600. var source;
  74601. if (this._shareOutputWithPostProcess) {
  74602. source = this._shareOutputWithPostProcess.inputTexture;
  74603. }
  74604. else if (this._forcedOutputTexture) {
  74605. source = this._forcedOutputTexture;
  74606. }
  74607. else {
  74608. source = this.inputTexture;
  74609. }
  74610. this._effect._bindTexture("textureSampler", source);
  74611. // Parameters
  74612. this._effect.setVector2("scale", this._scaleRatio);
  74613. this.onApplyObservable.notifyObservers(this._effect);
  74614. return this._effect;
  74615. };
  74616. PostProcess.prototype._disposeTextures = function () {
  74617. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  74618. return;
  74619. }
  74620. if (this._textures.length > 0) {
  74621. for (var i = 0; i < this._textures.length; i++) {
  74622. this._engine._releaseTexture(this._textures.data[i]);
  74623. }
  74624. }
  74625. this._textures.dispose();
  74626. };
  74627. /**
  74628. * Disposes the post process.
  74629. * @param camera The camera to dispose the post process on.
  74630. */
  74631. PostProcess.prototype.dispose = function (camera) {
  74632. camera = camera || this._camera;
  74633. this._disposeTextures();
  74634. if (this._scene) {
  74635. var index_1 = this._scene.postProcesses.indexOf(this);
  74636. if (index_1 !== -1) {
  74637. this._scene.postProcesses.splice(index_1, 1);
  74638. }
  74639. }
  74640. else {
  74641. var index_2 = this._engine.postProcesses.indexOf(this);
  74642. if (index_2 !== -1) {
  74643. this._engine.postProcesses.splice(index_2, 1);
  74644. }
  74645. }
  74646. if (!camera) {
  74647. return;
  74648. }
  74649. camera.detachPostProcess(this);
  74650. var index = camera._postProcesses.indexOf(this);
  74651. if (index === 0 && camera._postProcesses.length > 0) {
  74652. var firstPostProcess = this._camera._getFirstPostProcess();
  74653. if (firstPostProcess) {
  74654. firstPostProcess.markTextureDirty();
  74655. }
  74656. }
  74657. this.onActivateObservable.clear();
  74658. this.onAfterRenderObservable.clear();
  74659. this.onApplyObservable.clear();
  74660. this.onBeforeRenderObservable.clear();
  74661. this.onSizeChangedObservable.clear();
  74662. };
  74663. return PostProcess;
  74664. }());
  74665. BABYLON.PostProcess = PostProcess;
  74666. })(BABYLON || (BABYLON = {}));
  74667. //# sourceMappingURL=babylon.postProcess.js.map
  74668. var BABYLON;
  74669. (function (BABYLON) {
  74670. /**
  74671. * PassPostProcess which produces an output the same as it's input
  74672. */
  74673. var PassPostProcess = /** @class */ (function (_super) {
  74674. __extends(PassPostProcess, _super);
  74675. /**
  74676. * Creates the PassPostProcess
  74677. * @param name The name of the effect.
  74678. * @param options The required width/height ratio to downsize to before computing the render pass.
  74679. * @param camera The camera to apply the render pass to.
  74680. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74681. * @param engine The engine which the post process will be applied. (default: current engine)
  74682. * @param reusable If the post process can be reused on the same frame. (default: false)
  74683. * @param textureType The type of texture to be used when performing the post processing.
  74684. * @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)
  74685. */
  74686. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74687. if (camera === void 0) { camera = null; }
  74688. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74689. if (blockCompilation === void 0) { blockCompilation = false; }
  74690. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  74691. }
  74692. return PassPostProcess;
  74693. }(BABYLON.PostProcess));
  74694. BABYLON.PassPostProcess = PassPostProcess;
  74695. })(BABYLON || (BABYLON = {}));
  74696. //# sourceMappingURL=babylon.passPostProcess.js.map
  74697. var __assign = (this && this.__assign) || function () {
  74698. __assign = Object.assign || function(t) {
  74699. for (var s, i = 1, n = arguments.length; i < n; i++) {
  74700. s = arguments[i];
  74701. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  74702. t[p] = s[p];
  74703. }
  74704. return t;
  74705. };
  74706. return __assign.apply(this, arguments);
  74707. };
  74708. var BABYLON;
  74709. (function (BABYLON) {
  74710. /**
  74711. * Default implementation IShadowGenerator.
  74712. * This is the main object responsible of generating shadows in the framework.
  74713. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  74714. */
  74715. var ShadowGenerator = /** @class */ (function () {
  74716. /**
  74717. * Creates a ShadowGenerator object.
  74718. * A ShadowGenerator is the required tool to use the shadows.
  74719. * Each light casting shadows needs to use its own ShadowGenerator.
  74720. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  74721. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  74722. * @param light The light object generating the shadows.
  74723. * @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.
  74724. */
  74725. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  74726. this._bias = 0.00005;
  74727. this._normalBias = 0;
  74728. this._blurBoxOffset = 1;
  74729. this._blurScale = 2;
  74730. this._blurKernel = 1;
  74731. this._useKernelBlur = false;
  74732. this._filter = ShadowGenerator.FILTER_NONE;
  74733. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  74734. this._contactHardeningLightSizeUVRatio = 0.1;
  74735. this._darkness = 0;
  74736. this._transparencyShadow = false;
  74737. /**
  74738. * Controls the extent to which the shadows fade out at the edge of the frustum
  74739. * Used only by directionals and spots
  74740. */
  74741. this.frustumEdgeFalloff = 0;
  74742. /**
  74743. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  74744. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  74745. * It might on the other hand introduce peter panning.
  74746. */
  74747. this.forceBackFacesOnly = false;
  74748. this._lightDirection = BABYLON.Vector3.Zero();
  74749. this._viewMatrix = BABYLON.Matrix.Zero();
  74750. this._projectionMatrix = BABYLON.Matrix.Zero();
  74751. this._transformMatrix = BABYLON.Matrix.Zero();
  74752. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74753. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74754. this._currentFaceIndex = 0;
  74755. this._currentFaceIndexCache = 0;
  74756. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  74757. this._mapSize = mapSize;
  74758. this._light = light;
  74759. this._scene = light.getScene();
  74760. light._shadowGenerator = this;
  74761. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  74762. if (!component) {
  74763. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  74764. this._scene._addComponent(component);
  74765. }
  74766. // Texture type fallback from float to int if not supported.
  74767. var caps = this._scene.getEngine().getCaps();
  74768. if (!useFullFloatFirst) {
  74769. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74770. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74771. }
  74772. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74773. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74774. }
  74775. else {
  74776. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74777. }
  74778. }
  74779. else {
  74780. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74781. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74782. }
  74783. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74784. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74785. }
  74786. else {
  74787. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74788. }
  74789. }
  74790. this._initializeGenerator();
  74791. this._applyFilterValues();
  74792. }
  74793. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  74794. /**
  74795. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  74796. */
  74797. get: function () {
  74798. return this._bias;
  74799. },
  74800. /**
  74801. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  74802. */
  74803. set: function (bias) {
  74804. this._bias = bias;
  74805. },
  74806. enumerable: true,
  74807. configurable: true
  74808. });
  74809. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  74810. /**
  74811. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74812. */
  74813. get: function () {
  74814. return this._normalBias;
  74815. },
  74816. /**
  74817. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74818. */
  74819. set: function (normalBias) {
  74820. this._normalBias = normalBias;
  74821. },
  74822. enumerable: true,
  74823. configurable: true
  74824. });
  74825. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  74826. /**
  74827. * Gets the blur box offset: offset applied during the blur pass.
  74828. * Only usefull if useKernelBlur = false
  74829. */
  74830. get: function () {
  74831. return this._blurBoxOffset;
  74832. },
  74833. /**
  74834. * Sets the blur box offset: offset applied during the blur pass.
  74835. * Only usefull if useKernelBlur = false
  74836. */
  74837. set: function (value) {
  74838. if (this._blurBoxOffset === value) {
  74839. return;
  74840. }
  74841. this._blurBoxOffset = value;
  74842. this._disposeBlurPostProcesses();
  74843. },
  74844. enumerable: true,
  74845. configurable: true
  74846. });
  74847. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  74848. /**
  74849. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  74850. * 2 means half of the size.
  74851. */
  74852. get: function () {
  74853. return this._blurScale;
  74854. },
  74855. /**
  74856. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  74857. * 2 means half of the size.
  74858. */
  74859. set: function (value) {
  74860. if (this._blurScale === value) {
  74861. return;
  74862. }
  74863. this._blurScale = value;
  74864. this._disposeBlurPostProcesses();
  74865. },
  74866. enumerable: true,
  74867. configurable: true
  74868. });
  74869. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  74870. /**
  74871. * Gets the blur kernel: kernel size of the blur pass.
  74872. * Only usefull if useKernelBlur = true
  74873. */
  74874. get: function () {
  74875. return this._blurKernel;
  74876. },
  74877. /**
  74878. * Sets the blur kernel: kernel size of the blur pass.
  74879. * Only usefull if useKernelBlur = true
  74880. */
  74881. set: function (value) {
  74882. if (this._blurKernel === value) {
  74883. return;
  74884. }
  74885. this._blurKernel = value;
  74886. this._disposeBlurPostProcesses();
  74887. },
  74888. enumerable: true,
  74889. configurable: true
  74890. });
  74891. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  74892. /**
  74893. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  74894. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74895. */
  74896. get: function () {
  74897. return this._useKernelBlur;
  74898. },
  74899. /**
  74900. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  74901. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74902. */
  74903. set: function (value) {
  74904. if (this._useKernelBlur === value) {
  74905. return;
  74906. }
  74907. this._useKernelBlur = value;
  74908. this._disposeBlurPostProcesses();
  74909. },
  74910. enumerable: true,
  74911. configurable: true
  74912. });
  74913. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  74914. /**
  74915. * Gets the depth scale used in ESM mode.
  74916. */
  74917. get: function () {
  74918. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  74919. },
  74920. /**
  74921. * Sets the depth scale used in ESM mode.
  74922. * This can override the scale stored on the light.
  74923. */
  74924. set: function (value) {
  74925. this._depthScale = value;
  74926. },
  74927. enumerable: true,
  74928. configurable: true
  74929. });
  74930. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  74931. /**
  74932. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  74933. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74934. */
  74935. get: function () {
  74936. return this._filter;
  74937. },
  74938. /**
  74939. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  74940. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74941. */
  74942. set: function (value) {
  74943. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  74944. if (this._light.needCube()) {
  74945. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74946. this.useExponentialShadowMap = true;
  74947. return;
  74948. }
  74949. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74950. this.useCloseExponentialShadowMap = true;
  74951. return;
  74952. }
  74953. // PCF on cubemap would also be expensive
  74954. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74955. this.usePoissonSampling = true;
  74956. return;
  74957. }
  74958. }
  74959. // Weblg1 fallback for PCF.
  74960. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74961. if (this._scene.getEngine().webGLVersion === 1) {
  74962. this.usePoissonSampling = true;
  74963. return;
  74964. }
  74965. }
  74966. if (this._filter === value) {
  74967. return;
  74968. }
  74969. this._filter = value;
  74970. this._disposeBlurPostProcesses();
  74971. this._applyFilterValues();
  74972. this._light._markMeshesAsLightDirty();
  74973. },
  74974. enumerable: true,
  74975. configurable: true
  74976. });
  74977. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  74978. /**
  74979. * Gets if the current filter is set to Poisson Sampling.
  74980. */
  74981. get: function () {
  74982. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  74983. },
  74984. /**
  74985. * Sets the current filter to Poisson Sampling.
  74986. */
  74987. set: function (value) {
  74988. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  74989. return;
  74990. }
  74991. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  74992. },
  74993. enumerable: true,
  74994. configurable: true
  74995. });
  74996. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  74997. /**
  74998. * Gets if the current filter is set to VSM.
  74999. * DEPRECATED. Should use useExponentialShadowMap instead.
  75000. */
  75001. get: function () {
  75002. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  75003. return this.useExponentialShadowMap;
  75004. },
  75005. /**
  75006. * Sets the current filter is to VSM.
  75007. * DEPRECATED. Should use useExponentialShadowMap instead.
  75008. */
  75009. set: function (value) {
  75010. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  75011. this.useExponentialShadowMap = value;
  75012. },
  75013. enumerable: true,
  75014. configurable: true
  75015. });
  75016. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  75017. /**
  75018. * Gets if the current filter is set to blurred VSM.
  75019. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  75020. */
  75021. get: function () {
  75022. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  75023. return this.useBlurExponentialShadowMap;
  75024. },
  75025. /**
  75026. * Sets the current filter is to blurred VSM.
  75027. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  75028. */
  75029. set: function (value) {
  75030. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  75031. this.useBlurExponentialShadowMap = value;
  75032. },
  75033. enumerable: true,
  75034. configurable: true
  75035. });
  75036. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  75037. /**
  75038. * Gets if the current filter is set to ESM.
  75039. */
  75040. get: function () {
  75041. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  75042. },
  75043. /**
  75044. * Sets the current filter is to ESM.
  75045. */
  75046. set: function (value) {
  75047. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  75048. return;
  75049. }
  75050. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75051. },
  75052. enumerable: true,
  75053. configurable: true
  75054. });
  75055. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  75056. /**
  75057. * Gets if the current filter is set to filtered ESM.
  75058. */
  75059. get: function () {
  75060. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  75061. },
  75062. /**
  75063. * Gets if the current filter is set to filtered ESM.
  75064. */
  75065. set: function (value) {
  75066. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  75067. return;
  75068. }
  75069. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75070. },
  75071. enumerable: true,
  75072. configurable: true
  75073. });
  75074. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  75075. /**
  75076. * Gets if the current filter is set to "close ESM" (using the inverse of the
  75077. * exponential to prevent steep falloff artifacts).
  75078. */
  75079. get: function () {
  75080. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  75081. },
  75082. /**
  75083. * Sets the current filter to "close ESM" (using the inverse of the
  75084. * exponential to prevent steep falloff artifacts).
  75085. */
  75086. set: function (value) {
  75087. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  75088. return;
  75089. }
  75090. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75091. },
  75092. enumerable: true,
  75093. configurable: true
  75094. });
  75095. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  75096. /**
  75097. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  75098. * exponential to prevent steep falloff artifacts).
  75099. */
  75100. get: function () {
  75101. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  75102. },
  75103. /**
  75104. * Sets the current filter to filtered "close ESM" (using the inverse of the
  75105. * exponential to prevent steep falloff artifacts).
  75106. */
  75107. set: function (value) {
  75108. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  75109. return;
  75110. }
  75111. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  75112. },
  75113. enumerable: true,
  75114. configurable: true
  75115. });
  75116. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  75117. /**
  75118. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  75119. */
  75120. get: function () {
  75121. return this.filter === ShadowGenerator.FILTER_PCF;
  75122. },
  75123. /**
  75124. * Sets the current filter to "PCF" (percentage closer filtering).
  75125. */
  75126. set: function (value) {
  75127. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  75128. return;
  75129. }
  75130. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  75131. },
  75132. enumerable: true,
  75133. configurable: true
  75134. });
  75135. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  75136. /**
  75137. * Gets the PCF or PCSS Quality.
  75138. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  75139. */
  75140. get: function () {
  75141. return this._filteringQuality;
  75142. },
  75143. /**
  75144. * Sets the PCF or PCSS Quality.
  75145. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  75146. */
  75147. set: function (filteringQuality) {
  75148. this._filteringQuality = filteringQuality;
  75149. },
  75150. enumerable: true,
  75151. configurable: true
  75152. });
  75153. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  75154. /**
  75155. * Gets if the current filter is set to "PCSS" (contact hardening).
  75156. */
  75157. get: function () {
  75158. return this.filter === ShadowGenerator.FILTER_PCSS;
  75159. },
  75160. /**
  75161. * Sets the current filter to "PCSS" (contact hardening).
  75162. */
  75163. set: function (value) {
  75164. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  75165. return;
  75166. }
  75167. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  75168. },
  75169. enumerable: true,
  75170. configurable: true
  75171. });
  75172. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  75173. /**
  75174. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  75175. * Using a ratio helps keeping shape stability independently of the map size.
  75176. *
  75177. * It does not account for the light projection as it was having too much
  75178. * instability during the light setup or during light position changes.
  75179. *
  75180. * Only valid if useContactHardeningShadow is true.
  75181. */
  75182. get: function () {
  75183. return this._contactHardeningLightSizeUVRatio;
  75184. },
  75185. /**
  75186. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  75187. * Using a ratio helps keeping shape stability independently of the map size.
  75188. *
  75189. * It does not account for the light projection as it was having too much
  75190. * instability during the light setup or during light position changes.
  75191. *
  75192. * Only valid if useContactHardeningShadow is true.
  75193. */
  75194. set: function (contactHardeningLightSizeUVRatio) {
  75195. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  75196. },
  75197. enumerable: true,
  75198. configurable: true
  75199. });
  75200. /**
  75201. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  75202. * 0 means strongest and 1 would means no shadow.
  75203. * @returns the darkness.
  75204. */
  75205. ShadowGenerator.prototype.getDarkness = function () {
  75206. return this._darkness;
  75207. };
  75208. /**
  75209. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  75210. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  75211. * @returns the shadow generator allowing fluent coding.
  75212. */
  75213. ShadowGenerator.prototype.setDarkness = function (darkness) {
  75214. if (darkness >= 1.0) {
  75215. this._darkness = 1.0;
  75216. }
  75217. else if (darkness <= 0.0) {
  75218. this._darkness = 0.0;
  75219. }
  75220. else {
  75221. this._darkness = darkness;
  75222. }
  75223. return this;
  75224. };
  75225. /**
  75226. * Sets the ability to have transparent shadow (boolean).
  75227. * @param transparent True if transparent else False
  75228. * @returns the shadow generator allowing fluent coding
  75229. */
  75230. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  75231. this._transparencyShadow = transparent;
  75232. return this;
  75233. };
  75234. /**
  75235. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  75236. * @returns The render target texture if present otherwise, null
  75237. */
  75238. ShadowGenerator.prototype.getShadowMap = function () {
  75239. return this._shadowMap;
  75240. };
  75241. /**
  75242. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  75243. * @returns The render target texture if the shadow map is present otherwise, null
  75244. */
  75245. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  75246. if (this._shadowMap2) {
  75247. return this._shadowMap2;
  75248. }
  75249. return this._shadowMap;
  75250. };
  75251. /**
  75252. * Helper function to add a mesh and its descendants to the list of shadow casters.
  75253. * @param mesh Mesh to add
  75254. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  75255. * @returns the Shadow Generator itself
  75256. */
  75257. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  75258. if (includeDescendants === void 0) { includeDescendants = true; }
  75259. var _a;
  75260. if (!this._shadowMap) {
  75261. return this;
  75262. }
  75263. if (!this._shadowMap.renderList) {
  75264. this._shadowMap.renderList = [];
  75265. }
  75266. this._shadowMap.renderList.push(mesh);
  75267. if (includeDescendants) {
  75268. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  75269. }
  75270. return this;
  75271. };
  75272. /**
  75273. * Helper function to remove a mesh and its descendants from the list of shadow casters
  75274. * @param mesh Mesh to remove
  75275. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  75276. * @returns the Shadow Generator itself
  75277. */
  75278. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  75279. if (includeDescendants === void 0) { includeDescendants = true; }
  75280. if (!this._shadowMap || !this._shadowMap.renderList) {
  75281. return this;
  75282. }
  75283. var index = this._shadowMap.renderList.indexOf(mesh);
  75284. if (index !== -1) {
  75285. this._shadowMap.renderList.splice(index, 1);
  75286. }
  75287. if (includeDescendants) {
  75288. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  75289. var child = _a[_i];
  75290. this.removeShadowCaster(child);
  75291. }
  75292. }
  75293. return this;
  75294. };
  75295. /**
  75296. * Returns the associated light object.
  75297. * @returns the light generating the shadow
  75298. */
  75299. ShadowGenerator.prototype.getLight = function () {
  75300. return this._light;
  75301. };
  75302. ShadowGenerator.prototype._initializeGenerator = function () {
  75303. this._light._markMeshesAsLightDirty();
  75304. this._initializeShadowMap();
  75305. };
  75306. ShadowGenerator.prototype._initializeShadowMap = function () {
  75307. var _this = this;
  75308. // Render target
  75309. var engine = this._scene.getEngine();
  75310. if (engine.webGLVersion > 1) {
  75311. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  75312. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  75313. }
  75314. else {
  75315. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  75316. }
  75317. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75318. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75319. this._shadowMap.anisotropicFilteringLevel = 1;
  75320. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75321. this._shadowMap.renderParticles = false;
  75322. this._shadowMap.ignoreCameraViewport = true;
  75323. // Record Face Index before render.
  75324. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  75325. _this._currentFaceIndex = faceIndex;
  75326. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75327. engine.setColorWrite(false);
  75328. }
  75329. });
  75330. // Custom render function.
  75331. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  75332. // Blur if required afer render.
  75333. this._shadowMap.onAfterUnbindObservable.add(function () {
  75334. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75335. engine.setColorWrite(true);
  75336. }
  75337. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  75338. return;
  75339. }
  75340. var shadowMap = _this.getShadowMapForRendering();
  75341. if (shadowMap) {
  75342. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  75343. }
  75344. });
  75345. // Clear according to the chosen filter.
  75346. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  75347. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  75348. this._shadowMap.onClearObservable.add(function (engine) {
  75349. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75350. engine.clear(clearOne, false, true, false);
  75351. }
  75352. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  75353. engine.clear(clearZero, true, true, false);
  75354. }
  75355. else {
  75356. engine.clear(clearOne, true, true, false);
  75357. }
  75358. });
  75359. };
  75360. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  75361. var _this = this;
  75362. var engine = this._scene.getEngine();
  75363. var targetSize = this._mapSize / this.blurScale;
  75364. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  75365. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  75366. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75367. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75368. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75369. }
  75370. if (this.useKernelBlur) {
  75371. 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);
  75372. this._kernelBlurXPostprocess.width = targetSize;
  75373. this._kernelBlurXPostprocess.height = targetSize;
  75374. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  75375. effect.setTexture("textureSampler", _this._shadowMap);
  75376. });
  75377. 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);
  75378. this._kernelBlurXPostprocess.autoClear = false;
  75379. this._kernelBlurYPostprocess.autoClear = false;
  75380. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75381. this._kernelBlurXPostprocess.packedFloat = true;
  75382. this._kernelBlurYPostprocess.packedFloat = true;
  75383. }
  75384. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  75385. }
  75386. else {
  75387. 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);
  75388. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  75389. effect.setFloat2("screenSize", targetSize, targetSize);
  75390. effect.setTexture("textureSampler", _this._shadowMap);
  75391. });
  75392. this._boxBlurPostprocess.autoClear = false;
  75393. this._blurPostProcesses = [this._boxBlurPostprocess];
  75394. }
  75395. };
  75396. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75397. var index;
  75398. var engine = this._scene.getEngine();
  75399. if (depthOnlySubMeshes.length) {
  75400. engine.setColorWrite(false);
  75401. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75402. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  75403. }
  75404. engine.setColorWrite(true);
  75405. }
  75406. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75407. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  75408. }
  75409. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75410. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  75411. }
  75412. if (this._transparencyShadow) {
  75413. for (index = 0; index < transparentSubMeshes.length; index++) {
  75414. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  75415. }
  75416. }
  75417. };
  75418. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  75419. var _this = this;
  75420. var mesh = subMesh.getRenderingMesh();
  75421. var scene = this._scene;
  75422. var engine = scene.getEngine();
  75423. var material = subMesh.getMaterial();
  75424. if (!material) {
  75425. return;
  75426. }
  75427. // Culling
  75428. engine.setState(material.backFaceCulling);
  75429. // Managing instances
  75430. var batch = mesh._getInstancesRenderList(subMesh._id);
  75431. if (batch.mustReturn) {
  75432. return;
  75433. }
  75434. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75435. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  75436. engine.enableEffect(this._effect);
  75437. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75438. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  75439. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  75440. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75441. this._effect.setVector3("lightData", this._cachedDirection);
  75442. }
  75443. else {
  75444. this._effect.setVector3("lightData", this._cachedPosition);
  75445. }
  75446. if (scene.activeCamera) {
  75447. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  75448. }
  75449. // Alpha test
  75450. if (material && material.needAlphaTesting()) {
  75451. var alphaTexture = material.getAlphaTestTexture();
  75452. if (alphaTexture) {
  75453. this._effect.setTexture("diffuseSampler", alphaTexture);
  75454. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  75455. }
  75456. }
  75457. // Bones
  75458. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75459. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  75460. }
  75461. // Morph targets
  75462. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  75463. if (this.forceBackFacesOnly) {
  75464. engine.setState(true, 0, false, true);
  75465. }
  75466. // Draw
  75467. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75468. if (this.forceBackFacesOnly) {
  75469. engine.setState(true, 0, false, false);
  75470. }
  75471. }
  75472. else {
  75473. // Need to reset refresh rate of the shadowMap
  75474. if (this._shadowMap) {
  75475. this._shadowMap.resetRefreshCounter();
  75476. }
  75477. }
  75478. };
  75479. ShadowGenerator.prototype._applyFilterValues = function () {
  75480. if (!this._shadowMap) {
  75481. return;
  75482. }
  75483. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  75484. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  75485. }
  75486. else {
  75487. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75488. }
  75489. };
  75490. /**
  75491. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75492. * @param onCompiled Callback triggered at the and of the effects compilation
  75493. * @param options Sets of optional options forcing the compilation with different modes
  75494. */
  75495. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  75496. var _this = this;
  75497. var localOptions = __assign({ useInstances: false }, options);
  75498. var shadowMap = this.getShadowMap();
  75499. if (!shadowMap) {
  75500. if (onCompiled) {
  75501. onCompiled(this);
  75502. }
  75503. return;
  75504. }
  75505. var renderList = shadowMap.renderList;
  75506. if (!renderList) {
  75507. if (onCompiled) {
  75508. onCompiled(this);
  75509. }
  75510. return;
  75511. }
  75512. var subMeshes = new Array();
  75513. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  75514. var mesh = renderList_1[_i];
  75515. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  75516. }
  75517. if (subMeshes.length === 0) {
  75518. if (onCompiled) {
  75519. onCompiled(this);
  75520. }
  75521. return;
  75522. }
  75523. var currentIndex = 0;
  75524. var checkReady = function () {
  75525. if (!_this._scene || !_this._scene.getEngine()) {
  75526. return;
  75527. }
  75528. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  75529. currentIndex++;
  75530. if (currentIndex >= subMeshes.length) {
  75531. if (onCompiled) {
  75532. onCompiled(_this);
  75533. }
  75534. return;
  75535. }
  75536. }
  75537. setTimeout(checkReady, 16);
  75538. };
  75539. checkReady();
  75540. };
  75541. /**
  75542. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75543. * @param options Sets of optional options forcing the compilation with different modes
  75544. * @returns A promise that resolves when the compilation completes
  75545. */
  75546. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  75547. var _this = this;
  75548. return new Promise(function (resolve) {
  75549. _this.forceCompilation(function () {
  75550. resolve();
  75551. }, options);
  75552. });
  75553. };
  75554. /**
  75555. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  75556. * @param subMesh The submesh we want to render in the shadow map
  75557. * @param useInstances Defines wether will draw in the map using instances
  75558. * @returns true if ready otherwise, false
  75559. */
  75560. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  75561. var defines = [];
  75562. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75563. defines.push("#define FLOAT");
  75564. }
  75565. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75566. defines.push("#define ESM");
  75567. }
  75568. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  75569. defines.push("#define DEPTHTEXTURE");
  75570. }
  75571. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75572. var mesh = subMesh.getMesh();
  75573. var material = subMesh.getMaterial();
  75574. // Normal bias.
  75575. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75576. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75577. defines.push("#define NORMAL");
  75578. if (mesh.nonUniformScaling) {
  75579. defines.push("#define NONUNIFORMSCALING");
  75580. }
  75581. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75582. defines.push("#define DIRECTIONINLIGHTDATA");
  75583. }
  75584. }
  75585. // Alpha test
  75586. if (material && material.needAlphaTesting()) {
  75587. var alphaTexture = material.getAlphaTestTexture();
  75588. if (alphaTexture) {
  75589. defines.push("#define ALPHATEST");
  75590. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75591. attribs.push(BABYLON.VertexBuffer.UVKind);
  75592. defines.push("#define UV1");
  75593. }
  75594. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75595. if (alphaTexture.coordinatesIndex === 1) {
  75596. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75597. defines.push("#define UV2");
  75598. }
  75599. }
  75600. }
  75601. }
  75602. // Bones
  75603. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75604. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75605. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75606. if (mesh.numBoneInfluencers > 4) {
  75607. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75608. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75609. }
  75610. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75611. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  75612. }
  75613. else {
  75614. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75615. }
  75616. // Morph targets
  75617. var manager = mesh.morphTargetManager;
  75618. var morphInfluencers = 0;
  75619. if (manager) {
  75620. if (manager.numInfluencers > 0) {
  75621. defines.push("#define MORPHTARGETS");
  75622. morphInfluencers = manager.numInfluencers;
  75623. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  75624. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  75625. }
  75626. }
  75627. // Instances
  75628. if (useInstances) {
  75629. defines.push("#define INSTANCES");
  75630. attribs.push("world0");
  75631. attribs.push("world1");
  75632. attribs.push("world2");
  75633. attribs.push("world3");
  75634. }
  75635. // Get correct effect
  75636. var join = defines.join("\n");
  75637. if (this._cachedDefines !== join) {
  75638. this._cachedDefines = join;
  75639. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  75640. }
  75641. if (!this._effect.isReady()) {
  75642. return false;
  75643. }
  75644. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75645. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  75646. this._initializeBlurRTTAndPostProcesses();
  75647. }
  75648. }
  75649. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  75650. return false;
  75651. }
  75652. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  75653. return false;
  75654. }
  75655. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  75656. return false;
  75657. }
  75658. return true;
  75659. };
  75660. /**
  75661. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  75662. * @param defines Defines of the material we want to update
  75663. * @param lightIndex Index of the light in the enabled light list of the material
  75664. */
  75665. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  75666. var scene = this._scene;
  75667. var light = this._light;
  75668. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75669. return;
  75670. }
  75671. defines["SHADOW" + lightIndex] = true;
  75672. if (this.useContactHardeningShadow) {
  75673. defines["SHADOWPCSS" + lightIndex] = true;
  75674. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75675. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75676. }
  75677. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75678. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75679. }
  75680. // else default to high.
  75681. }
  75682. if (this.usePercentageCloserFiltering) {
  75683. defines["SHADOWPCF" + lightIndex] = true;
  75684. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75685. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75686. }
  75687. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75688. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75689. }
  75690. // else default to high.
  75691. }
  75692. else if (this.usePoissonSampling) {
  75693. defines["SHADOWPOISSON" + lightIndex] = true;
  75694. }
  75695. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75696. defines["SHADOWESM" + lightIndex] = true;
  75697. }
  75698. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75699. defines["SHADOWCLOSEESM" + lightIndex] = true;
  75700. }
  75701. if (light.needCube()) {
  75702. defines["SHADOWCUBE" + lightIndex] = true;
  75703. }
  75704. };
  75705. /**
  75706. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  75707. * defined in the generator but impacting the effect).
  75708. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  75709. * @param effect The effect we are binfing the information for
  75710. */
  75711. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  75712. var light = this._light;
  75713. var scene = this._scene;
  75714. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75715. return;
  75716. }
  75717. var camera = scene.activeCamera;
  75718. if (!camera) {
  75719. return;
  75720. }
  75721. var shadowMap = this.getShadowMap();
  75722. if (!shadowMap) {
  75723. return;
  75724. }
  75725. if (!light.needCube()) {
  75726. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  75727. }
  75728. // Only PCF uses depth stencil texture.
  75729. if (this._filter === ShadowGenerator.FILTER_PCF) {
  75730. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75731. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75732. }
  75733. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  75734. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75735. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  75736. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75737. }
  75738. else {
  75739. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75740. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  75741. }
  75742. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  75743. };
  75744. /**
  75745. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  75746. * (eq to shadow prjection matrix * light transform matrix)
  75747. * @returns The transform matrix used to create the shadow map
  75748. */
  75749. ShadowGenerator.prototype.getTransformMatrix = function () {
  75750. var scene = this._scene;
  75751. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  75752. return this._transformMatrix;
  75753. }
  75754. this._currentRenderID = scene.getRenderId();
  75755. this._currentFaceIndexCache = this._currentFaceIndex;
  75756. var lightPosition = this._light.position;
  75757. if (this._light.computeTransformedInformation()) {
  75758. lightPosition = this._light.transformedPosition;
  75759. }
  75760. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  75761. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  75762. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  75763. }
  75764. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  75765. this._cachedPosition.copyFrom(lightPosition);
  75766. this._cachedDirection.copyFrom(this._lightDirection);
  75767. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  75768. var shadowMap = this.getShadowMap();
  75769. if (shadowMap) {
  75770. var renderList = shadowMap.renderList;
  75771. if (renderList) {
  75772. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  75773. }
  75774. }
  75775. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  75776. }
  75777. return this._transformMatrix;
  75778. };
  75779. /**
  75780. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  75781. * Cube and 2D textures for instance.
  75782. */
  75783. ShadowGenerator.prototype.recreateShadowMap = function () {
  75784. var shadowMap = this._shadowMap;
  75785. if (!shadowMap) {
  75786. return;
  75787. }
  75788. // Track render list.
  75789. var renderList = shadowMap.renderList;
  75790. // Clean up existing data.
  75791. this._disposeRTTandPostProcesses();
  75792. // Reinitializes.
  75793. this._initializeGenerator();
  75794. // Reaffect the filter to ensure a correct fallback if necessary.
  75795. this.filter = this.filter;
  75796. // Reaffect the filter.
  75797. this._applyFilterValues();
  75798. // Reaffect Render List.
  75799. this._shadowMap.renderList = renderList;
  75800. };
  75801. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  75802. if (this._shadowMap2) {
  75803. this._shadowMap2.dispose();
  75804. this._shadowMap2 = null;
  75805. }
  75806. if (this._boxBlurPostprocess) {
  75807. this._boxBlurPostprocess.dispose();
  75808. this._boxBlurPostprocess = null;
  75809. }
  75810. if (this._kernelBlurXPostprocess) {
  75811. this._kernelBlurXPostprocess.dispose();
  75812. this._kernelBlurXPostprocess = null;
  75813. }
  75814. if (this._kernelBlurYPostprocess) {
  75815. this._kernelBlurYPostprocess.dispose();
  75816. this._kernelBlurYPostprocess = null;
  75817. }
  75818. this._blurPostProcesses = [];
  75819. };
  75820. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  75821. if (this._shadowMap) {
  75822. this._shadowMap.dispose();
  75823. this._shadowMap = null;
  75824. }
  75825. this._disposeBlurPostProcesses();
  75826. };
  75827. /**
  75828. * Disposes the ShadowGenerator.
  75829. * Returns nothing.
  75830. */
  75831. ShadowGenerator.prototype.dispose = function () {
  75832. this._disposeRTTandPostProcesses();
  75833. if (this._light) {
  75834. this._light._shadowGenerator = null;
  75835. this._light._markMeshesAsLightDirty();
  75836. }
  75837. };
  75838. /**
  75839. * Serializes the shadow generator setup to a json object.
  75840. * @returns The serialized JSON object
  75841. */
  75842. ShadowGenerator.prototype.serialize = function () {
  75843. var serializationObject = {};
  75844. var shadowMap = this.getShadowMap();
  75845. if (!shadowMap) {
  75846. return serializationObject;
  75847. }
  75848. serializationObject.lightId = this._light.id;
  75849. serializationObject.mapSize = shadowMap.getRenderSize();
  75850. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  75851. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  75852. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75853. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75854. serializationObject.usePoissonSampling = this.usePoissonSampling;
  75855. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  75856. serializationObject.depthScale = this.depthScale;
  75857. serializationObject.darkness = this.getDarkness();
  75858. serializationObject.blurBoxOffset = this.blurBoxOffset;
  75859. serializationObject.blurKernel = this.blurKernel;
  75860. serializationObject.blurScale = this.blurScale;
  75861. serializationObject.useKernelBlur = this.useKernelBlur;
  75862. serializationObject.transparencyShadow = this._transparencyShadow;
  75863. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  75864. serializationObject.bias = this.bias;
  75865. serializationObject.normalBias = this.normalBias;
  75866. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  75867. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  75868. serializationObject.filteringQuality = this.filteringQuality;
  75869. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  75870. serializationObject.renderList = [];
  75871. if (shadowMap.renderList) {
  75872. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  75873. var mesh = shadowMap.renderList[meshIndex];
  75874. serializationObject.renderList.push(mesh.id);
  75875. }
  75876. }
  75877. return serializationObject;
  75878. };
  75879. /**
  75880. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  75881. * @param parsedShadowGenerator The JSON object to parse
  75882. * @param scene The scene to create the shadow map for
  75883. * @returns The parsed shadow generator
  75884. */
  75885. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  75886. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  75887. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  75888. var shadowMap = shadowGenerator.getShadowMap();
  75889. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  75890. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  75891. meshes.forEach(function (mesh) {
  75892. if (!shadowMap) {
  75893. return;
  75894. }
  75895. if (!shadowMap.renderList) {
  75896. shadowMap.renderList = [];
  75897. }
  75898. shadowMap.renderList.push(mesh);
  75899. });
  75900. }
  75901. if (parsedShadowGenerator.usePoissonSampling) {
  75902. shadowGenerator.usePoissonSampling = true;
  75903. }
  75904. else if (parsedShadowGenerator.useExponentialShadowMap) {
  75905. shadowGenerator.useExponentialShadowMap = true;
  75906. }
  75907. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  75908. shadowGenerator.useBlurExponentialShadowMap = true;
  75909. }
  75910. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  75911. shadowGenerator.useCloseExponentialShadowMap = true;
  75912. }
  75913. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  75914. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  75915. }
  75916. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  75917. shadowGenerator.usePercentageCloserFiltering = true;
  75918. }
  75919. else if (parsedShadowGenerator.useContactHardeningShadow) {
  75920. shadowGenerator.useContactHardeningShadow = true;
  75921. }
  75922. if (parsedShadowGenerator.filteringQuality) {
  75923. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  75924. }
  75925. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  75926. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  75927. }
  75928. // Backward compat
  75929. else if (parsedShadowGenerator.useVarianceShadowMap) {
  75930. shadowGenerator.useExponentialShadowMap = true;
  75931. }
  75932. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  75933. shadowGenerator.useBlurExponentialShadowMap = true;
  75934. }
  75935. if (parsedShadowGenerator.depthScale) {
  75936. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  75937. }
  75938. if (parsedShadowGenerator.blurScale) {
  75939. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  75940. }
  75941. if (parsedShadowGenerator.blurBoxOffset) {
  75942. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  75943. }
  75944. if (parsedShadowGenerator.useKernelBlur) {
  75945. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  75946. }
  75947. if (parsedShadowGenerator.blurKernel) {
  75948. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  75949. }
  75950. if (parsedShadowGenerator.bias !== undefined) {
  75951. shadowGenerator.bias = parsedShadowGenerator.bias;
  75952. }
  75953. if (parsedShadowGenerator.normalBias !== undefined) {
  75954. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  75955. }
  75956. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  75957. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  75958. }
  75959. if (parsedShadowGenerator.darkness) {
  75960. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  75961. }
  75962. if (parsedShadowGenerator.transparencyShadow) {
  75963. shadowGenerator.setTransparencyShadow(true);
  75964. }
  75965. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  75966. return shadowGenerator;
  75967. };
  75968. /**
  75969. * Shadow generator mode None: no filtering applied.
  75970. */
  75971. ShadowGenerator.FILTER_NONE = 0;
  75972. /**
  75973. * Shadow generator mode ESM: Exponential Shadow Mapping.
  75974. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75975. */
  75976. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  75977. /**
  75978. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  75979. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  75980. */
  75981. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  75982. /**
  75983. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  75984. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75985. */
  75986. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  75987. /**
  75988. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  75989. * edge artifacts on steep falloff.
  75990. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75991. */
  75992. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  75993. /**
  75994. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  75995. * edge artifacts on steep falloff.
  75996. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75997. */
  75998. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  75999. /**
  76000. * Shadow generator mode PCF: Percentage Closer Filtering
  76001. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  76002. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  76003. */
  76004. ShadowGenerator.FILTER_PCF = 6;
  76005. /**
  76006. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  76007. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  76008. * Contact Hardening
  76009. */
  76010. ShadowGenerator.FILTER_PCSS = 7;
  76011. /**
  76012. * Reserved for PCF and PCSS
  76013. * Highest Quality.
  76014. *
  76015. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  76016. *
  76017. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  76018. */
  76019. ShadowGenerator.QUALITY_HIGH = 0;
  76020. /**
  76021. * Reserved for PCF and PCSS
  76022. * Good tradeoff for quality/perf cross devices
  76023. *
  76024. * Execute PCF on a 3*3 kernel.
  76025. *
  76026. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  76027. */
  76028. ShadowGenerator.QUALITY_MEDIUM = 1;
  76029. /**
  76030. * Reserved for PCF and PCSS
  76031. * The lowest quality but the fastest.
  76032. *
  76033. * Execute PCF on a 1*1 kernel.
  76034. *
  76035. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  76036. */
  76037. ShadowGenerator.QUALITY_LOW = 2;
  76038. return ShadowGenerator;
  76039. }());
  76040. BABYLON.ShadowGenerator = ShadowGenerator;
  76041. })(BABYLON || (BABYLON = {}));
  76042. //# sourceMappingURL=babylon.shadowGenerator.js.map
  76043. var BABYLON;
  76044. (function (BABYLON) {
  76045. // Adds the parser to the scene parsers.
  76046. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  76047. // Shadows
  76048. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  76049. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  76050. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  76051. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  76052. // SG would be available on their associated lights
  76053. }
  76054. }
  76055. });
  76056. /**
  76057. * Defines the shadow generator component responsible to manage any shadow generators
  76058. * in a given scene.
  76059. */
  76060. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  76061. /**
  76062. * Creates a new instance of the component for the given scene
  76063. * @param scene Defines the scene to register the component in
  76064. */
  76065. function ShadowGeneratorSceneComponent(scene) {
  76066. /**
  76067. * The component name helpfull to identify the component in the list of scene components.
  76068. */
  76069. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  76070. this.scene = scene;
  76071. }
  76072. /**
  76073. * Registers the component in a given scene
  76074. */
  76075. ShadowGeneratorSceneComponent.prototype.register = function () {
  76076. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  76077. };
  76078. /**
  76079. * Rebuilds the elements related to this component in case of
  76080. * context lost for instance.
  76081. */
  76082. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  76083. // Nothing To Do Here.
  76084. };
  76085. /**
  76086. * Serializes the component data to the specified json object
  76087. * @param serializationObject The object to serialize to
  76088. */
  76089. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  76090. // Shadows
  76091. serializationObject.shadowGenerators = [];
  76092. var lights = this.scene.lights;
  76093. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  76094. var light = lights_1[_i];
  76095. var shadowGenerator = light.getShadowGenerator();
  76096. if (shadowGenerator) {
  76097. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  76098. }
  76099. }
  76100. };
  76101. /**
  76102. * Adds all the element from the container to the scene
  76103. * @param container the container holding the elements
  76104. */
  76105. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  76106. // Nothing To Do Here. (directly attached to a light)
  76107. };
  76108. /**
  76109. * Removes all the elements in the container from the scene
  76110. * @param container contains the elements to remove
  76111. */
  76112. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  76113. // Nothing To Do Here. (directly attached to a light)
  76114. };
  76115. /**
  76116. * Rebuilds the elements related to this component in case of
  76117. * context lost for instance.
  76118. */
  76119. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  76120. // Nothing To Do Here.
  76121. };
  76122. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76123. // Shadows
  76124. var scene = this.scene;
  76125. if (this.scene.shadowsEnabled) {
  76126. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  76127. var light = scene.lights[lightIndex];
  76128. var shadowGenerator = light.getShadowGenerator();
  76129. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  76130. var shadowMap = (shadowGenerator.getShadowMap());
  76131. if (scene.textures.indexOf(shadowMap) !== -1) {
  76132. renderTargets.push(shadowMap);
  76133. }
  76134. }
  76135. }
  76136. }
  76137. };
  76138. return ShadowGeneratorSceneComponent;
  76139. }());
  76140. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  76141. })(BABYLON || (BABYLON = {}));
  76142. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  76143. var BABYLON;
  76144. (function (BABYLON) {
  76145. /**
  76146. * Class used for the default loading screen
  76147. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  76148. */
  76149. var DefaultLoadingScreen = /** @class */ (function () {
  76150. /**
  76151. * Creates a new default loading screen
  76152. * @param _renderingCanvas defines the canvas used to render the scene
  76153. * @param _loadingText defines the default text to display
  76154. * @param _loadingDivBackgroundColor defines the default background color
  76155. */
  76156. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  76157. if (_loadingText === void 0) { _loadingText = ""; }
  76158. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  76159. var _this = this;
  76160. this._renderingCanvas = _renderingCanvas;
  76161. this._loadingText = _loadingText;
  76162. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  76163. // Resize
  76164. this._resizeLoadingUI = function () {
  76165. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  76166. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  76167. if (!_this._loadingDiv) {
  76168. return;
  76169. }
  76170. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  76171. _this._loadingDiv.style.left = canvasRect.left + "px";
  76172. _this._loadingDiv.style.top = canvasRect.top + "px";
  76173. _this._loadingDiv.style.width = canvasRect.width + "px";
  76174. _this._loadingDiv.style.height = canvasRect.height + "px";
  76175. };
  76176. }
  76177. /**
  76178. * Function called to display the loading screen
  76179. */
  76180. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  76181. if (this._loadingDiv) {
  76182. // Do not add a loading screen if there is already one
  76183. return;
  76184. }
  76185. this._loadingDiv = document.createElement("div");
  76186. this._loadingDiv.id = "babylonjsLoadingDiv";
  76187. this._loadingDiv.style.opacity = "0";
  76188. this._loadingDiv.style.transition = "opacity 1.5s ease";
  76189. this._loadingDiv.style.pointerEvents = "none";
  76190. // Loading text
  76191. this._loadingTextDiv = document.createElement("div");
  76192. this._loadingTextDiv.style.position = "absolute";
  76193. this._loadingTextDiv.style.left = "0";
  76194. this._loadingTextDiv.style.top = "50%";
  76195. this._loadingTextDiv.style.marginTop = "80px";
  76196. this._loadingTextDiv.style.width = "100%";
  76197. this._loadingTextDiv.style.height = "20px";
  76198. this._loadingTextDiv.style.fontFamily = "Arial";
  76199. this._loadingTextDiv.style.fontSize = "14px";
  76200. this._loadingTextDiv.style.color = "white";
  76201. this._loadingTextDiv.style.textAlign = "center";
  76202. this._loadingTextDiv.innerHTML = "Loading";
  76203. this._loadingDiv.appendChild(this._loadingTextDiv);
  76204. //set the predefined text
  76205. this._loadingTextDiv.innerHTML = this._loadingText;
  76206. // Generating keyframes
  76207. var style = document.createElement('style');
  76208. style.type = 'text/css';
  76209. 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 }";
  76210. style.innerHTML = keyFrames;
  76211. document.getElementsByTagName('head')[0].appendChild(style);
  76212. // Loading img
  76213. var imgBack = new Image();
  76214. 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";
  76215. imgBack.style.position = "absolute";
  76216. imgBack.style.left = "50%";
  76217. imgBack.style.top = "50%";
  76218. imgBack.style.marginLeft = "-60px";
  76219. imgBack.style.marginTop = "-60px";
  76220. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  76221. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  76222. imgBack.style.transformOrigin = "50% 50%";
  76223. imgBack.style.webkitTransformOrigin = "50% 50%";
  76224. this._loadingDiv.appendChild(imgBack);
  76225. this._resizeLoadingUI();
  76226. window.addEventListener("resize", this._resizeLoadingUI);
  76227. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76228. document.body.appendChild(this._loadingDiv);
  76229. this._loadingDiv.style.opacity = "1";
  76230. };
  76231. /**
  76232. * Function called to hide the loading screen
  76233. */
  76234. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  76235. var _this = this;
  76236. if (!this._loadingDiv) {
  76237. return;
  76238. }
  76239. var onTransitionEnd = function () {
  76240. if (!_this._loadingDiv) {
  76241. return;
  76242. }
  76243. document.body.removeChild(_this._loadingDiv);
  76244. window.removeEventListener("resize", _this._resizeLoadingUI);
  76245. _this._loadingDiv = null;
  76246. };
  76247. this._loadingDiv.style.opacity = "0";
  76248. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  76249. };
  76250. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  76251. get: function () {
  76252. return this._loadingText;
  76253. },
  76254. /**
  76255. * Gets or sets the text to display while loading
  76256. */
  76257. set: function (text) {
  76258. this._loadingText = text;
  76259. if (this._loadingTextDiv) {
  76260. this._loadingTextDiv.innerHTML = this._loadingText;
  76261. }
  76262. },
  76263. enumerable: true,
  76264. configurable: true
  76265. });
  76266. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  76267. /**
  76268. * Gets or sets the color to use for the background
  76269. */
  76270. get: function () {
  76271. return this._loadingDivBackgroundColor;
  76272. },
  76273. set: function (color) {
  76274. this._loadingDivBackgroundColor = color;
  76275. if (!this._loadingDiv) {
  76276. return;
  76277. }
  76278. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76279. },
  76280. enumerable: true,
  76281. configurable: true
  76282. });
  76283. return DefaultLoadingScreen;
  76284. }());
  76285. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  76286. })(BABYLON || (BABYLON = {}));
  76287. //# sourceMappingURL=babylon.loadingScreen.js.map
  76288. var BABYLON;
  76289. (function (BABYLON) {
  76290. /**
  76291. * Class used to represent data loading progression
  76292. */
  76293. var SceneLoaderProgressEvent = /** @class */ (function () {
  76294. /**
  76295. * Create a new progress event
  76296. * @param lengthComputable defines if data length to load can be evaluated
  76297. * @param loaded defines the loaded data length
  76298. * @param total defines the data length to load
  76299. */
  76300. function SceneLoaderProgressEvent(
  76301. /** defines if data length to load can be evaluated */
  76302. lengthComputable,
  76303. /** defines the loaded data length */
  76304. loaded,
  76305. /** defines the data length to load */
  76306. total) {
  76307. this.lengthComputable = lengthComputable;
  76308. this.loaded = loaded;
  76309. this.total = total;
  76310. }
  76311. /**
  76312. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  76313. * @param event defines the source event
  76314. * @returns a new SceneLoaderProgressEvent
  76315. */
  76316. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  76317. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  76318. };
  76319. return SceneLoaderProgressEvent;
  76320. }());
  76321. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  76322. /**
  76323. * Class used to load scene from various file formats using registered plugins
  76324. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  76325. */
  76326. var SceneLoader = /** @class */ (function () {
  76327. function SceneLoader() {
  76328. }
  76329. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  76330. /**
  76331. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  76332. */
  76333. get: function () {
  76334. return SceneLoader._ForceFullSceneLoadingForIncremental;
  76335. },
  76336. set: function (value) {
  76337. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  76338. },
  76339. enumerable: true,
  76340. configurable: true
  76341. });
  76342. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  76343. /**
  76344. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  76345. */
  76346. get: function () {
  76347. return SceneLoader._ShowLoadingScreen;
  76348. },
  76349. set: function (value) {
  76350. SceneLoader._ShowLoadingScreen = value;
  76351. },
  76352. enumerable: true,
  76353. configurable: true
  76354. });
  76355. Object.defineProperty(SceneLoader, "loggingLevel", {
  76356. /**
  76357. * Defines the current logging level (while loading the scene)
  76358. * @ignorenaming
  76359. */
  76360. get: function () {
  76361. return SceneLoader._loggingLevel;
  76362. },
  76363. set: function (value) {
  76364. SceneLoader._loggingLevel = value;
  76365. },
  76366. enumerable: true,
  76367. configurable: true
  76368. });
  76369. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  76370. /**
  76371. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  76372. */
  76373. get: function () {
  76374. return SceneLoader._CleanBoneMatrixWeights;
  76375. },
  76376. set: function (value) {
  76377. SceneLoader._CleanBoneMatrixWeights = value;
  76378. },
  76379. enumerable: true,
  76380. configurable: true
  76381. });
  76382. SceneLoader._getDefaultPlugin = function () {
  76383. return SceneLoader._registeredPlugins[".babylon"];
  76384. };
  76385. SceneLoader._getPluginForExtension = function (extension) {
  76386. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  76387. if (registeredPlugin) {
  76388. return registeredPlugin;
  76389. }
  76390. 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");
  76391. return SceneLoader._getDefaultPlugin();
  76392. };
  76393. SceneLoader._getPluginForDirectLoad = function (data) {
  76394. for (var extension in SceneLoader._registeredPlugins) {
  76395. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  76396. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  76397. return SceneLoader._registeredPlugins[extension];
  76398. }
  76399. }
  76400. return SceneLoader._getDefaultPlugin();
  76401. };
  76402. SceneLoader._getPluginForFilename = function (sceneFilename) {
  76403. var queryStringPosition = sceneFilename.indexOf("?");
  76404. if (queryStringPosition !== -1) {
  76405. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  76406. }
  76407. var dotPosition = sceneFilename.lastIndexOf(".");
  76408. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  76409. return SceneLoader._getPluginForExtension(extension);
  76410. };
  76411. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  76412. SceneLoader._getDirectLoad = function (sceneFilename) {
  76413. if (sceneFilename.substr(0, 5) === "data:") {
  76414. return sceneFilename.substr(5);
  76415. }
  76416. return null;
  76417. };
  76418. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  76419. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  76420. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  76421. var plugin;
  76422. if (registeredPlugin.plugin.createPlugin) {
  76423. plugin = registeredPlugin.plugin.createPlugin();
  76424. }
  76425. else {
  76426. plugin = registeredPlugin.plugin;
  76427. }
  76428. var useArrayBuffer = registeredPlugin.isBinary;
  76429. var database;
  76430. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  76431. var dataCallback = function (data, responseURL) {
  76432. if (scene.isDisposed) {
  76433. onError("Scene has been disposed");
  76434. return;
  76435. }
  76436. scene.database = database;
  76437. onSuccess(plugin, data, responseURL);
  76438. };
  76439. var request = null;
  76440. var pluginDisposed = false;
  76441. var onDisposeObservable = plugin.onDisposeObservable;
  76442. if (onDisposeObservable) {
  76443. onDisposeObservable.add(function () {
  76444. pluginDisposed = true;
  76445. if (request) {
  76446. request.abort();
  76447. request = null;
  76448. }
  76449. onDispose();
  76450. });
  76451. }
  76452. var manifestChecked = function () {
  76453. if (pluginDisposed) {
  76454. return;
  76455. }
  76456. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  76457. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  76458. } : undefined, database, useArrayBuffer, function (request, exception) {
  76459. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  76460. });
  76461. };
  76462. if (directLoad) {
  76463. dataCallback(directLoad);
  76464. return plugin;
  76465. }
  76466. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  76467. var engine = scene.getEngine();
  76468. var canUseOfflineSupport = engine.enableOfflineSupport;
  76469. if (canUseOfflineSupport) {
  76470. // Also check for exceptions
  76471. var exceptionFound = false;
  76472. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  76473. var regex = _a[_i];
  76474. if (regex.test(fileInfo.url)) {
  76475. exceptionFound = true;
  76476. break;
  76477. }
  76478. }
  76479. canUseOfflineSupport = !exceptionFound;
  76480. }
  76481. if (canUseOfflineSupport) {
  76482. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  76483. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  76484. }
  76485. else {
  76486. manifestChecked();
  76487. }
  76488. }
  76489. // Loading file from disk via input file or drag'n'drop
  76490. else {
  76491. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  76492. if (file) {
  76493. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  76494. }
  76495. else {
  76496. onError("Unable to find file named " + fileInfo.name);
  76497. }
  76498. }
  76499. return plugin;
  76500. };
  76501. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  76502. var url;
  76503. var name;
  76504. if (!sceneFilename) {
  76505. url = rootUrl;
  76506. name = BABYLON.Tools.GetFilename(rootUrl);
  76507. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  76508. }
  76509. else {
  76510. if (sceneFilename.substr(0, 1) === "/") {
  76511. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  76512. return null;
  76513. }
  76514. url = rootUrl + sceneFilename;
  76515. name = sceneFilename;
  76516. }
  76517. return {
  76518. url: url,
  76519. rootUrl: rootUrl,
  76520. name: name
  76521. };
  76522. };
  76523. // Public functions
  76524. /**
  76525. * Gets a plugin that can load the given extension
  76526. * @param extension defines the extension to load
  76527. * @returns a plugin or null if none works
  76528. */
  76529. SceneLoader.GetPluginForExtension = function (extension) {
  76530. return SceneLoader._getPluginForExtension(extension).plugin;
  76531. };
  76532. /**
  76533. * Gets a boolean indicating that the given extension can be loaded
  76534. * @param extension defines the extension to load
  76535. * @returns true if the extension is supported
  76536. */
  76537. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  76538. return !!SceneLoader._registeredPlugins[extension];
  76539. };
  76540. /**
  76541. * Adds a new plugin to the list of registered plugins
  76542. * @param plugin defines the plugin to add
  76543. */
  76544. SceneLoader.RegisterPlugin = function (plugin) {
  76545. if (typeof plugin.extensions === "string") {
  76546. var extension = plugin.extensions;
  76547. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76548. plugin: plugin,
  76549. isBinary: false
  76550. };
  76551. }
  76552. else {
  76553. var extensions = plugin.extensions;
  76554. Object.keys(extensions).forEach(function (extension) {
  76555. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76556. plugin: plugin,
  76557. isBinary: extensions[extension].isBinary
  76558. };
  76559. });
  76560. }
  76561. };
  76562. /**
  76563. * Import meshes into a scene
  76564. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76565. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76566. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76567. * @param scene the instance of BABYLON.Scene to append to
  76568. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  76569. * @param onProgress a callback with a progress event for each file being loaded
  76570. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76571. * @param pluginExtension the extension used to determine the plugin
  76572. * @returns The loaded plugin
  76573. */
  76574. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76575. if (sceneFilename === void 0) { sceneFilename = ""; }
  76576. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76577. if (onSuccess === void 0) { onSuccess = null; }
  76578. if (onProgress === void 0) { onProgress = null; }
  76579. if (onError === void 0) { onError = null; }
  76580. if (pluginExtension === void 0) { pluginExtension = null; }
  76581. if (!scene) {
  76582. BABYLON.Tools.Error("No scene available to import mesh to");
  76583. return null;
  76584. }
  76585. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76586. if (!fileInfo) {
  76587. return null;
  76588. }
  76589. var loadingToken = {};
  76590. scene._addPendingData(loadingToken);
  76591. var disposeHandler = function () {
  76592. scene._removePendingData(loadingToken);
  76593. };
  76594. var errorHandler = function (message, exception) {
  76595. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  76596. if (onError) {
  76597. onError(scene, errorMessage, exception);
  76598. }
  76599. else {
  76600. BABYLON.Tools.Error(errorMessage);
  76601. // should the exception be thrown?
  76602. }
  76603. disposeHandler();
  76604. };
  76605. var progressHandler = onProgress ? function (event) {
  76606. try {
  76607. onProgress(event);
  76608. }
  76609. catch (e) {
  76610. errorHandler("Error in onProgress callback", e);
  76611. }
  76612. } : undefined;
  76613. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  76614. scene.importedMeshesFiles.push(fileInfo.url);
  76615. if (onSuccess) {
  76616. try {
  76617. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  76618. }
  76619. catch (e) {
  76620. errorHandler("Error in onSuccess callback", e);
  76621. }
  76622. }
  76623. scene._removePendingData(loadingToken);
  76624. };
  76625. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76626. if (plugin.rewriteRootURL) {
  76627. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  76628. }
  76629. if (plugin.importMesh) {
  76630. var syncedPlugin = plugin;
  76631. var meshes = new Array();
  76632. var particleSystems = new Array();
  76633. var skeletons = new Array();
  76634. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  76635. return;
  76636. }
  76637. scene.loadingPluginName = plugin.name;
  76638. successHandler(meshes, particleSystems, skeletons, []);
  76639. }
  76640. else {
  76641. var asyncedPlugin = plugin;
  76642. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  76643. scene.loadingPluginName = plugin.name;
  76644. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  76645. }).catch(function (error) {
  76646. errorHandler(error.message, error);
  76647. });
  76648. }
  76649. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76650. };
  76651. /**
  76652. * Import meshes into a scene
  76653. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76654. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76655. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76656. * @param scene the instance of BABYLON.Scene to append to
  76657. * @param onProgress a callback with a progress event for each file being loaded
  76658. * @param pluginExtension the extension used to determine the plugin
  76659. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  76660. */
  76661. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76662. if (sceneFilename === void 0) { sceneFilename = ""; }
  76663. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76664. if (onProgress === void 0) { onProgress = null; }
  76665. if (pluginExtension === void 0) { pluginExtension = null; }
  76666. return new Promise(function (resolve, reject) {
  76667. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  76668. resolve({
  76669. meshes: meshes,
  76670. particleSystems: particleSystems,
  76671. skeletons: skeletons,
  76672. animationGroups: animationGroups
  76673. });
  76674. }, onProgress, function (scene, message, exception) {
  76675. reject(exception || new Error(message));
  76676. }, pluginExtension);
  76677. });
  76678. };
  76679. /**
  76680. * Load a scene
  76681. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76682. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76683. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76684. * @param onSuccess a callback with the scene when import succeeds
  76685. * @param onProgress a callback with a progress event for each file being loaded
  76686. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76687. * @param pluginExtension the extension used to determine the plugin
  76688. * @returns The loaded plugin
  76689. */
  76690. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  76691. if (onSuccess === void 0) { onSuccess = null; }
  76692. if (onProgress === void 0) { onProgress = null; }
  76693. if (onError === void 0) { onError = null; }
  76694. if (pluginExtension === void 0) { pluginExtension = null; }
  76695. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  76696. };
  76697. /**
  76698. * Load a scene
  76699. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76700. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76701. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76702. * @param onProgress a callback with a progress event for each file being loaded
  76703. * @param pluginExtension the extension used to determine the plugin
  76704. * @returns The loaded scene
  76705. */
  76706. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  76707. if (onProgress === void 0) { onProgress = null; }
  76708. if (pluginExtension === void 0) { pluginExtension = null; }
  76709. return new Promise(function (resolve, reject) {
  76710. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  76711. resolve(scene);
  76712. }, onProgress, function (scene, message, exception) {
  76713. reject(exception || new Error(message));
  76714. }, pluginExtension);
  76715. });
  76716. };
  76717. /**
  76718. * Append a scene
  76719. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76720. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76721. * @param scene is the instance of BABYLON.Scene to append to
  76722. * @param onSuccess a callback with the scene when import succeeds
  76723. * @param onProgress a callback with a progress event for each file being loaded
  76724. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76725. * @param pluginExtension the extension used to determine the plugin
  76726. * @returns The loaded plugin
  76727. */
  76728. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76729. if (sceneFilename === void 0) { sceneFilename = ""; }
  76730. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76731. if (onSuccess === void 0) { onSuccess = null; }
  76732. if (onProgress === void 0) { onProgress = null; }
  76733. if (onError === void 0) { onError = null; }
  76734. if (pluginExtension === void 0) { pluginExtension = null; }
  76735. if (!scene) {
  76736. BABYLON.Tools.Error("No scene available to append to");
  76737. return null;
  76738. }
  76739. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76740. if (!fileInfo) {
  76741. return null;
  76742. }
  76743. if (SceneLoader.ShowLoadingScreen) {
  76744. scene.getEngine().displayLoadingUI();
  76745. }
  76746. var loadingToken = {};
  76747. scene._addPendingData(loadingToken);
  76748. var disposeHandler = function () {
  76749. scene._removePendingData(loadingToken);
  76750. scene.getEngine().hideLoadingUI();
  76751. };
  76752. var errorHandler = function (message, exception) {
  76753. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  76754. if (onError) {
  76755. onError(scene, errorMessage, exception);
  76756. }
  76757. else {
  76758. BABYLON.Tools.Error(errorMessage);
  76759. // should the exception be thrown?
  76760. }
  76761. disposeHandler();
  76762. };
  76763. var progressHandler = onProgress ? function (event) {
  76764. try {
  76765. onProgress(event);
  76766. }
  76767. catch (e) {
  76768. errorHandler("Error in onProgress callback", e);
  76769. }
  76770. } : undefined;
  76771. var successHandler = function () {
  76772. if (onSuccess) {
  76773. try {
  76774. onSuccess(scene);
  76775. }
  76776. catch (e) {
  76777. errorHandler("Error in onSuccess callback", e);
  76778. }
  76779. }
  76780. scene._removePendingData(loadingToken);
  76781. };
  76782. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76783. if (plugin.load) {
  76784. var syncedPlugin = plugin;
  76785. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  76786. return;
  76787. }
  76788. scene.loadingPluginName = plugin.name;
  76789. successHandler();
  76790. }
  76791. else {
  76792. var asyncedPlugin = plugin;
  76793. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  76794. scene.loadingPluginName = plugin.name;
  76795. successHandler();
  76796. }).catch(function (error) {
  76797. errorHandler(error.message, error);
  76798. });
  76799. }
  76800. if (SceneLoader.ShowLoadingScreen) {
  76801. scene.executeWhenReady(function () {
  76802. scene.getEngine().hideLoadingUI();
  76803. });
  76804. }
  76805. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76806. };
  76807. /**
  76808. * Append a scene
  76809. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76810. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76811. * @param scene is the instance of BABYLON.Scene to append to
  76812. * @param onProgress a callback with a progress event for each file being loaded
  76813. * @param pluginExtension the extension used to determine the plugin
  76814. * @returns The given scene
  76815. */
  76816. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76817. if (sceneFilename === void 0) { sceneFilename = ""; }
  76818. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76819. if (onProgress === void 0) { onProgress = null; }
  76820. if (pluginExtension === void 0) { pluginExtension = null; }
  76821. return new Promise(function (resolve, reject) {
  76822. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  76823. resolve(scene);
  76824. }, onProgress, function (scene, message, exception) {
  76825. reject(exception || new Error(message));
  76826. }, pluginExtension);
  76827. });
  76828. };
  76829. /**
  76830. * Load a scene into an asset container
  76831. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76832. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76833. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  76834. * @param onSuccess a callback with the scene when import succeeds
  76835. * @param onProgress a callback with a progress event for each file being loaded
  76836. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76837. * @param pluginExtension the extension used to determine the plugin
  76838. * @returns The loaded plugin
  76839. */
  76840. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76841. if (sceneFilename === void 0) { sceneFilename = ""; }
  76842. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76843. if (onSuccess === void 0) { onSuccess = null; }
  76844. if (onProgress === void 0) { onProgress = null; }
  76845. if (onError === void 0) { onError = null; }
  76846. if (pluginExtension === void 0) { pluginExtension = null; }
  76847. if (!scene) {
  76848. BABYLON.Tools.Error("No scene available to load asset container to");
  76849. return null;
  76850. }
  76851. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76852. if (!fileInfo) {
  76853. return null;
  76854. }
  76855. var loadingToken = {};
  76856. scene._addPendingData(loadingToken);
  76857. var disposeHandler = function () {
  76858. scene._removePendingData(loadingToken);
  76859. };
  76860. var errorHandler = function (message, exception) {
  76861. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  76862. if (onError) {
  76863. onError(scene, errorMessage, exception);
  76864. }
  76865. else {
  76866. BABYLON.Tools.Error(errorMessage);
  76867. // should the exception be thrown?
  76868. }
  76869. disposeHandler();
  76870. };
  76871. var progressHandler = onProgress ? function (event) {
  76872. try {
  76873. onProgress(event);
  76874. }
  76875. catch (e) {
  76876. errorHandler("Error in onProgress callback", e);
  76877. }
  76878. } : undefined;
  76879. var successHandler = function (assets) {
  76880. if (onSuccess) {
  76881. try {
  76882. onSuccess(assets);
  76883. }
  76884. catch (e) {
  76885. errorHandler("Error in onSuccess callback", e);
  76886. }
  76887. }
  76888. scene._removePendingData(loadingToken);
  76889. };
  76890. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76891. if (plugin.loadAssetContainer) {
  76892. var syncedPlugin = plugin;
  76893. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  76894. if (!assetContainer) {
  76895. return;
  76896. }
  76897. scene.loadingPluginName = plugin.name;
  76898. successHandler(assetContainer);
  76899. }
  76900. else if (plugin.loadAssetContainerAsync) {
  76901. var asyncedPlugin = plugin;
  76902. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  76903. scene.loadingPluginName = plugin.name;
  76904. successHandler(assetContainer);
  76905. }).catch(function (error) {
  76906. errorHandler(error.message, error);
  76907. });
  76908. }
  76909. else {
  76910. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  76911. }
  76912. if (SceneLoader.ShowLoadingScreen) {
  76913. scene.executeWhenReady(function () {
  76914. scene.getEngine().hideLoadingUI();
  76915. });
  76916. }
  76917. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76918. };
  76919. /**
  76920. * Load a scene into an asset container
  76921. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  76922. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  76923. * @param scene is the instance of BABYLON.Scene to append to
  76924. * @param onProgress a callback with a progress event for each file being loaded
  76925. * @param pluginExtension the extension used to determine the plugin
  76926. * @returns The loaded asset container
  76927. */
  76928. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76929. if (sceneFilename === void 0) { sceneFilename = ""; }
  76930. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76931. if (onProgress === void 0) { onProgress = null; }
  76932. if (pluginExtension === void 0) { pluginExtension = null; }
  76933. return new Promise(function (resolve, reject) {
  76934. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  76935. resolve(assetContainer);
  76936. }, onProgress, function (scene, message, exception) {
  76937. reject(exception || new Error(message));
  76938. }, pluginExtension);
  76939. });
  76940. };
  76941. // Flags
  76942. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  76943. SceneLoader._ShowLoadingScreen = true;
  76944. SceneLoader._CleanBoneMatrixWeights = false;
  76945. /**
  76946. * No logging while loading
  76947. */
  76948. SceneLoader.NO_LOGGING = 0;
  76949. /**
  76950. * Minimal logging while loading
  76951. */
  76952. SceneLoader.MINIMAL_LOGGING = 1;
  76953. /**
  76954. * Summary logging while loading
  76955. */
  76956. SceneLoader.SUMMARY_LOGGING = 2;
  76957. /**
  76958. * Detailled logging while loading
  76959. */
  76960. SceneLoader.DETAILED_LOGGING = 3;
  76961. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  76962. // Members
  76963. /**
  76964. * Event raised when a plugin is used to load a scene
  76965. */
  76966. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  76967. SceneLoader._registeredPlugins = {};
  76968. return SceneLoader;
  76969. }());
  76970. BABYLON.SceneLoader = SceneLoader;
  76971. })(BABYLON || (BABYLON = {}));
  76972. //# sourceMappingURL=babylon.sceneLoader.js.map
  76973. var BABYLON;
  76974. (function (BABYLON) {
  76975. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  76976. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76977. var parsedMaterial = parsedData.materials[index];
  76978. if (parsedMaterial.id === id) {
  76979. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76980. }
  76981. }
  76982. return null;
  76983. };
  76984. var isDescendantOf = function (mesh, names, hierarchyIds) {
  76985. for (var i in names) {
  76986. if (mesh.name === names[i]) {
  76987. hierarchyIds.push(mesh.id);
  76988. return true;
  76989. }
  76990. }
  76991. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  76992. hierarchyIds.push(mesh.id);
  76993. return true;
  76994. }
  76995. return false;
  76996. };
  76997. var logOperation = function (operation, producer) {
  76998. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  76999. };
  77000. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  77001. if (addToScene === void 0) { addToScene = false; }
  77002. var container = new BABYLON.AssetContainer(scene);
  77003. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77004. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77005. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77006. // and avoid problems with multiple concurrent .babylon loads.
  77007. var log = "importScene has failed JSON parse";
  77008. try {
  77009. var parsedData = JSON.parse(data);
  77010. log = "";
  77011. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77012. var index;
  77013. var cache;
  77014. // Lights
  77015. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  77016. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  77017. var parsedLight = parsedData.lights[index];
  77018. var light = BABYLON.Light.Parse(parsedLight, scene);
  77019. if (light) {
  77020. container.lights.push(light);
  77021. log += (index === 0 ? "\n\tLights:" : "");
  77022. log += "\n\t\t" + light.toString(fullDetails);
  77023. }
  77024. }
  77025. }
  77026. // Animations
  77027. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  77028. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  77029. var parsedAnimation = parsedData.animations[index];
  77030. var animation = BABYLON.Animation.Parse(parsedAnimation);
  77031. scene.animations.push(animation);
  77032. container.animations.push(animation);
  77033. log += (index === 0 ? "\n\tAnimations:" : "");
  77034. log += "\n\t\t" + animation.toString(fullDetails);
  77035. }
  77036. }
  77037. // Materials
  77038. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  77039. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  77040. var parsedMaterial = parsedData.materials[index];
  77041. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  77042. container.materials.push(mat);
  77043. log += (index === 0 ? "\n\tMaterials:" : "");
  77044. log += "\n\t\t" + mat.toString(fullDetails);
  77045. }
  77046. }
  77047. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77048. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  77049. var parsedMultiMaterial = parsedData.multiMaterials[index];
  77050. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77051. container.multiMaterials.push(mmat);
  77052. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  77053. log += "\n\t\t" + mmat.toString(fullDetails);
  77054. }
  77055. }
  77056. // Morph targets
  77057. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77058. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77059. var managerData = _a[_i];
  77060. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  77061. }
  77062. }
  77063. // Skeletons
  77064. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77065. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  77066. var parsedSkeleton = parsedData.skeletons[index];
  77067. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77068. container.skeletons.push(skeleton);
  77069. log += (index === 0 ? "\n\tSkeletons:" : "");
  77070. log += "\n\t\t" + skeleton.toString(fullDetails);
  77071. }
  77072. }
  77073. // Geometries
  77074. var geometries = parsedData.geometries;
  77075. if (geometries !== undefined && geometries !== null) {
  77076. var addedGeometry = new Array();
  77077. // Boxes
  77078. var boxes = geometries.boxes;
  77079. if (boxes !== undefined && boxes !== null) {
  77080. for (index = 0, cache = boxes.length; index < cache; index++) {
  77081. var parsedBox = boxes[index];
  77082. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  77083. }
  77084. }
  77085. // Spheres
  77086. var spheres = geometries.spheres;
  77087. if (spheres !== undefined && spheres !== null) {
  77088. for (index = 0, cache = spheres.length; index < cache; index++) {
  77089. var parsedSphere = spheres[index];
  77090. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  77091. }
  77092. }
  77093. // Cylinders
  77094. var cylinders = geometries.cylinders;
  77095. if (cylinders !== undefined && cylinders !== null) {
  77096. for (index = 0, cache = cylinders.length; index < cache; index++) {
  77097. var parsedCylinder = cylinders[index];
  77098. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  77099. }
  77100. }
  77101. // Toruses
  77102. var toruses = geometries.toruses;
  77103. if (toruses !== undefined && toruses !== null) {
  77104. for (index = 0, cache = toruses.length; index < cache; index++) {
  77105. var parsedTorus = toruses[index];
  77106. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  77107. }
  77108. }
  77109. // Grounds
  77110. var grounds = geometries.grounds;
  77111. if (grounds !== undefined && grounds !== null) {
  77112. for (index = 0, cache = grounds.length; index < cache; index++) {
  77113. var parsedGround = grounds[index];
  77114. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  77115. }
  77116. }
  77117. // Planes
  77118. var planes = geometries.planes;
  77119. if (planes !== undefined && planes !== null) {
  77120. for (index = 0, cache = planes.length; index < cache; index++) {
  77121. var parsedPlane = planes[index];
  77122. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  77123. }
  77124. }
  77125. // TorusKnots
  77126. var torusKnots = geometries.torusKnots;
  77127. if (torusKnots !== undefined && torusKnots !== null) {
  77128. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  77129. var parsedTorusKnot = torusKnots[index];
  77130. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  77131. }
  77132. }
  77133. // VertexData
  77134. var vertexData = geometries.vertexData;
  77135. if (vertexData !== undefined && vertexData !== null) {
  77136. for (index = 0, cache = vertexData.length; index < cache; index++) {
  77137. var parsedVertexData = vertexData[index];
  77138. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  77139. }
  77140. }
  77141. addedGeometry.forEach(function (g) {
  77142. if (g) {
  77143. container.geometries.push(g);
  77144. }
  77145. });
  77146. }
  77147. // Transform nodes
  77148. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  77149. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  77150. var parsedTransformNode = parsedData.transformNodes[index];
  77151. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  77152. container.transformNodes.push(node);
  77153. }
  77154. }
  77155. // Meshes
  77156. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77157. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77158. var parsedMesh = parsedData.meshes[index];
  77159. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77160. container.meshes.push(mesh);
  77161. log += (index === 0 ? "\n\tMeshes:" : "");
  77162. log += "\n\t\t" + mesh.toString(fullDetails);
  77163. }
  77164. }
  77165. // Cameras
  77166. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  77167. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  77168. var parsedCamera = parsedData.cameras[index];
  77169. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  77170. container.cameras.push(camera);
  77171. log += (index === 0 ? "\n\tCameras:" : "");
  77172. log += "\n\t\t" + camera.toString(fullDetails);
  77173. }
  77174. }
  77175. // Animation Groups
  77176. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  77177. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  77178. var parsedAnimationGroup = parsedData.animationGroups[index];
  77179. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  77180. container.animationGroups.push(animationGroup);
  77181. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  77182. log += "\n\t\t" + animationGroup.toString(fullDetails);
  77183. }
  77184. }
  77185. // Browsing all the graph to connect the dots
  77186. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  77187. var camera = scene.cameras[index];
  77188. if (camera._waitingParentId) {
  77189. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  77190. camera._waitingParentId = null;
  77191. }
  77192. }
  77193. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  77194. var light_1 = scene.lights[index];
  77195. if (light_1 && light_1._waitingParentId) {
  77196. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  77197. light_1._waitingParentId = null;
  77198. }
  77199. }
  77200. // Connect parents & children and parse actions
  77201. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  77202. var transformNode = scene.transformNodes[index];
  77203. if (transformNode._waitingParentId) {
  77204. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  77205. transformNode._waitingParentId = null;
  77206. }
  77207. }
  77208. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77209. var mesh = scene.meshes[index];
  77210. if (mesh._waitingParentId) {
  77211. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  77212. mesh._waitingParentId = null;
  77213. }
  77214. }
  77215. // freeze world matrix application
  77216. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77217. var currentMesh = scene.meshes[index];
  77218. if (currentMesh._waitingFreezeWorldMatrix) {
  77219. currentMesh.freezeWorldMatrix();
  77220. currentMesh._waitingFreezeWorldMatrix = null;
  77221. }
  77222. else {
  77223. currentMesh.computeWorldMatrix(true);
  77224. }
  77225. }
  77226. // Lights exclusions / inclusions
  77227. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  77228. var light_2 = scene.lights[index];
  77229. // Excluded check
  77230. if (light_2._excludedMeshesIds.length > 0) {
  77231. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  77232. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  77233. if (excludedMesh) {
  77234. light_2.excludedMeshes.push(excludedMesh);
  77235. }
  77236. }
  77237. light_2._excludedMeshesIds = [];
  77238. }
  77239. // Included check
  77240. if (light_2._includedOnlyMeshesIds.length > 0) {
  77241. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  77242. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  77243. if (includedOnlyMesh) {
  77244. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  77245. }
  77246. }
  77247. light_2._includedOnlyMeshesIds = [];
  77248. }
  77249. }
  77250. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  77251. // Actions (scene) Done last as it can access other objects.
  77252. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77253. var mesh = scene.meshes[index];
  77254. if (mesh._waitingActions) {
  77255. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  77256. mesh._waitingActions = null;
  77257. }
  77258. }
  77259. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  77260. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  77261. }
  77262. if (!addToScene) {
  77263. container.removeAllFromScene();
  77264. }
  77265. }
  77266. catch (err) {
  77267. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  77268. if (onError) {
  77269. onError(msg, err);
  77270. }
  77271. else {
  77272. BABYLON.Tools.Log(msg);
  77273. throw err;
  77274. }
  77275. }
  77276. finally {
  77277. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77278. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77279. }
  77280. }
  77281. return container;
  77282. };
  77283. BABYLON.SceneLoader.RegisterPlugin({
  77284. name: "babylon.js",
  77285. extensions: ".babylon",
  77286. canDirectLoad: function (data) {
  77287. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  77288. return true;
  77289. }
  77290. return false;
  77291. },
  77292. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  77293. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77294. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77295. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77296. // and avoid problems with multiple concurrent .babylon loads.
  77297. var log = "importMesh has failed JSON parse";
  77298. try {
  77299. var parsedData = JSON.parse(data);
  77300. log = "";
  77301. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77302. if (!meshesNames) {
  77303. meshesNames = null;
  77304. }
  77305. else if (!Array.isArray(meshesNames)) {
  77306. meshesNames = [meshesNames];
  77307. }
  77308. var hierarchyIds = new Array();
  77309. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77310. var loadedSkeletonsIds = [];
  77311. var loadedMaterialsIds = [];
  77312. var index;
  77313. var cache;
  77314. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77315. var parsedMesh = parsedData.meshes[index];
  77316. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  77317. if (meshesNames !== null) {
  77318. // Remove found mesh name from list.
  77319. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  77320. }
  77321. //Geometry?
  77322. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  77323. //does the file contain geometries?
  77324. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  77325. //find the correct geometry and add it to the scene
  77326. var found = false;
  77327. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  77328. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  77329. return;
  77330. }
  77331. else {
  77332. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  77333. if (parsedGeometryData.id === parsedMesh.geometryId) {
  77334. switch (geometryType) {
  77335. case "boxes":
  77336. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  77337. break;
  77338. case "spheres":
  77339. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  77340. break;
  77341. case "cylinders":
  77342. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  77343. break;
  77344. case "toruses":
  77345. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  77346. break;
  77347. case "grounds":
  77348. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  77349. break;
  77350. case "planes":
  77351. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  77352. break;
  77353. case "torusKnots":
  77354. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  77355. break;
  77356. case "vertexData":
  77357. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  77358. break;
  77359. }
  77360. found = true;
  77361. }
  77362. });
  77363. }
  77364. });
  77365. if (found === false) {
  77366. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  77367. }
  77368. }
  77369. }
  77370. // Material ?
  77371. if (parsedMesh.materialId) {
  77372. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  77373. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77374. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  77375. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  77376. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  77377. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  77378. var subMatId = parsedMultiMaterial.materials[matIndex];
  77379. loadedMaterialsIds.push(subMatId);
  77380. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  77381. if (mat) {
  77382. log += "\n\tMaterial " + mat.toString(fullDetails);
  77383. }
  77384. }
  77385. loadedMaterialsIds.push(parsedMultiMaterial.id);
  77386. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77387. if (mmat) {
  77388. materialFound = true;
  77389. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  77390. }
  77391. break;
  77392. }
  77393. }
  77394. }
  77395. if (materialFound === false) {
  77396. loadedMaterialsIds.push(parsedMesh.materialId);
  77397. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  77398. if (!mat) {
  77399. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  77400. }
  77401. else {
  77402. log += "\n\tMaterial " + mat.toString(fullDetails);
  77403. }
  77404. }
  77405. }
  77406. // Skeleton ?
  77407. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77408. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  77409. if (skeletonAlreadyLoaded === false) {
  77410. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  77411. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  77412. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  77413. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77414. skeletons.push(skeleton);
  77415. loadedSkeletonsIds.push(parsedSkeleton.id);
  77416. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  77417. }
  77418. }
  77419. }
  77420. }
  77421. // Morph targets ?
  77422. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77423. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77424. var managerData = _a[_i];
  77425. BABYLON.MorphTargetManager.Parse(managerData, scene);
  77426. }
  77427. }
  77428. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77429. meshes.push(mesh);
  77430. log += "\n\tMesh " + mesh.toString(fullDetails);
  77431. }
  77432. }
  77433. // Connecting parents
  77434. var currentMesh;
  77435. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77436. currentMesh = scene.meshes[index];
  77437. if (currentMesh._waitingParentId) {
  77438. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  77439. currentMesh._waitingParentId = null;
  77440. }
  77441. }
  77442. // freeze and compute world matrix application
  77443. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77444. currentMesh = scene.meshes[index];
  77445. if (currentMesh._waitingFreezeWorldMatrix) {
  77446. currentMesh.freezeWorldMatrix();
  77447. currentMesh._waitingFreezeWorldMatrix = null;
  77448. }
  77449. else {
  77450. currentMesh.computeWorldMatrix(true);
  77451. }
  77452. }
  77453. }
  77454. // Particles
  77455. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  77456. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  77457. if (parser) {
  77458. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  77459. var parsedParticleSystem = parsedData.particleSystems[index];
  77460. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  77461. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  77462. }
  77463. }
  77464. }
  77465. }
  77466. return true;
  77467. }
  77468. catch (err) {
  77469. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  77470. if (onError) {
  77471. onError(msg, err);
  77472. }
  77473. else {
  77474. BABYLON.Tools.Log(msg);
  77475. throw err;
  77476. }
  77477. }
  77478. finally {
  77479. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77480. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77481. }
  77482. }
  77483. return false;
  77484. },
  77485. load: function (scene, data, rootUrl, onError) {
  77486. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77487. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77488. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77489. // and avoid problems with multiple concurrent .babylon loads.
  77490. var log = "importScene has failed JSON parse";
  77491. try {
  77492. var parsedData = JSON.parse(data);
  77493. log = "";
  77494. // Scene
  77495. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  77496. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  77497. }
  77498. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  77499. scene.autoClear = parsedData.autoClear;
  77500. }
  77501. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  77502. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  77503. }
  77504. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  77505. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  77506. }
  77507. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  77508. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  77509. }
  77510. // Fog
  77511. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  77512. scene.fogMode = parsedData.fogMode;
  77513. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  77514. scene.fogStart = parsedData.fogStart;
  77515. scene.fogEnd = parsedData.fogEnd;
  77516. scene.fogDensity = parsedData.fogDensity;
  77517. log += "\tFog mode for scene: ";
  77518. switch (scene.fogMode) {
  77519. // getters not compiling, so using hardcoded
  77520. case 1:
  77521. log += "exp\n";
  77522. break;
  77523. case 2:
  77524. log += "exp2\n";
  77525. break;
  77526. case 3:
  77527. log += "linear\n";
  77528. break;
  77529. }
  77530. }
  77531. //Physics
  77532. if (parsedData.physicsEnabled) {
  77533. var physicsPlugin;
  77534. if (parsedData.physicsEngine === "cannon") {
  77535. physicsPlugin = new BABYLON.CannonJSPlugin();
  77536. }
  77537. else if (parsedData.physicsEngine === "oimo") {
  77538. physicsPlugin = new BABYLON.OimoJSPlugin();
  77539. }
  77540. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  77541. //else - default engine, which is currently oimo
  77542. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  77543. scene.enablePhysics(physicsGravity, physicsPlugin);
  77544. }
  77545. // Metadata
  77546. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  77547. scene.metadata = parsedData.metadata;
  77548. }
  77549. //collisions, if defined. otherwise, default is true
  77550. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  77551. scene.collisionsEnabled = parsedData.collisionsEnabled;
  77552. }
  77553. scene.workerCollisions = !!parsedData.workerCollisions;
  77554. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  77555. if (!container) {
  77556. return false;
  77557. }
  77558. if (parsedData.autoAnimate) {
  77559. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  77560. }
  77561. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  77562. scene.setActiveCameraByID(parsedData.activeCameraID);
  77563. }
  77564. // Environment texture
  77565. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  77566. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  77567. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  77568. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  77569. if (parsedData.environmentTextureRotationY) {
  77570. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  77571. }
  77572. scene.environmentTexture = hdrTexture;
  77573. }
  77574. else {
  77575. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  77576. if (parsedData.environmentTextureRotationY) {
  77577. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  77578. }
  77579. scene.environmentTexture = cubeTexture;
  77580. }
  77581. if (parsedData.createDefaultSkybox === true) {
  77582. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  77583. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  77584. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  77585. }
  77586. }
  77587. // Finish
  77588. return true;
  77589. }
  77590. catch (err) {
  77591. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  77592. if (onError) {
  77593. onError(msg, err);
  77594. }
  77595. else {
  77596. BABYLON.Tools.Log(msg);
  77597. throw err;
  77598. }
  77599. }
  77600. finally {
  77601. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77602. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77603. }
  77604. }
  77605. return false;
  77606. },
  77607. loadAssetContainer: function (scene, data, rootUrl, onError) {
  77608. var container = loadAssetContainer(scene, data, rootUrl, onError);
  77609. return container;
  77610. }
  77611. });
  77612. })(BABYLON || (BABYLON = {}));
  77613. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  77614. var BABYLON;
  77615. (function (BABYLON) {
  77616. /**
  77617. * Class used to help managing file picking and drag'n'drop
  77618. */
  77619. var FilesInput = /** @class */ (function () {
  77620. /**
  77621. * Creates a new FilesInput
  77622. * @param engine defines the rendering engine
  77623. * @param scene defines the hosting scene
  77624. * @param sceneLoadedCallback callback called when scene is loaded
  77625. * @param progressCallback callback called to track progress
  77626. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  77627. * @param textureLoadingCallback callback called when a texture is loading
  77628. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  77629. * @param onReloadCallback callback called when a reload is requested
  77630. * @param errorCallback callback call if an error occurs
  77631. */
  77632. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  77633. /**
  77634. * Callback called when a file is processed
  77635. */
  77636. this.onProcessFileCallback = function () { return true; };
  77637. this._engine = engine;
  77638. this._currentScene = scene;
  77639. this._sceneLoadedCallback = sceneLoadedCallback;
  77640. this._progressCallback = progressCallback;
  77641. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  77642. this._textureLoadingCallback = textureLoadingCallback;
  77643. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  77644. this._onReloadCallback = onReloadCallback;
  77645. this._errorCallback = errorCallback;
  77646. }
  77647. /**
  77648. * Calls this function to listen to drag'n'drop events on a specific DOM element
  77649. * @param elementToMonitor defines the DOM element to track
  77650. */
  77651. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  77652. var _this = this;
  77653. if (elementToMonitor) {
  77654. this._elementToMonitor = elementToMonitor;
  77655. this._dragEnterHandler = function (e) { _this.drag(e); };
  77656. this._dragOverHandler = function (e) { _this.drag(e); };
  77657. this._dropHandler = function (e) { _this.drop(e); };
  77658. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  77659. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  77660. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  77661. }
  77662. };
  77663. /**
  77664. * Release all associated resources
  77665. */
  77666. FilesInput.prototype.dispose = function () {
  77667. if (!this._elementToMonitor) {
  77668. return;
  77669. }
  77670. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  77671. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  77672. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  77673. };
  77674. FilesInput.prototype.renderFunction = function () {
  77675. if (this._additionalRenderLoopLogicCallback) {
  77676. this._additionalRenderLoopLogicCallback();
  77677. }
  77678. if (this._currentScene) {
  77679. if (this._textureLoadingCallback) {
  77680. var remaining = this._currentScene.getWaitingItemsCount();
  77681. if (remaining > 0) {
  77682. this._textureLoadingCallback(remaining);
  77683. }
  77684. }
  77685. this._currentScene.render();
  77686. }
  77687. };
  77688. FilesInput.prototype.drag = function (e) {
  77689. e.stopPropagation();
  77690. e.preventDefault();
  77691. };
  77692. FilesInput.prototype.drop = function (eventDrop) {
  77693. eventDrop.stopPropagation();
  77694. eventDrop.preventDefault();
  77695. this.loadFiles(eventDrop);
  77696. };
  77697. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  77698. var _this = this;
  77699. var reader = folder.createReader();
  77700. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  77701. reader.readEntries(function (entries) {
  77702. remaining.count += entries.length;
  77703. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  77704. var entry = entries_1[_i];
  77705. if (entry.isFile) {
  77706. entry.file(function (file) {
  77707. file.correctName = relativePath + file.name;
  77708. files.push(file);
  77709. if (--remaining.count === 0) {
  77710. callback();
  77711. }
  77712. });
  77713. }
  77714. else if (entry.isDirectory) {
  77715. _this._traverseFolder(entry, files, remaining, callback);
  77716. }
  77717. }
  77718. if (--remaining.count) {
  77719. callback();
  77720. }
  77721. });
  77722. };
  77723. FilesInput.prototype._processFiles = function (files) {
  77724. for (var i = 0; i < files.length; i++) {
  77725. var name = files[i].correctName.toLowerCase();
  77726. var extension = name.split('.').pop();
  77727. if (!this.onProcessFileCallback(files[i], name, extension)) {
  77728. continue;
  77729. }
  77730. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  77731. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  77732. this._sceneFileToLoad = files[i];
  77733. }
  77734. FilesInput.FilesToLoad[name] = files[i];
  77735. }
  77736. };
  77737. /**
  77738. * Load files from a drop event
  77739. * @param event defines the drop event to use as source
  77740. */
  77741. FilesInput.prototype.loadFiles = function (event) {
  77742. var _this = this;
  77743. // Handling data transfer via drag'n'drop
  77744. if (event && event.dataTransfer && event.dataTransfer.files) {
  77745. this._filesToLoad = event.dataTransfer.files;
  77746. }
  77747. // Handling files from input files
  77748. if (event && event.target && event.target.files) {
  77749. this._filesToLoad = event.target.files;
  77750. }
  77751. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  77752. return;
  77753. }
  77754. if (this._startingProcessingFilesCallback) {
  77755. this._startingProcessingFilesCallback(this._filesToLoad);
  77756. }
  77757. if (this._filesToLoad && this._filesToLoad.length > 0) {
  77758. var files_1 = new Array();
  77759. var folders = [];
  77760. var items = event.dataTransfer ? event.dataTransfer.items : null;
  77761. for (var i = 0; i < this._filesToLoad.length; i++) {
  77762. var fileToLoad = this._filesToLoad[i];
  77763. var name_1 = fileToLoad.name.toLowerCase();
  77764. var entry = void 0;
  77765. fileToLoad.correctName = name_1;
  77766. if (items) {
  77767. var item = items[i];
  77768. if (item.getAsEntry) {
  77769. entry = item.getAsEntry();
  77770. }
  77771. else if (item.webkitGetAsEntry) {
  77772. entry = item.webkitGetAsEntry();
  77773. }
  77774. }
  77775. if (!entry) {
  77776. files_1.push(fileToLoad);
  77777. }
  77778. else {
  77779. if (entry.isDirectory) {
  77780. folders.push(entry);
  77781. }
  77782. else {
  77783. files_1.push(fileToLoad);
  77784. }
  77785. }
  77786. }
  77787. if (folders.length === 0) {
  77788. this._processFiles(files_1);
  77789. this._processReload();
  77790. }
  77791. else {
  77792. var remaining = { count: folders.length };
  77793. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  77794. var folder = folders_1[_i];
  77795. this._traverseFolder(folder, files_1, remaining, function () {
  77796. _this._processFiles(files_1);
  77797. if (remaining.count === 0) {
  77798. _this._processReload();
  77799. }
  77800. });
  77801. }
  77802. }
  77803. }
  77804. };
  77805. FilesInput.prototype._processReload = function () {
  77806. if (this._onReloadCallback) {
  77807. this._onReloadCallback(this._sceneFileToLoad);
  77808. }
  77809. else {
  77810. this.reload();
  77811. }
  77812. };
  77813. /**
  77814. * Reload the current scene from the loaded files
  77815. */
  77816. FilesInput.prototype.reload = function () {
  77817. var _this = this;
  77818. // If a scene file has been provided
  77819. if (this._sceneFileToLoad) {
  77820. if (this._currentScene) {
  77821. if (BABYLON.Tools.errorsCount > 0) {
  77822. BABYLON.Tools.ClearLogCache();
  77823. }
  77824. this._engine.stopRenderLoop();
  77825. }
  77826. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  77827. if (_this._progressCallback) {
  77828. _this._progressCallback(progress);
  77829. }
  77830. }).then(function (scene) {
  77831. if (_this._currentScene) {
  77832. _this._currentScene.dispose();
  77833. }
  77834. _this._currentScene = scene;
  77835. if (_this._sceneLoadedCallback) {
  77836. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  77837. }
  77838. // Wait for textures and shaders to be ready
  77839. _this._currentScene.executeWhenReady(function () {
  77840. _this._engine.runRenderLoop(function () {
  77841. _this.renderFunction();
  77842. });
  77843. });
  77844. }).catch(function (error) {
  77845. if (_this._errorCallback) {
  77846. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  77847. }
  77848. });
  77849. }
  77850. else {
  77851. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  77852. }
  77853. };
  77854. /**
  77855. * List of files ready to be loaded
  77856. */
  77857. FilesInput.FilesToLoad = {};
  77858. return FilesInput;
  77859. }());
  77860. BABYLON.FilesInput = FilesInput;
  77861. })(BABYLON || (BABYLON = {}));
  77862. //# sourceMappingURL=babylon.filesInput.js.map
  77863. var BABYLON;
  77864. (function (BABYLON) {
  77865. /**
  77866. * Class used to store custom tags
  77867. */
  77868. var Tags = /** @class */ (function () {
  77869. function Tags() {
  77870. }
  77871. /**
  77872. * Adds support for tags on the given object
  77873. * @param obj defines the object to use
  77874. */
  77875. Tags.EnableFor = function (obj) {
  77876. obj._tags = obj._tags || {};
  77877. obj.hasTags = function () {
  77878. return Tags.HasTags(obj);
  77879. };
  77880. obj.addTags = function (tagsString) {
  77881. return Tags.AddTagsTo(obj, tagsString);
  77882. };
  77883. obj.removeTags = function (tagsString) {
  77884. return Tags.RemoveTagsFrom(obj, tagsString);
  77885. };
  77886. obj.matchesTagsQuery = function (tagsQuery) {
  77887. return Tags.MatchesQuery(obj, tagsQuery);
  77888. };
  77889. };
  77890. /**
  77891. * Removes tags support
  77892. * @param obj defines the object to use
  77893. */
  77894. Tags.DisableFor = function (obj) {
  77895. delete obj._tags;
  77896. delete obj.hasTags;
  77897. delete obj.addTags;
  77898. delete obj.removeTags;
  77899. delete obj.matchesTagsQuery;
  77900. };
  77901. /**
  77902. * Gets a boolean indicating if the given object has tags
  77903. * @param obj defines the object to use
  77904. * @returns a boolean
  77905. */
  77906. Tags.HasTags = function (obj) {
  77907. if (!obj._tags) {
  77908. return false;
  77909. }
  77910. return !BABYLON.Tools.IsEmpty(obj._tags);
  77911. };
  77912. /**
  77913. * Gets the tags available on a given object
  77914. * @param obj defines the object to use
  77915. * @param asString defines if the tags must be returned as a string instead of an array of strings
  77916. * @returns the tags
  77917. */
  77918. Tags.GetTags = function (obj, asString) {
  77919. if (asString === void 0) { asString = true; }
  77920. if (!obj._tags) {
  77921. return null;
  77922. }
  77923. if (asString) {
  77924. var tagsArray = [];
  77925. for (var tag in obj._tags) {
  77926. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  77927. tagsArray.push(tag);
  77928. }
  77929. }
  77930. return tagsArray.join(" ");
  77931. }
  77932. else {
  77933. return obj._tags;
  77934. }
  77935. };
  77936. /**
  77937. * Adds tags to an object
  77938. * @param obj defines the object to use
  77939. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  77940. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  77941. */
  77942. Tags.AddTagsTo = function (obj, tagsString) {
  77943. if (!tagsString) {
  77944. return;
  77945. }
  77946. if (typeof tagsString !== "string") {
  77947. return;
  77948. }
  77949. var tags = tagsString.split(" ");
  77950. tags.forEach(function (tag, index, array) {
  77951. Tags._AddTagTo(obj, tag);
  77952. });
  77953. };
  77954. /**
  77955. * @hidden
  77956. */
  77957. Tags._AddTagTo = function (obj, tag) {
  77958. tag = tag.trim();
  77959. if (tag === "" || tag === "true" || tag === "false") {
  77960. return;
  77961. }
  77962. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  77963. return;
  77964. }
  77965. Tags.EnableFor(obj);
  77966. obj._tags[tag] = true;
  77967. };
  77968. /**
  77969. * Removes specific tags from a specific object
  77970. * @param obj defines the object to use
  77971. * @param tagsString defines the tags to remove
  77972. */
  77973. Tags.RemoveTagsFrom = function (obj, tagsString) {
  77974. if (!Tags.HasTags(obj)) {
  77975. return;
  77976. }
  77977. var tags = tagsString.split(" ");
  77978. for (var t in tags) {
  77979. Tags._RemoveTagFrom(obj, tags[t]);
  77980. }
  77981. };
  77982. /**
  77983. * @hidden
  77984. */
  77985. Tags._RemoveTagFrom = function (obj, tag) {
  77986. delete obj._tags[tag];
  77987. };
  77988. /**
  77989. * Defines if tags hosted on an object match a given query
  77990. * @param obj defines the object to use
  77991. * @param tagsQuery defines the tag query
  77992. * @returns a boolean
  77993. */
  77994. Tags.MatchesQuery = function (obj, tagsQuery) {
  77995. if (tagsQuery === undefined) {
  77996. return true;
  77997. }
  77998. if (tagsQuery === "") {
  77999. return Tags.HasTags(obj);
  78000. }
  78001. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  78002. };
  78003. return Tags;
  78004. }());
  78005. BABYLON.Tags = Tags;
  78006. })(BABYLON || (BABYLON = {}));
  78007. //# sourceMappingURL=babylon.tags.js.map
  78008. var BABYLON;
  78009. (function (BABYLON) {
  78010. /**
  78011. * Class used to evalaute queries containing `and` and `or` operators
  78012. */
  78013. var AndOrNotEvaluator = /** @class */ (function () {
  78014. function AndOrNotEvaluator() {
  78015. }
  78016. /**
  78017. * Evaluate a query
  78018. * @param query defines the query to evaluate
  78019. * @param evaluateCallback defines the callback used to filter result
  78020. * @returns true if the query matches
  78021. */
  78022. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  78023. if (!query.match(/\([^\(\)]*\)/g)) {
  78024. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  78025. }
  78026. else {
  78027. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  78028. // remove parenthesis
  78029. r = r.slice(1, r.length - 1);
  78030. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  78031. });
  78032. }
  78033. if (query === "true") {
  78034. return true;
  78035. }
  78036. if (query === "false") {
  78037. return false;
  78038. }
  78039. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  78040. };
  78041. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  78042. evaluateCallback = evaluateCallback || (function (r) {
  78043. return r === "true" ? true : false;
  78044. });
  78045. var result;
  78046. var or = parenthesisContent.split("||");
  78047. for (var i in or) {
  78048. if (or.hasOwnProperty(i)) {
  78049. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  78050. var and = ori.split("&&");
  78051. if (and.length > 1) {
  78052. for (var j = 0; j < and.length; ++j) {
  78053. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  78054. if (andj !== "true" && andj !== "false") {
  78055. if (andj[0] === "!") {
  78056. result = !evaluateCallback(andj.substring(1));
  78057. }
  78058. else {
  78059. result = evaluateCallback(andj);
  78060. }
  78061. }
  78062. else {
  78063. result = andj === "true" ? true : false;
  78064. }
  78065. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  78066. ori = "false";
  78067. break;
  78068. }
  78069. }
  78070. }
  78071. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  78072. result = true;
  78073. break;
  78074. }
  78075. // result equals false (or undefined)
  78076. if (ori !== "true" && ori !== "false") {
  78077. if (ori[0] === "!") {
  78078. result = !evaluateCallback(ori.substring(1));
  78079. }
  78080. else {
  78081. result = evaluateCallback(ori);
  78082. }
  78083. }
  78084. else {
  78085. result = ori === "true" ? true : false;
  78086. }
  78087. }
  78088. }
  78089. // the whole parenthesis scope is replaced by 'true' or 'false'
  78090. return result ? "true" : "false";
  78091. };
  78092. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  78093. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  78094. // remove whitespaces
  78095. r = r.replace(/[\s]/g, function () { return ""; });
  78096. return r.length % 2 ? "!" : "";
  78097. });
  78098. booleanString = booleanString.trim();
  78099. if (booleanString === "!true") {
  78100. booleanString = "false";
  78101. }
  78102. else if (booleanString === "!false") {
  78103. booleanString = "true";
  78104. }
  78105. return booleanString;
  78106. };
  78107. return AndOrNotEvaluator;
  78108. }());
  78109. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  78110. })(BABYLON || (BABYLON = {}));
  78111. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  78112. var BABYLON;
  78113. (function (BABYLON) {
  78114. /**
  78115. * Class used to enable access to IndexedDB
  78116. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  78117. */
  78118. var Database = /** @class */ (function () {
  78119. /**
  78120. * Creates a new Database
  78121. * @param urlToScene defines the url to load the scene
  78122. * @param callbackManifestChecked defines the callback to use when manifest is checked
  78123. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  78124. */
  78125. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  78126. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  78127. var _this = this;
  78128. // Handling various flavors of prefixed version of IndexedDB
  78129. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  78130. this.callbackManifestChecked = callbackManifestChecked;
  78131. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  78132. this.db = null;
  78133. this._enableSceneOffline = false;
  78134. this._enableTexturesOffline = false;
  78135. this.manifestVersionFound = 0;
  78136. this.mustUpdateRessources = false;
  78137. this.hasReachedQuota = false;
  78138. if (!Database.IDBStorageEnabled) {
  78139. this.callbackManifestChecked(true);
  78140. }
  78141. else {
  78142. if (disableManifestCheck) {
  78143. this._enableSceneOffline = true;
  78144. this._enableTexturesOffline = true;
  78145. this.manifestVersionFound = 1;
  78146. BABYLON.Tools.SetImmediate(function () {
  78147. _this.callbackManifestChecked(true);
  78148. });
  78149. }
  78150. else {
  78151. this._checkManifestFile();
  78152. }
  78153. }
  78154. }
  78155. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  78156. /**
  78157. * Gets a boolean indicating if scene must be saved in the database
  78158. */
  78159. get: function () {
  78160. return this._enableSceneOffline;
  78161. },
  78162. enumerable: true,
  78163. configurable: true
  78164. });
  78165. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  78166. /**
  78167. * Gets a boolean indicating if textures must be saved in the database
  78168. */
  78169. get: function () {
  78170. return this._enableTexturesOffline;
  78171. },
  78172. enumerable: true,
  78173. configurable: true
  78174. });
  78175. Database.prototype._checkManifestFile = function () {
  78176. var _this = this;
  78177. var noManifestFile = function () {
  78178. _this._enableSceneOffline = false;
  78179. _this._enableTexturesOffline = false;
  78180. _this.callbackManifestChecked(false);
  78181. };
  78182. var timeStampUsed = false;
  78183. var manifestURL = this.currentSceneUrl + ".manifest";
  78184. var xhr = new XMLHttpRequest();
  78185. if (navigator.onLine) {
  78186. // Adding a timestamp to by-pass browsers' cache
  78187. timeStampUsed = true;
  78188. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  78189. }
  78190. xhr.open("GET", manifestURL, true);
  78191. xhr.addEventListener("load", function () {
  78192. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78193. try {
  78194. var manifestFile = JSON.parse(xhr.response);
  78195. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  78196. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  78197. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  78198. _this.manifestVersionFound = manifestFile.version;
  78199. }
  78200. if (_this.callbackManifestChecked) {
  78201. _this.callbackManifestChecked(true);
  78202. }
  78203. }
  78204. catch (ex) {
  78205. noManifestFile();
  78206. }
  78207. }
  78208. else {
  78209. noManifestFile();
  78210. }
  78211. }, false);
  78212. xhr.addEventListener("error", function (event) {
  78213. if (timeStampUsed) {
  78214. timeStampUsed = false;
  78215. // Let's retry without the timeStamp
  78216. // It could fail when coupled with HTML5 Offline API
  78217. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  78218. xhr.open("GET", retryManifestURL, true);
  78219. xhr.send();
  78220. }
  78221. else {
  78222. noManifestFile();
  78223. }
  78224. }, false);
  78225. try {
  78226. xhr.send();
  78227. }
  78228. catch (ex) {
  78229. BABYLON.Tools.Error("Error on XHR send request.");
  78230. this.callbackManifestChecked(false);
  78231. }
  78232. };
  78233. /**
  78234. * Open the database and make it available
  78235. * @param successCallback defines the callback to call on success
  78236. * @param errorCallback defines the callback to call on error
  78237. */
  78238. Database.prototype.openAsync = function (successCallback, errorCallback) {
  78239. var _this = this;
  78240. var handleError = function () {
  78241. _this.isSupported = false;
  78242. if (errorCallback) {
  78243. errorCallback();
  78244. }
  78245. };
  78246. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  78247. // Your browser doesn't support IndexedDB
  78248. this.isSupported = false;
  78249. if (errorCallback) {
  78250. errorCallback();
  78251. }
  78252. }
  78253. else {
  78254. // If the DB hasn't been opened or created yet
  78255. if (!this.db) {
  78256. this.hasReachedQuota = false;
  78257. this.isSupported = true;
  78258. var request = this.idbFactory.open("babylonjs", 1);
  78259. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  78260. request.onerror = function (event) {
  78261. handleError();
  78262. };
  78263. // executes when a version change transaction cannot complete due to other active transactions
  78264. request.onblocked = function (event) {
  78265. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  78266. handleError();
  78267. };
  78268. // DB has been opened successfully
  78269. request.onsuccess = function (event) {
  78270. _this.db = request.result;
  78271. successCallback();
  78272. };
  78273. // Initialization of the DB. Creating Scenes & Textures stores
  78274. request.onupgradeneeded = function (event) {
  78275. _this.db = (event.target).result;
  78276. if (_this.db) {
  78277. try {
  78278. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  78279. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  78280. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  78281. }
  78282. catch (ex) {
  78283. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  78284. handleError();
  78285. }
  78286. }
  78287. };
  78288. }
  78289. // DB has already been created and opened
  78290. else {
  78291. if (successCallback) {
  78292. successCallback();
  78293. }
  78294. }
  78295. }
  78296. };
  78297. /**
  78298. * Loads an image from the database
  78299. * @param url defines the url to load from
  78300. * @param image defines the target DOM image
  78301. */
  78302. Database.prototype.loadImageFromDB = function (url, image) {
  78303. var _this = this;
  78304. var completeURL = Database._ReturnFullUrlLocation(url);
  78305. var saveAndLoadImage = function () {
  78306. if (!_this.hasReachedQuota && _this.db !== null) {
  78307. // the texture is not yet in the DB, let's try to save it
  78308. _this._saveImageIntoDBAsync(completeURL, image);
  78309. }
  78310. // If the texture is not in the DB and we've reached the DB quota limit
  78311. // let's load it directly from the web
  78312. else {
  78313. image.src = url;
  78314. }
  78315. };
  78316. if (!this.mustUpdateRessources) {
  78317. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  78318. }
  78319. // First time we're download the images or update requested in the manifest file by a version change
  78320. else {
  78321. saveAndLoadImage();
  78322. }
  78323. };
  78324. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  78325. if (this.isSupported && this.db !== null) {
  78326. var texture;
  78327. var transaction = this.db.transaction(["textures"]);
  78328. transaction.onabort = function (event) {
  78329. image.src = url;
  78330. };
  78331. transaction.oncomplete = function (event) {
  78332. var blobTextureURL;
  78333. if (texture) {
  78334. var URL = window.URL || window.webkitURL;
  78335. blobTextureURL = URL.createObjectURL(texture.data);
  78336. image.onerror = function () {
  78337. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  78338. image.src = url;
  78339. };
  78340. image.src = blobTextureURL;
  78341. }
  78342. else {
  78343. notInDBCallback();
  78344. }
  78345. };
  78346. var getRequest = transaction.objectStore("textures").get(url);
  78347. getRequest.onsuccess = function (event) {
  78348. texture = (event.target).result;
  78349. };
  78350. getRequest.onerror = function (event) {
  78351. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  78352. image.src = url;
  78353. };
  78354. }
  78355. else {
  78356. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78357. image.src = url;
  78358. }
  78359. };
  78360. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  78361. var _this = this;
  78362. if (this.isSupported) {
  78363. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  78364. var generateBlobUrl = function () {
  78365. var blobTextureURL;
  78366. if (blob) {
  78367. var URL = window.URL || window.webkitURL;
  78368. try {
  78369. blobTextureURL = URL.createObjectURL(blob);
  78370. }
  78371. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  78372. catch (ex) {
  78373. blobTextureURL = URL.createObjectURL(blob);
  78374. }
  78375. }
  78376. if (blobTextureURL) {
  78377. image.src = blobTextureURL;
  78378. }
  78379. };
  78380. if (Database.IsUASupportingBlobStorage) { // Create XHR
  78381. var xhr = new XMLHttpRequest(), blob;
  78382. xhr.open("GET", url, true);
  78383. xhr.responseType = "blob";
  78384. xhr.addEventListener("load", function () {
  78385. if (xhr.status === 200 && _this.db) {
  78386. // Blob as response (XHR2)
  78387. blob = xhr.response;
  78388. var transaction = _this.db.transaction(["textures"], "readwrite");
  78389. // the transaction could abort because of a QuotaExceededError error
  78390. transaction.onabort = function (event) {
  78391. try {
  78392. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78393. var srcElement = (event.srcElement || event.target);
  78394. var error = srcElement.error;
  78395. if (error && error.name === "QuotaExceededError") {
  78396. _this.hasReachedQuota = true;
  78397. }
  78398. }
  78399. catch (ex) { }
  78400. generateBlobUrl();
  78401. };
  78402. transaction.oncomplete = function (event) {
  78403. generateBlobUrl();
  78404. };
  78405. var newTexture = { textureUrl: url, data: blob };
  78406. try {
  78407. // Put the blob into the dabase
  78408. var addRequest = transaction.objectStore("textures").put(newTexture);
  78409. addRequest.onsuccess = function (event) {
  78410. };
  78411. addRequest.onerror = function (event) {
  78412. generateBlobUrl();
  78413. };
  78414. }
  78415. catch (ex) {
  78416. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  78417. if (ex.code === 25) {
  78418. Database.IsUASupportingBlobStorage = false;
  78419. }
  78420. image.src = url;
  78421. }
  78422. }
  78423. else {
  78424. image.src = url;
  78425. }
  78426. }, false);
  78427. xhr.addEventListener("error", function (event) {
  78428. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  78429. image.src = url;
  78430. }, false);
  78431. xhr.send();
  78432. }
  78433. else {
  78434. image.src = url;
  78435. }
  78436. }
  78437. else {
  78438. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78439. image.src = url;
  78440. }
  78441. };
  78442. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  78443. var _this = this;
  78444. var updateVersion = function () {
  78445. // the version is not yet in the DB or we need to update it
  78446. _this._saveVersionIntoDBAsync(url, versionLoaded);
  78447. };
  78448. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  78449. };
  78450. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  78451. var _this = this;
  78452. if (this.isSupported && this.db) {
  78453. var version;
  78454. try {
  78455. var transaction = this.db.transaction(["versions"]);
  78456. transaction.oncomplete = function (event) {
  78457. if (version) {
  78458. // If the version in the JSON file is different from the version in DB
  78459. if (_this.manifestVersionFound !== version.data) {
  78460. _this.mustUpdateRessources = true;
  78461. updateInDBCallback();
  78462. }
  78463. else {
  78464. callback(version.data);
  78465. }
  78466. }
  78467. // version was not found in DB
  78468. else {
  78469. _this.mustUpdateRessources = true;
  78470. updateInDBCallback();
  78471. }
  78472. };
  78473. transaction.onabort = function (event) {
  78474. callback(-1);
  78475. };
  78476. var getRequest = transaction.objectStore("versions").get(url);
  78477. getRequest.onsuccess = function (event) {
  78478. version = (event.target).result;
  78479. };
  78480. getRequest.onerror = function (event) {
  78481. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  78482. callback(-1);
  78483. };
  78484. }
  78485. catch (ex) {
  78486. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  78487. callback(-1);
  78488. }
  78489. }
  78490. else {
  78491. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78492. callback(-1);
  78493. }
  78494. };
  78495. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  78496. var _this = this;
  78497. if (this.isSupported && !this.hasReachedQuota && this.db) {
  78498. try {
  78499. // Open a transaction to the database
  78500. var transaction = this.db.transaction(["versions"], "readwrite");
  78501. // the transaction could abort because of a QuotaExceededError error
  78502. transaction.onabort = function (event) {
  78503. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78504. var error = event.srcElement['error'];
  78505. if (error && error.name === "QuotaExceededError") {
  78506. _this.hasReachedQuota = true;
  78507. }
  78508. }
  78509. catch (ex) { }
  78510. callback(-1);
  78511. };
  78512. transaction.oncomplete = function (event) {
  78513. callback(_this.manifestVersionFound);
  78514. };
  78515. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  78516. // Put the scene into the database
  78517. var addRequest = transaction.objectStore("versions").put(newVersion);
  78518. addRequest.onsuccess = function (event) {
  78519. };
  78520. addRequest.onerror = function (event) {
  78521. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  78522. };
  78523. }
  78524. catch (ex) {
  78525. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  78526. callback(-1);
  78527. }
  78528. }
  78529. else {
  78530. callback(-1);
  78531. }
  78532. };
  78533. /**
  78534. * Loads a file from database
  78535. * @param url defines the URL to load from
  78536. * @param sceneLoaded defines a callback to call on success
  78537. * @param progressCallBack defines a callback to call when progress changed
  78538. * @param errorCallback defines a callback to call on error
  78539. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  78540. */
  78541. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  78542. var _this = this;
  78543. var completeUrl = Database._ReturnFullUrlLocation(url);
  78544. var saveAndLoadFile = function () {
  78545. // the scene is not yet in the DB, let's try to save it
  78546. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78547. };
  78548. this._checkVersionFromDB(completeUrl, function (version) {
  78549. if (version !== -1) {
  78550. if (!_this.mustUpdateRessources) {
  78551. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  78552. }
  78553. else {
  78554. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78555. }
  78556. }
  78557. else {
  78558. if (errorCallback) {
  78559. errorCallback();
  78560. }
  78561. }
  78562. });
  78563. };
  78564. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  78565. if (this.isSupported && this.db) {
  78566. var targetStore;
  78567. if (url.indexOf(".babylon") !== -1) {
  78568. targetStore = "scenes";
  78569. }
  78570. else {
  78571. targetStore = "textures";
  78572. }
  78573. var file;
  78574. var transaction = this.db.transaction([targetStore]);
  78575. transaction.oncomplete = function (event) {
  78576. if (file) {
  78577. callback(file.data);
  78578. }
  78579. // file was not found in DB
  78580. else {
  78581. notInDBCallback();
  78582. }
  78583. };
  78584. transaction.onabort = function (event) {
  78585. notInDBCallback();
  78586. };
  78587. var getRequest = transaction.objectStore(targetStore).get(url);
  78588. getRequest.onsuccess = function (event) {
  78589. file = (event.target).result;
  78590. };
  78591. getRequest.onerror = function (event) {
  78592. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  78593. notInDBCallback();
  78594. };
  78595. }
  78596. else {
  78597. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78598. callback();
  78599. }
  78600. };
  78601. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  78602. var _this = this;
  78603. if (this.isSupported) {
  78604. var targetStore;
  78605. if (url.indexOf(".babylon") !== -1) {
  78606. targetStore = "scenes";
  78607. }
  78608. else {
  78609. targetStore = "textures";
  78610. }
  78611. // Create XHR
  78612. var xhr = new XMLHttpRequest();
  78613. var fileData;
  78614. xhr.open("GET", url + "?" + Date.now(), true);
  78615. if (useArrayBuffer) {
  78616. xhr.responseType = "arraybuffer";
  78617. }
  78618. if (progressCallback) {
  78619. xhr.onprogress = progressCallback;
  78620. }
  78621. xhr.addEventListener("load", function () {
  78622. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  78623. // Blob as response (XHR2)
  78624. //fileData = xhr.responseText;
  78625. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  78626. if (!_this.hasReachedQuota && _this.db) {
  78627. // Open a transaction to the database
  78628. var transaction = _this.db.transaction([targetStore], "readwrite");
  78629. // the transaction could abort because of a QuotaExceededError error
  78630. transaction.onabort = function (event) {
  78631. try {
  78632. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78633. var error = event.srcElement['error'];
  78634. if (error && error.name === "QuotaExceededError") {
  78635. _this.hasReachedQuota = true;
  78636. }
  78637. }
  78638. catch (ex) { }
  78639. callback(fileData);
  78640. };
  78641. transaction.oncomplete = function (event) {
  78642. callback(fileData);
  78643. };
  78644. var newFile;
  78645. if (targetStore === "scenes") {
  78646. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  78647. }
  78648. else {
  78649. newFile = { textureUrl: url, data: fileData };
  78650. }
  78651. try {
  78652. // Put the scene into the database
  78653. var addRequest = transaction.objectStore(targetStore).put(newFile);
  78654. addRequest.onsuccess = function (event) {
  78655. };
  78656. addRequest.onerror = function (event) {
  78657. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  78658. };
  78659. }
  78660. catch (ex) {
  78661. callback(fileData);
  78662. }
  78663. }
  78664. else {
  78665. callback(fileData);
  78666. }
  78667. }
  78668. else {
  78669. if (xhr.status >= 400 && errorCallback) {
  78670. errorCallback(xhr);
  78671. }
  78672. else {
  78673. callback();
  78674. }
  78675. }
  78676. }, false);
  78677. xhr.addEventListener("error", function (event) {
  78678. BABYLON.Tools.Error("error on XHR request.");
  78679. callback();
  78680. }, false);
  78681. xhr.send();
  78682. }
  78683. else {
  78684. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78685. callback();
  78686. }
  78687. };
  78688. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  78689. Database.IsUASupportingBlobStorage = true;
  78690. /** Gets a boolean indicating if Database storate is enabled */
  78691. Database.IDBStorageEnabled = true;
  78692. Database._ParseURL = function (url) {
  78693. var a = document.createElement('a');
  78694. a.href = url;
  78695. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  78696. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  78697. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  78698. return absLocation;
  78699. };
  78700. Database._ReturnFullUrlLocation = function (url) {
  78701. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  78702. return (Database._ParseURL(window.location.href) + url);
  78703. }
  78704. else {
  78705. return url;
  78706. }
  78707. };
  78708. return Database;
  78709. }());
  78710. BABYLON.Database = Database;
  78711. })(BABYLON || (BABYLON = {}));
  78712. //# sourceMappingURL=babylon.database.js.map
  78713. var BABYLON;
  78714. (function (BABYLON) {
  78715. /**
  78716. * This represents all the required information to add a fresnel effect on a material:
  78717. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  78718. */
  78719. var FresnelParameters = /** @class */ (function () {
  78720. function FresnelParameters() {
  78721. this._isEnabled = true;
  78722. /**
  78723. * Define the color used on edges (grazing angle)
  78724. */
  78725. this.leftColor = BABYLON.Color3.White();
  78726. /**
  78727. * Define the color used on center
  78728. */
  78729. this.rightColor = BABYLON.Color3.Black();
  78730. /**
  78731. * Define bias applied to computed fresnel term
  78732. */
  78733. this.bias = 0;
  78734. /**
  78735. * Defined the power exponent applied to fresnel term
  78736. */
  78737. this.power = 1;
  78738. }
  78739. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  78740. /**
  78741. * Define if the fresnel effect is enable or not.
  78742. */
  78743. get: function () {
  78744. return this._isEnabled;
  78745. },
  78746. set: function (value) {
  78747. if (this._isEnabled === value) {
  78748. return;
  78749. }
  78750. this._isEnabled = value;
  78751. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  78752. },
  78753. enumerable: true,
  78754. configurable: true
  78755. });
  78756. /**
  78757. * Clones the current fresnel and its valuues
  78758. * @returns a clone fresnel configuration
  78759. */
  78760. FresnelParameters.prototype.clone = function () {
  78761. var newFresnelParameters = new FresnelParameters();
  78762. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  78763. return newFresnelParameters;
  78764. };
  78765. /**
  78766. * Serializes the current fresnel parameters to a JSON representation.
  78767. * @return the JSON serialization
  78768. */
  78769. FresnelParameters.prototype.serialize = function () {
  78770. var serializationObject = {};
  78771. serializationObject.isEnabled = this.isEnabled;
  78772. serializationObject.leftColor = this.leftColor.asArray();
  78773. serializationObject.rightColor = this.rightColor.asArray();
  78774. serializationObject.bias = this.bias;
  78775. serializationObject.power = this.power;
  78776. return serializationObject;
  78777. };
  78778. /**
  78779. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  78780. * @param parsedFresnelParameters Define the JSON representation
  78781. * @returns the parsed parameters
  78782. */
  78783. FresnelParameters.Parse = function (parsedFresnelParameters) {
  78784. var fresnelParameters = new FresnelParameters();
  78785. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  78786. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  78787. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  78788. fresnelParameters.bias = parsedFresnelParameters.bias;
  78789. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  78790. return fresnelParameters;
  78791. };
  78792. return FresnelParameters;
  78793. }());
  78794. BABYLON.FresnelParameters = FresnelParameters;
  78795. })(BABYLON || (BABYLON = {}));
  78796. //# sourceMappingURL=babylon.fresnelParameters.js.map
  78797. var BABYLON;
  78798. (function (BABYLON) {
  78799. /**
  78800. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78801. * separate meshes. This can be use to improve performances.
  78802. * @see http://doc.babylonjs.com/how_to/multi_materials
  78803. */
  78804. var MultiMaterial = /** @class */ (function (_super) {
  78805. __extends(MultiMaterial, _super);
  78806. /**
  78807. * Instantiates a new Multi Material
  78808. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78809. * separate meshes. This can be use to improve performances.
  78810. * @see http://doc.babylonjs.com/how_to/multi_materials
  78811. * @param name Define the name in the scene
  78812. * @param scene Define the scene the material belongs to
  78813. */
  78814. function MultiMaterial(name, scene) {
  78815. var _this = _super.call(this, name, scene, true) || this;
  78816. scene.multiMaterials.push(_this);
  78817. _this.subMaterials = new Array();
  78818. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  78819. return _this;
  78820. }
  78821. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  78822. /**
  78823. * Gets or Sets the list of Materials used within the multi material.
  78824. * They need to be ordered according to the submeshes order in the associated mesh
  78825. */
  78826. get: function () {
  78827. return this._subMaterials;
  78828. },
  78829. set: function (value) {
  78830. this._subMaterials = value;
  78831. this._hookArray(value);
  78832. },
  78833. enumerable: true,
  78834. configurable: true
  78835. });
  78836. MultiMaterial.prototype._hookArray = function (array) {
  78837. var _this = this;
  78838. var oldPush = array.push;
  78839. array.push = function () {
  78840. var items = [];
  78841. for (var _i = 0; _i < arguments.length; _i++) {
  78842. items[_i] = arguments[_i];
  78843. }
  78844. var result = oldPush.apply(array, items);
  78845. _this._markAllSubMeshesAsTexturesDirty();
  78846. return result;
  78847. };
  78848. var oldSplice = array.splice;
  78849. array.splice = function (index, deleteCount) {
  78850. var deleted = oldSplice.apply(array, [index, deleteCount]);
  78851. _this._markAllSubMeshesAsTexturesDirty();
  78852. return deleted;
  78853. };
  78854. };
  78855. /**
  78856. * Get one of the submaterial by its index in the submaterials array
  78857. * @param index The index to look the sub material at
  78858. * @returns The Material if the index has been defined
  78859. */
  78860. MultiMaterial.prototype.getSubMaterial = function (index) {
  78861. if (index < 0 || index >= this.subMaterials.length) {
  78862. return this.getScene().defaultMaterial;
  78863. }
  78864. return this.subMaterials[index];
  78865. };
  78866. /**
  78867. * Get the list of active textures for the whole sub materials list.
  78868. * @returns All the textures that will be used during the rendering
  78869. */
  78870. MultiMaterial.prototype.getActiveTextures = function () {
  78871. var _a;
  78872. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  78873. if (subMaterial) {
  78874. return subMaterial.getActiveTextures();
  78875. }
  78876. else {
  78877. return [];
  78878. }
  78879. }));
  78880. };
  78881. /**
  78882. * Gets the current class name of the material e.g. "MultiMaterial"
  78883. * Mainly use in serialization.
  78884. * @returns the class name
  78885. */
  78886. MultiMaterial.prototype.getClassName = function () {
  78887. return "MultiMaterial";
  78888. };
  78889. /**
  78890. * Checks if the material is ready to render the requested sub mesh
  78891. * @param mesh Define the mesh the submesh belongs to
  78892. * @param subMesh Define the sub mesh to look readyness for
  78893. * @param useInstances Define whether or not the material is used with instances
  78894. * @returns true if ready, otherwise false
  78895. */
  78896. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78897. for (var index = 0; index < this.subMaterials.length; index++) {
  78898. var subMaterial = this.subMaterials[index];
  78899. if (subMaterial) {
  78900. if (subMaterial.storeEffectOnSubMeshes) {
  78901. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  78902. return false;
  78903. }
  78904. continue;
  78905. }
  78906. if (!subMaterial.isReady(mesh)) {
  78907. return false;
  78908. }
  78909. }
  78910. }
  78911. return true;
  78912. };
  78913. /**
  78914. * Clones the current material and its related sub materials
  78915. * @param name Define the name of the newly cloned material
  78916. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  78917. * @returns the cloned material
  78918. */
  78919. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  78920. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  78921. for (var index = 0; index < this.subMaterials.length; index++) {
  78922. var subMaterial = null;
  78923. var current = this.subMaterials[index];
  78924. if (cloneChildren && current) {
  78925. subMaterial = current.clone(name + "-" + current.name);
  78926. }
  78927. else {
  78928. subMaterial = this.subMaterials[index];
  78929. }
  78930. newMultiMaterial.subMaterials.push(subMaterial);
  78931. }
  78932. return newMultiMaterial;
  78933. };
  78934. /**
  78935. * Serializes the materials into a JSON representation.
  78936. * @returns the JSON representation
  78937. */
  78938. MultiMaterial.prototype.serialize = function () {
  78939. var serializationObject = {};
  78940. serializationObject.name = this.name;
  78941. serializationObject.id = this.id;
  78942. if (BABYLON.Tags) {
  78943. serializationObject.tags = BABYLON.Tags.GetTags(this);
  78944. }
  78945. serializationObject.materials = [];
  78946. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  78947. var subMat = this.subMaterials[matIndex];
  78948. if (subMat) {
  78949. serializationObject.materials.push(subMat.id);
  78950. }
  78951. else {
  78952. serializationObject.materials.push(null);
  78953. }
  78954. }
  78955. return serializationObject;
  78956. };
  78957. /**
  78958. * Dispose the material and release its associated resources
  78959. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  78960. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  78961. */
  78962. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78963. var scene = this.getScene();
  78964. if (!scene) {
  78965. return;
  78966. }
  78967. var index = scene.multiMaterials.indexOf(this);
  78968. if (index >= 0) {
  78969. scene.multiMaterials.splice(index, 1);
  78970. }
  78971. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  78972. };
  78973. return MultiMaterial;
  78974. }(BABYLON.Material));
  78975. BABYLON.MultiMaterial = MultiMaterial;
  78976. })(BABYLON || (BABYLON = {}));
  78977. //# sourceMappingURL=babylon.multiMaterial.js.map
  78978. var BABYLON;
  78979. (function (BABYLON) {
  78980. /**
  78981. * Manage the touch inputs to control the movement of a free camera.
  78982. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78983. */
  78984. var FreeCameraTouchInput = /** @class */ (function () {
  78985. function FreeCameraTouchInput() {
  78986. /**
  78987. * Defines the touch sensibility for rotation.
  78988. * The higher the faster.
  78989. */
  78990. this.touchAngularSensibility = 200000.0;
  78991. /**
  78992. * Defines the touch sensibility for move.
  78993. * The higher the faster.
  78994. */
  78995. this.touchMoveSensibility = 250.0;
  78996. this._offsetX = null;
  78997. this._offsetY = null;
  78998. this._pointerPressed = new Array();
  78999. }
  79000. /**
  79001. * Attach the input controls to a specific dom element to get the input from.
  79002. * @param element Defines the element the controls should be listened from
  79003. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79004. */
  79005. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  79006. var _this = this;
  79007. var previousPosition = null;
  79008. if (this._pointerInput === undefined) {
  79009. this._onLostFocus = function (evt) {
  79010. _this._offsetX = null;
  79011. _this._offsetY = null;
  79012. };
  79013. this._pointerInput = function (p, s) {
  79014. var evt = p.event;
  79015. if (evt.pointerType === "mouse") {
  79016. return;
  79017. }
  79018. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79019. if (!noPreventDefault) {
  79020. evt.preventDefault();
  79021. }
  79022. _this._pointerPressed.push(evt.pointerId);
  79023. if (_this._pointerPressed.length !== 1) {
  79024. return;
  79025. }
  79026. previousPosition = {
  79027. x: evt.clientX,
  79028. y: evt.clientY
  79029. };
  79030. }
  79031. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  79032. if (!noPreventDefault) {
  79033. evt.preventDefault();
  79034. }
  79035. var index = _this._pointerPressed.indexOf(evt.pointerId);
  79036. if (index === -1) {
  79037. return;
  79038. }
  79039. _this._pointerPressed.splice(index, 1);
  79040. if (index != 0) {
  79041. return;
  79042. }
  79043. previousPosition = null;
  79044. _this._offsetX = null;
  79045. _this._offsetY = null;
  79046. }
  79047. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  79048. if (!noPreventDefault) {
  79049. evt.preventDefault();
  79050. }
  79051. if (!previousPosition) {
  79052. return;
  79053. }
  79054. var index = _this._pointerPressed.indexOf(evt.pointerId);
  79055. if (index != 0) {
  79056. return;
  79057. }
  79058. _this._offsetX = evt.clientX - previousPosition.x;
  79059. _this._offsetY = -(evt.clientY - previousPosition.y);
  79060. }
  79061. };
  79062. }
  79063. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  79064. if (this._onLostFocus) {
  79065. element.addEventListener("blur", this._onLostFocus);
  79066. }
  79067. };
  79068. /**
  79069. * Detach the current controls from the specified dom element.
  79070. * @param element Defines the element to stop listening the inputs from
  79071. */
  79072. FreeCameraTouchInput.prototype.detachControl = function (element) {
  79073. if (this._pointerInput && element) {
  79074. if (this._observer) {
  79075. this.camera.getScene().onPointerObservable.remove(this._observer);
  79076. this._observer = null;
  79077. }
  79078. if (this._onLostFocus) {
  79079. element.removeEventListener("blur", this._onLostFocus);
  79080. this._onLostFocus = null;
  79081. }
  79082. this._pointerPressed = [];
  79083. this._offsetX = null;
  79084. this._offsetY = null;
  79085. }
  79086. };
  79087. /**
  79088. * Update the current camera state depending on the inputs that have been used this frame.
  79089. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79090. */
  79091. FreeCameraTouchInput.prototype.checkInputs = function () {
  79092. if (this._offsetX && this._offsetY) {
  79093. var camera = this.camera;
  79094. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  79095. if (this._pointerPressed.length > 1) {
  79096. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  79097. }
  79098. else {
  79099. var speed = camera._computeLocalCameraSpeed();
  79100. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  79101. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  79102. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  79103. }
  79104. }
  79105. };
  79106. /**
  79107. * Gets the class name of the current intput.
  79108. * @returns the class name
  79109. */
  79110. FreeCameraTouchInput.prototype.getClassName = function () {
  79111. return "FreeCameraTouchInput";
  79112. };
  79113. /**
  79114. * Get the friendly name associated with the input class.
  79115. * @returns the input friendly name
  79116. */
  79117. FreeCameraTouchInput.prototype.getSimpleName = function () {
  79118. return "touch";
  79119. };
  79120. __decorate([
  79121. BABYLON.serialize()
  79122. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  79123. __decorate([
  79124. BABYLON.serialize()
  79125. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  79126. return FreeCameraTouchInput;
  79127. }());
  79128. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  79129. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  79130. })(BABYLON || (BABYLON = {}));
  79131. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  79132. var BABYLON;
  79133. (function (BABYLON) {
  79134. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  79135. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  79136. });
  79137. /**
  79138. * This represents a FPS type of camera controlled by touch.
  79139. * This is like a universal camera minus the Gamepad controls.
  79140. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79141. */
  79142. var TouchCamera = /** @class */ (function (_super) {
  79143. __extends(TouchCamera, _super);
  79144. /**
  79145. * Instantiates a new touch camera.
  79146. * This represents a FPS type of camera controlled by touch.
  79147. * This is like a universal camera minus the Gamepad controls.
  79148. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79149. * @param name Define the name of the camera in the scene
  79150. * @param position Define the start position of the camera in the scene
  79151. * @param scene Define the scene the camera belongs to
  79152. */
  79153. function TouchCamera(name, position, scene) {
  79154. var _this = _super.call(this, name, position, scene) || this;
  79155. _this.inputs.addTouch();
  79156. _this._setupInputs();
  79157. return _this;
  79158. }
  79159. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  79160. /**
  79161. * Defines the touch sensibility for rotation.
  79162. * The higher the faster.
  79163. */
  79164. get: function () {
  79165. var touch = this.inputs.attached["touch"];
  79166. if (touch) {
  79167. return touch.touchAngularSensibility;
  79168. }
  79169. return 0;
  79170. },
  79171. set: function (value) {
  79172. var touch = this.inputs.attached["touch"];
  79173. if (touch) {
  79174. touch.touchAngularSensibility = value;
  79175. }
  79176. },
  79177. enumerable: true,
  79178. configurable: true
  79179. });
  79180. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  79181. /**
  79182. * Defines the touch sensibility for move.
  79183. * The higher the faster.
  79184. */
  79185. get: function () {
  79186. var touch = this.inputs.attached["touch"];
  79187. if (touch) {
  79188. return touch.touchMoveSensibility;
  79189. }
  79190. return 0;
  79191. },
  79192. set: function (value) {
  79193. var touch = this.inputs.attached["touch"];
  79194. if (touch) {
  79195. touch.touchMoveSensibility = value;
  79196. }
  79197. },
  79198. enumerable: true,
  79199. configurable: true
  79200. });
  79201. /**
  79202. * Gets the current object class name.
  79203. * @return the class name
  79204. */
  79205. TouchCamera.prototype.getClassName = function () {
  79206. return "TouchCamera";
  79207. };
  79208. /** @hidden */
  79209. TouchCamera.prototype._setupInputs = function () {
  79210. var mouse = this.inputs.attached["mouse"];
  79211. if (mouse) {
  79212. mouse.touchEnabled = false;
  79213. }
  79214. };
  79215. return TouchCamera;
  79216. }(BABYLON.FreeCamera));
  79217. BABYLON.TouchCamera = TouchCamera;
  79218. })(BABYLON || (BABYLON = {}));
  79219. //# sourceMappingURL=babylon.touchCamera.js.map
  79220. var BABYLON;
  79221. (function (BABYLON) {
  79222. /**
  79223. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79224. * This is the base class of any Procedural texture and contains most of the shareable code.
  79225. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  79226. */
  79227. var ProceduralTexture = /** @class */ (function (_super) {
  79228. __extends(ProceduralTexture, _super);
  79229. /**
  79230. * Instantiates a new procedural texture.
  79231. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79232. * This is the base class of any Procedural texture and contains most of the shareable code.
  79233. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  79234. * @param name Define the name of the texture
  79235. * @param size Define the size of the texture to create
  79236. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  79237. * @param scene Define the scene the texture belongs to
  79238. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79239. * @param generateMipMaps Define if the texture should creates mip maps or not
  79240. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  79241. */
  79242. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  79243. if (fallbackTexture === void 0) { fallbackTexture = null; }
  79244. if (generateMipMaps === void 0) { generateMipMaps = true; }
  79245. if (isCube === void 0) { isCube = false; }
  79246. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  79247. _this.isCube = isCube;
  79248. /**
  79249. * Define if the texture is enabled or not (disabled texture will not render)
  79250. */
  79251. _this.isEnabled = true;
  79252. /**
  79253. * Event raised when the texture is generated
  79254. */
  79255. _this.onGeneratedObservable = new BABYLON.Observable();
  79256. /** @hidden */
  79257. _this._textures = {};
  79258. _this._currentRefreshId = -1;
  79259. _this._refreshRate = 1;
  79260. _this._vertexBuffers = {};
  79261. _this._uniforms = new Array();
  79262. _this._samplers = new Array();
  79263. _this._floats = {};
  79264. _this._ints = {};
  79265. _this._floatsArrays = {};
  79266. _this._colors3 = {};
  79267. _this._colors4 = {};
  79268. _this._vectors2 = {};
  79269. _this._vectors3 = {};
  79270. _this._matrices = {};
  79271. _this._fallbackTextureUsed = false;
  79272. _this._cachedDefines = "";
  79273. _this._contentUpdateId = -1;
  79274. scene = _this.getScene();
  79275. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  79276. if (!component) {
  79277. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  79278. scene._addComponent(component);
  79279. }
  79280. scene.proceduralTextures.push(_this);
  79281. _this._engine = scene.getEngine();
  79282. _this.name = name;
  79283. _this.isRenderTarget = true;
  79284. _this._size = size;
  79285. _this._generateMipMaps = generateMipMaps;
  79286. _this.setFragment(fragment);
  79287. _this._fallbackTexture = fallbackTexture;
  79288. if (isCube) {
  79289. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  79290. _this.setFloat("face", 0);
  79291. }
  79292. else {
  79293. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  79294. }
  79295. // VBO
  79296. var vertices = [];
  79297. vertices.push(1, 1);
  79298. vertices.push(-1, 1);
  79299. vertices.push(-1, -1);
  79300. vertices.push(1, -1);
  79301. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79302. _this._createIndexBuffer();
  79303. return _this;
  79304. }
  79305. /**
  79306. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  79307. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  79308. */
  79309. ProceduralTexture.prototype.getContent = function () {
  79310. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  79311. return this._contentData;
  79312. }
  79313. this._contentData = this.readPixels(0, 0, this._contentData);
  79314. this._contentUpdateId = this._currentRefreshId;
  79315. return this._contentData;
  79316. };
  79317. ProceduralTexture.prototype._createIndexBuffer = function () {
  79318. var engine = this._engine;
  79319. // Indices
  79320. var indices = [];
  79321. indices.push(0);
  79322. indices.push(1);
  79323. indices.push(2);
  79324. indices.push(0);
  79325. indices.push(2);
  79326. indices.push(3);
  79327. this._indexBuffer = engine.createIndexBuffer(indices);
  79328. };
  79329. /** @hidden */
  79330. ProceduralTexture.prototype._rebuild = function () {
  79331. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79332. if (vb) {
  79333. vb._rebuild();
  79334. }
  79335. this._createIndexBuffer();
  79336. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  79337. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  79338. }
  79339. };
  79340. /**
  79341. * Resets the texture in order to recreate its associated resources.
  79342. * This can be called in case of context loss
  79343. */
  79344. ProceduralTexture.prototype.reset = function () {
  79345. if (this._effect === undefined) {
  79346. return;
  79347. }
  79348. var engine = this._engine;
  79349. engine._releaseEffect(this._effect);
  79350. };
  79351. ProceduralTexture.prototype._getDefines = function () {
  79352. return "";
  79353. };
  79354. /**
  79355. * Is the texture ready to be used ? (rendered at least once)
  79356. * @returns true if ready, otherwise, false.
  79357. */
  79358. ProceduralTexture.prototype.isReady = function () {
  79359. var _this = this;
  79360. var engine = this._engine;
  79361. var shaders;
  79362. if (!this._fragment) {
  79363. return false;
  79364. }
  79365. if (this._fallbackTextureUsed) {
  79366. return true;
  79367. }
  79368. var defines = this._getDefines();
  79369. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  79370. return true;
  79371. }
  79372. if (this._fragment.fragmentElement !== undefined) {
  79373. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  79374. }
  79375. else {
  79376. shaders = { vertex: "procedural", fragment: this._fragment };
  79377. }
  79378. this._cachedDefines = defines;
  79379. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  79380. _this.releaseInternalTexture();
  79381. if (_this._fallbackTexture) {
  79382. _this._texture = _this._fallbackTexture._texture;
  79383. if (_this._texture) {
  79384. _this._texture.incrementReferences();
  79385. }
  79386. }
  79387. _this._fallbackTextureUsed = true;
  79388. });
  79389. return this._effect.isReady();
  79390. };
  79391. /**
  79392. * Resets the refresh counter of the texture and start bak from scratch.
  79393. * Could be usefull to regenerate the texture if it is setup to render only once.
  79394. */
  79395. ProceduralTexture.prototype.resetRefreshCounter = function () {
  79396. this._currentRefreshId = -1;
  79397. };
  79398. /**
  79399. * Set the fragment shader to use in order to render the texture.
  79400. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  79401. */
  79402. ProceduralTexture.prototype.setFragment = function (fragment) {
  79403. this._fragment = fragment;
  79404. };
  79405. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  79406. /**
  79407. * Define the refresh rate of the texture or the rendering frequency.
  79408. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  79409. */
  79410. get: function () {
  79411. return this._refreshRate;
  79412. },
  79413. set: function (value) {
  79414. this._refreshRate = value;
  79415. this.resetRefreshCounter();
  79416. },
  79417. enumerable: true,
  79418. configurable: true
  79419. });
  79420. /** @hidden */
  79421. ProceduralTexture.prototype._shouldRender = function () {
  79422. if (!this.isEnabled || !this.isReady() || !this._texture) {
  79423. if (this._texture) {
  79424. this._texture.isReady = false;
  79425. }
  79426. return false;
  79427. }
  79428. if (this._fallbackTextureUsed) {
  79429. return false;
  79430. }
  79431. if (this._currentRefreshId === -1) { // At least render once
  79432. this._currentRefreshId = 1;
  79433. return true;
  79434. }
  79435. if (this.refreshRate === this._currentRefreshId) {
  79436. this._currentRefreshId = 1;
  79437. return true;
  79438. }
  79439. this._currentRefreshId++;
  79440. return false;
  79441. };
  79442. /**
  79443. * Get the size the texture is rendering at.
  79444. * @returns the size (texture is always squared)
  79445. */
  79446. ProceduralTexture.prototype.getRenderSize = function () {
  79447. return this._size;
  79448. };
  79449. /**
  79450. * Resize the texture to new value.
  79451. * @param size Define the new size the texture should have
  79452. * @param generateMipMaps Define whether the new texture should create mip maps
  79453. */
  79454. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  79455. if (this._fallbackTextureUsed) {
  79456. return;
  79457. }
  79458. this.releaseInternalTexture();
  79459. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  79460. // Update properties
  79461. this._size = size;
  79462. this._generateMipMaps = generateMipMaps;
  79463. };
  79464. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  79465. if (this._uniforms.indexOf(uniformName) === -1) {
  79466. this._uniforms.push(uniformName);
  79467. }
  79468. };
  79469. /**
  79470. * Set a texture in the shader program used to render.
  79471. * @param name Define the name of the uniform samplers as defined in the shader
  79472. * @param texture Define the texture to bind to this sampler
  79473. * @return the texture itself allowing "fluent" like uniform updates
  79474. */
  79475. ProceduralTexture.prototype.setTexture = function (name, texture) {
  79476. if (this._samplers.indexOf(name) === -1) {
  79477. this._samplers.push(name);
  79478. }
  79479. this._textures[name] = texture;
  79480. return this;
  79481. };
  79482. /**
  79483. * Set a float in the shader.
  79484. * @param name Define the name of the uniform as defined in the shader
  79485. * @param value Define the value to give to the uniform
  79486. * @return the texture itself allowing "fluent" like uniform updates
  79487. */
  79488. ProceduralTexture.prototype.setFloat = function (name, value) {
  79489. this._checkUniform(name);
  79490. this._floats[name] = value;
  79491. return this;
  79492. };
  79493. /**
  79494. * Set a int in the shader.
  79495. * @param name Define the name of the uniform as defined in the shader
  79496. * @param value Define the value to give to the uniform
  79497. * @return the texture itself allowing "fluent" like uniform updates
  79498. */
  79499. ProceduralTexture.prototype.setInt = function (name, value) {
  79500. this._checkUniform(name);
  79501. this._ints[name] = value;
  79502. return this;
  79503. };
  79504. /**
  79505. * Set an array of floats in the shader.
  79506. * @param name Define the name of the uniform as defined in the shader
  79507. * @param value Define the value to give to the uniform
  79508. * @return the texture itself allowing "fluent" like uniform updates
  79509. */
  79510. ProceduralTexture.prototype.setFloats = function (name, value) {
  79511. this._checkUniform(name);
  79512. this._floatsArrays[name] = value;
  79513. return this;
  79514. };
  79515. /**
  79516. * Set a vec3 in the shader from a Color3.
  79517. * @param name Define the name of the uniform as defined in the shader
  79518. * @param value Define the value to give to the uniform
  79519. * @return the texture itself allowing "fluent" like uniform updates
  79520. */
  79521. ProceduralTexture.prototype.setColor3 = function (name, value) {
  79522. this._checkUniform(name);
  79523. this._colors3[name] = value;
  79524. return this;
  79525. };
  79526. /**
  79527. * Set a vec4 in the shader from a Color4.
  79528. * @param name Define the name of the uniform as defined in the shader
  79529. * @param value Define the value to give to the uniform
  79530. * @return the texture itself allowing "fluent" like uniform updates
  79531. */
  79532. ProceduralTexture.prototype.setColor4 = function (name, value) {
  79533. this._checkUniform(name);
  79534. this._colors4[name] = value;
  79535. return this;
  79536. };
  79537. /**
  79538. * Set a vec2 in the shader from a Vector2.
  79539. * @param name Define the name of the uniform as defined in the shader
  79540. * @param value Define the value to give to the uniform
  79541. * @return the texture itself allowing "fluent" like uniform updates
  79542. */
  79543. ProceduralTexture.prototype.setVector2 = function (name, value) {
  79544. this._checkUniform(name);
  79545. this._vectors2[name] = value;
  79546. return this;
  79547. };
  79548. /**
  79549. * Set a vec3 in the shader from a Vector3.
  79550. * @param name Define the name of the uniform as defined in the shader
  79551. * @param value Define the value to give to the uniform
  79552. * @return the texture itself allowing "fluent" like uniform updates
  79553. */
  79554. ProceduralTexture.prototype.setVector3 = function (name, value) {
  79555. this._checkUniform(name);
  79556. this._vectors3[name] = value;
  79557. return this;
  79558. };
  79559. /**
  79560. * Set a mat4 in the shader from a MAtrix.
  79561. * @param name Define the name of the uniform as defined in the shader
  79562. * @param value Define the value to give to the uniform
  79563. * @return the texture itself allowing "fluent" like uniform updates
  79564. */
  79565. ProceduralTexture.prototype.setMatrix = function (name, value) {
  79566. this._checkUniform(name);
  79567. this._matrices[name] = value;
  79568. return this;
  79569. };
  79570. /**
  79571. * Render the texture to its associated render target.
  79572. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79573. */
  79574. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79575. var scene = this.getScene();
  79576. if (!scene) {
  79577. return;
  79578. }
  79579. var engine = this._engine;
  79580. // Render
  79581. engine.enableEffect(this._effect);
  79582. engine.setState(false);
  79583. // Texture
  79584. for (var name in this._textures) {
  79585. this._effect.setTexture(name, this._textures[name]);
  79586. }
  79587. // Float
  79588. for (name in this._ints) {
  79589. this._effect.setInt(name, this._ints[name]);
  79590. }
  79591. // Float
  79592. for (name in this._floats) {
  79593. this._effect.setFloat(name, this._floats[name]);
  79594. }
  79595. // Floats
  79596. for (name in this._floatsArrays) {
  79597. this._effect.setArray(name, this._floatsArrays[name]);
  79598. }
  79599. // Color3
  79600. for (name in this._colors3) {
  79601. this._effect.setColor3(name, this._colors3[name]);
  79602. }
  79603. // Color4
  79604. for (name in this._colors4) {
  79605. var color = this._colors4[name];
  79606. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  79607. }
  79608. // Vector2
  79609. for (name in this._vectors2) {
  79610. this._effect.setVector2(name, this._vectors2[name]);
  79611. }
  79612. // Vector3
  79613. for (name in this._vectors3) {
  79614. this._effect.setVector3(name, this._vectors3[name]);
  79615. }
  79616. // Matrix
  79617. for (name in this._matrices) {
  79618. this._effect.setMatrix(name, this._matrices[name]);
  79619. }
  79620. if (!this._texture) {
  79621. return;
  79622. }
  79623. if (this.isCube) {
  79624. for (var face = 0; face < 6; face++) {
  79625. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  79626. // VBOs
  79627. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79628. this._effect.setFloat("face", face);
  79629. // Clear
  79630. engine.clear(scene.clearColor, true, true, true);
  79631. // Draw order
  79632. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79633. // Mipmaps
  79634. if (face === 5) {
  79635. engine.generateMipMapsForCubemap(this._texture);
  79636. }
  79637. }
  79638. }
  79639. else {
  79640. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  79641. // VBOs
  79642. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79643. // Clear
  79644. engine.clear(scene.clearColor, true, true, true);
  79645. // Draw order
  79646. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79647. }
  79648. // Unbind
  79649. engine.unBindFramebuffer(this._texture, this.isCube);
  79650. if (this.onGenerated) {
  79651. this.onGenerated();
  79652. }
  79653. this.onGeneratedObservable.notifyObservers(this);
  79654. };
  79655. /**
  79656. * Clone the texture.
  79657. * @returns the cloned texture
  79658. */
  79659. ProceduralTexture.prototype.clone = function () {
  79660. var textureSize = this.getSize();
  79661. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  79662. // Base texture
  79663. newTexture.hasAlpha = this.hasAlpha;
  79664. newTexture.level = this.level;
  79665. // RenderTarget Texture
  79666. newTexture.coordinatesMode = this.coordinatesMode;
  79667. return newTexture;
  79668. };
  79669. /**
  79670. * Dispose the texture and release its asoociated resources.
  79671. */
  79672. ProceduralTexture.prototype.dispose = function () {
  79673. var scene = this.getScene();
  79674. if (!scene) {
  79675. return;
  79676. }
  79677. var index = scene.proceduralTextures.indexOf(this);
  79678. if (index >= 0) {
  79679. scene.proceduralTextures.splice(index, 1);
  79680. }
  79681. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79682. if (vertexBuffer) {
  79683. vertexBuffer.dispose();
  79684. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79685. }
  79686. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  79687. this._indexBuffer = null;
  79688. }
  79689. _super.prototype.dispose.call(this);
  79690. };
  79691. __decorate([
  79692. BABYLON.serialize()
  79693. ], ProceduralTexture.prototype, "isEnabled", void 0);
  79694. __decorate([
  79695. BABYLON.serialize()
  79696. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  79697. __decorate([
  79698. BABYLON.serialize()
  79699. ], ProceduralTexture.prototype, "_size", void 0);
  79700. __decorate([
  79701. BABYLON.serialize()
  79702. ], ProceduralTexture.prototype, "refreshRate", null);
  79703. return ProceduralTexture;
  79704. }(BABYLON.Texture));
  79705. BABYLON.ProceduralTexture = ProceduralTexture;
  79706. })(BABYLON || (BABYLON = {}));
  79707. //# sourceMappingURL=babylon.proceduralTexture.js.map
  79708. var BABYLON;
  79709. (function (BABYLON) {
  79710. /**
  79711. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  79712. * in a given scene.
  79713. */
  79714. var ProceduralTextureSceneComponent = /** @class */ (function () {
  79715. /**
  79716. * Creates a new instance of the component for the given scene
  79717. * @param scene Defines the scene to register the component in
  79718. */
  79719. function ProceduralTextureSceneComponent(scene) {
  79720. /**
  79721. * The component name helpfull to identify the component in the list of scene components.
  79722. */
  79723. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  79724. this.scene = scene;
  79725. this.scene.proceduralTextures = new Array();
  79726. scene.layers = new Array();
  79727. }
  79728. /**
  79729. * Registers the component in a given scene
  79730. */
  79731. ProceduralTextureSceneComponent.prototype.register = function () {
  79732. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  79733. };
  79734. /**
  79735. * Rebuilds the elements related to this component in case of
  79736. * context lost for instance.
  79737. */
  79738. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  79739. // Nothing to do here.
  79740. };
  79741. /**
  79742. * Disposes the component and the associated ressources.
  79743. */
  79744. ProceduralTextureSceneComponent.prototype.dispose = function () {
  79745. // Nothing to do here.
  79746. };
  79747. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  79748. if (this.scene.proceduralTexturesEnabled) {
  79749. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79750. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  79751. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  79752. if (proceduralTexture._shouldRender()) {
  79753. proceduralTexture.render();
  79754. }
  79755. }
  79756. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79757. }
  79758. };
  79759. return ProceduralTextureSceneComponent;
  79760. }());
  79761. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  79762. })(BABYLON || (BABYLON = {}));
  79763. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  79764. var BABYLON;
  79765. (function (BABYLON) {
  79766. /**
  79767. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79768. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79769. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79770. */
  79771. var CustomProceduralTexture = /** @class */ (function (_super) {
  79772. __extends(CustomProceduralTexture, _super);
  79773. /**
  79774. * Instantiates a new Custom Procedural Texture.
  79775. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  79776. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79777. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79778. * @param name Define the name of the texture
  79779. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  79780. * @param size Define the size of the texture to create
  79781. * @param scene Define the scene the texture belongs to
  79782. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79783. * @param generateMipMaps Define if the texture should creates mip maps or not
  79784. */
  79785. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  79786. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  79787. _this._animate = true;
  79788. _this._time = 0;
  79789. _this._texturePath = texturePath;
  79790. //Try to load json
  79791. _this._loadJson(texturePath);
  79792. _this.refreshRate = 1;
  79793. return _this;
  79794. }
  79795. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  79796. var _this = this;
  79797. var noConfigFile = function () {
  79798. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  79799. try {
  79800. _this.setFragment(_this._texturePath);
  79801. }
  79802. catch (ex) {
  79803. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  79804. }
  79805. };
  79806. var configFileUrl = jsonUrl + "/config.json";
  79807. var xhr = new XMLHttpRequest();
  79808. xhr.open("GET", configFileUrl, true);
  79809. xhr.addEventListener("load", function () {
  79810. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79811. try {
  79812. _this._config = JSON.parse(xhr.response);
  79813. _this.updateShaderUniforms();
  79814. _this.updateTextures();
  79815. _this.setFragment(_this._texturePath + "/custom");
  79816. _this._animate = _this._config.animate;
  79817. _this.refreshRate = _this._config.refreshrate;
  79818. }
  79819. catch (ex) {
  79820. noConfigFile();
  79821. }
  79822. }
  79823. else {
  79824. noConfigFile();
  79825. }
  79826. }, false);
  79827. xhr.addEventListener("error", function () {
  79828. noConfigFile();
  79829. }, false);
  79830. try {
  79831. xhr.send();
  79832. }
  79833. catch (ex) {
  79834. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  79835. }
  79836. };
  79837. /**
  79838. * Is the texture ready to be used ? (rendered at least once)
  79839. * @returns true if ready, otherwise, false.
  79840. */
  79841. CustomProceduralTexture.prototype.isReady = function () {
  79842. if (!_super.prototype.isReady.call(this)) {
  79843. return false;
  79844. }
  79845. for (var name in this._textures) {
  79846. var texture = this._textures[name];
  79847. if (!texture.isReady()) {
  79848. return false;
  79849. }
  79850. }
  79851. return true;
  79852. };
  79853. /**
  79854. * Render the texture to its associated render target.
  79855. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79856. */
  79857. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79858. var scene = this.getScene();
  79859. if (this._animate && scene) {
  79860. this._time += scene.getAnimationRatio() * 0.03;
  79861. this.updateShaderUniforms();
  79862. }
  79863. _super.prototype.render.call(this, useCameraPostProcess);
  79864. };
  79865. /**
  79866. * Update the list of dependant textures samplers in the shader.
  79867. */
  79868. CustomProceduralTexture.prototype.updateTextures = function () {
  79869. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  79870. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  79871. }
  79872. };
  79873. /**
  79874. * Update the uniform values of the procedural texture in the shader.
  79875. */
  79876. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  79877. if (this._config) {
  79878. for (var j = 0; j < this._config.uniforms.length; j++) {
  79879. var uniform = this._config.uniforms[j];
  79880. switch (uniform.type) {
  79881. case "float":
  79882. this.setFloat(uniform.name, uniform.value);
  79883. break;
  79884. case "color3":
  79885. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  79886. break;
  79887. case "color4":
  79888. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  79889. break;
  79890. case "vector2":
  79891. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  79892. break;
  79893. case "vector3":
  79894. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  79895. break;
  79896. }
  79897. }
  79898. }
  79899. this.setFloat("time", this._time);
  79900. };
  79901. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  79902. /**
  79903. * Define if the texture animates or not.
  79904. */
  79905. get: function () {
  79906. return this._animate;
  79907. },
  79908. set: function (value) {
  79909. this._animate = value;
  79910. },
  79911. enumerable: true,
  79912. configurable: true
  79913. });
  79914. return CustomProceduralTexture;
  79915. }(BABYLON.ProceduralTexture));
  79916. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  79917. })(BABYLON || (BABYLON = {}));
  79918. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  79919. var BABYLON;
  79920. (function (BABYLON) {
  79921. /**
  79922. * Manage the gamepad inputs to control a free camera.
  79923. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79924. */
  79925. var FreeCameraGamepadInput = /** @class */ (function () {
  79926. function FreeCameraGamepadInput() {
  79927. /**
  79928. * Defines the gamepad rotation sensiblity.
  79929. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79930. */
  79931. this.gamepadAngularSensibility = 200;
  79932. /**
  79933. * Defines the gamepad move sensiblity.
  79934. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79935. */
  79936. this.gamepadMoveSensibility = 40;
  79937. this._cameraTransform = BABYLON.Matrix.Identity();
  79938. this._deltaTransform = BABYLON.Vector3.Zero();
  79939. this._vector3 = BABYLON.Vector3.Zero();
  79940. this._vector2 = BABYLON.Vector2.Zero();
  79941. }
  79942. /**
  79943. * Attach the input controls to a specific dom element to get the input from.
  79944. * @param element Defines the element the controls should be listened from
  79945. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79946. */
  79947. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79948. var _this = this;
  79949. var manager = this.camera.getScene().gamepadManager;
  79950. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79951. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79952. // prioritize XBOX gamepads.
  79953. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79954. _this.gamepad = gamepad;
  79955. }
  79956. }
  79957. });
  79958. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79959. if (_this.gamepad === gamepad) {
  79960. _this.gamepad = null;
  79961. }
  79962. });
  79963. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79964. };
  79965. /**
  79966. * Detach the current controls from the specified dom element.
  79967. * @param element Defines the element to stop listening the inputs from
  79968. */
  79969. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  79970. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79971. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79972. this.gamepad = null;
  79973. };
  79974. /**
  79975. * Update the current camera state depending on the inputs that have been used this frame.
  79976. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79977. */
  79978. FreeCameraGamepadInput.prototype.checkInputs = function () {
  79979. if (this.gamepad && this.gamepad.leftStick) {
  79980. var camera = this.camera;
  79981. var LSValues = this.gamepad.leftStick;
  79982. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  79983. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79984. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  79985. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  79986. var RSValues = this.gamepad.rightStick;
  79987. if (RSValues) {
  79988. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  79989. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  79990. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  79991. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  79992. }
  79993. else {
  79994. RSValues = { x: 0, y: 0 };
  79995. }
  79996. if (!camera.rotationQuaternion) {
  79997. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  79998. }
  79999. else {
  80000. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  80001. }
  80002. var speed = camera._computeLocalCameraSpeed() * 50.0;
  80003. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  80004. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  80005. camera.cameraDirection.addInPlace(this._deltaTransform);
  80006. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  80007. camera.cameraRotation.addInPlace(this._vector2);
  80008. }
  80009. };
  80010. /**
  80011. * Gets the class name of the current intput.
  80012. * @returns the class name
  80013. */
  80014. FreeCameraGamepadInput.prototype.getClassName = function () {
  80015. return "FreeCameraGamepadInput";
  80016. };
  80017. /**
  80018. * Get the friendly name associated with the input class.
  80019. * @returns the input friendly name
  80020. */
  80021. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  80022. return "gamepad";
  80023. };
  80024. __decorate([
  80025. BABYLON.serialize()
  80026. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  80027. __decorate([
  80028. BABYLON.serialize()
  80029. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  80030. return FreeCameraGamepadInput;
  80031. }());
  80032. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  80033. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  80034. })(BABYLON || (BABYLON = {}));
  80035. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  80036. var BABYLON;
  80037. (function (BABYLON) {
  80038. /**
  80039. * Manage the gamepad inputs to control an arc rotate camera.
  80040. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80041. */
  80042. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  80043. function ArcRotateCameraGamepadInput() {
  80044. /**
  80045. * Defines the gamepad rotation sensiblity.
  80046. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  80047. */
  80048. this.gamepadRotationSensibility = 80;
  80049. /**
  80050. * Defines the gamepad move sensiblity.
  80051. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  80052. */
  80053. this.gamepadMoveSensibility = 40;
  80054. }
  80055. /**
  80056. * Attach the input controls to a specific dom element to get the input from.
  80057. * @param element Defines the element the controls should be listened from
  80058. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80059. */
  80060. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  80061. var _this = this;
  80062. var manager = this.camera.getScene().gamepadManager;
  80063. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  80064. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80065. // prioritize XBOX gamepads.
  80066. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  80067. _this.gamepad = gamepad;
  80068. }
  80069. }
  80070. });
  80071. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  80072. if (_this.gamepad === gamepad) {
  80073. _this.gamepad = null;
  80074. }
  80075. });
  80076. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  80077. };
  80078. /**
  80079. * Detach the current controls from the specified dom element.
  80080. * @param element Defines the element to stop listening the inputs from
  80081. */
  80082. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  80083. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80084. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80085. this.gamepad = null;
  80086. };
  80087. /**
  80088. * Update the current camera state depending on the inputs that have been used this frame.
  80089. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80090. */
  80091. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  80092. if (this.gamepad) {
  80093. var camera = this.camera;
  80094. var RSValues = this.gamepad.rightStick;
  80095. if (RSValues) {
  80096. if (RSValues.x != 0) {
  80097. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  80098. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  80099. camera.inertialAlphaOffset += normalizedRX;
  80100. }
  80101. }
  80102. if (RSValues.y != 0) {
  80103. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  80104. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  80105. camera.inertialBetaOffset += normalizedRY;
  80106. }
  80107. }
  80108. }
  80109. var LSValues = this.gamepad.leftStick;
  80110. if (LSValues && LSValues.y != 0) {
  80111. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  80112. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  80113. this.camera.inertialRadiusOffset -= normalizedLY;
  80114. }
  80115. }
  80116. }
  80117. };
  80118. /**
  80119. * Gets the class name of the current intput.
  80120. * @returns the class name
  80121. */
  80122. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  80123. return "ArcRotateCameraGamepadInput";
  80124. };
  80125. /**
  80126. * Get the friendly name associated with the input class.
  80127. * @returns the input friendly name
  80128. */
  80129. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  80130. return "gamepad";
  80131. };
  80132. __decorate([
  80133. BABYLON.serialize()
  80134. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  80135. __decorate([
  80136. BABYLON.serialize()
  80137. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  80138. return ArcRotateCameraGamepadInput;
  80139. }());
  80140. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  80141. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  80142. })(BABYLON || (BABYLON = {}));
  80143. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  80144. var BABYLON;
  80145. (function (BABYLON) {
  80146. /**
  80147. * Manager for handling gamepads
  80148. */
  80149. var GamepadManager = /** @class */ (function () {
  80150. /**
  80151. * Initializes the gamepad manager
  80152. * @param _scene BabylonJS scene
  80153. */
  80154. function GamepadManager(_scene) {
  80155. var _this = this;
  80156. this._scene = _scene;
  80157. this._babylonGamepads = [];
  80158. this._oneGamepadConnected = false;
  80159. /** @hidden */
  80160. this._isMonitoring = false;
  80161. /**
  80162. * observable to be triggered when the gamepad controller has been disconnected
  80163. */
  80164. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  80165. if (!BABYLON.Tools.IsWindowObjectExist()) {
  80166. this._gamepadEventSupported = false;
  80167. }
  80168. else {
  80169. this._gamepadEventSupported = 'GamepadEvent' in window;
  80170. this._gamepadSupport = (navigator.getGamepads ||
  80171. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  80172. }
  80173. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  80174. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  80175. for (var i in _this._babylonGamepads) {
  80176. var gamepad = _this._babylonGamepads[i];
  80177. if (gamepad && gamepad._isConnected) {
  80178. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  80179. }
  80180. }
  80181. });
  80182. this._onGamepadConnectedEvent = function (evt) {
  80183. var gamepad = evt.gamepad;
  80184. if (gamepad.index in _this._babylonGamepads) {
  80185. if (_this._babylonGamepads[gamepad.index].isConnected) {
  80186. return;
  80187. }
  80188. }
  80189. var newGamepad;
  80190. if (_this._babylonGamepads[gamepad.index]) {
  80191. newGamepad = _this._babylonGamepads[gamepad.index];
  80192. newGamepad.browserGamepad = gamepad;
  80193. newGamepad._isConnected = true;
  80194. }
  80195. else {
  80196. newGamepad = _this._addNewGamepad(gamepad);
  80197. }
  80198. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80199. _this._startMonitoringGamepads();
  80200. };
  80201. this._onGamepadDisconnectedEvent = function (evt) {
  80202. var gamepad = evt.gamepad;
  80203. // Remove the gamepad from the list of gamepads to monitor.
  80204. for (var i in _this._babylonGamepads) {
  80205. if (_this._babylonGamepads[i].index === gamepad.index) {
  80206. var disconnectedGamepad = _this._babylonGamepads[i];
  80207. disconnectedGamepad._isConnected = false;
  80208. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  80209. break;
  80210. }
  80211. }
  80212. };
  80213. if (this._gamepadSupport) {
  80214. //first add already-connected gamepads
  80215. this._updateGamepadObjects();
  80216. if (this._babylonGamepads.length) {
  80217. this._startMonitoringGamepads();
  80218. }
  80219. // Checking if the gamepad connected event is supported (like in Firefox)
  80220. if (this._gamepadEventSupported) {
  80221. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  80222. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  80223. }
  80224. else {
  80225. this._startMonitoringGamepads();
  80226. }
  80227. }
  80228. }
  80229. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  80230. /**
  80231. * The gamepads in the game pad manager
  80232. */
  80233. get: function () {
  80234. return this._babylonGamepads;
  80235. },
  80236. enumerable: true,
  80237. configurable: true
  80238. });
  80239. /**
  80240. * Get the gamepad controllers based on type
  80241. * @param type The type of gamepad controller
  80242. * @returns Nullable gamepad
  80243. */
  80244. GamepadManager.prototype.getGamepadByType = function (type) {
  80245. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  80246. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  80247. var gamepad = _a[_i];
  80248. if (gamepad && gamepad.type === type) {
  80249. return gamepad;
  80250. }
  80251. }
  80252. return null;
  80253. };
  80254. /**
  80255. * Disposes the gamepad manager
  80256. */
  80257. GamepadManager.prototype.dispose = function () {
  80258. if (this._gamepadEventSupported) {
  80259. if (this._onGamepadConnectedEvent) {
  80260. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  80261. }
  80262. if (this._onGamepadDisconnectedEvent) {
  80263. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  80264. }
  80265. this._onGamepadConnectedEvent = null;
  80266. this._onGamepadDisconnectedEvent = null;
  80267. }
  80268. this._babylonGamepads.forEach(function (gamepad) {
  80269. gamepad.dispose();
  80270. });
  80271. this.onGamepadConnectedObservable.clear();
  80272. this.onGamepadDisconnectedObservable.clear();
  80273. this._oneGamepadConnected = false;
  80274. this._stopMonitoringGamepads();
  80275. this._babylonGamepads = [];
  80276. };
  80277. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  80278. if (!this._oneGamepadConnected) {
  80279. this._oneGamepadConnected = true;
  80280. }
  80281. var newGamepad;
  80282. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  80283. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  80284. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  80285. }
  80286. // if pose is supported, use the (WebVR) pose enabled controller
  80287. else if (gamepad.pose) {
  80288. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  80289. }
  80290. else {
  80291. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  80292. }
  80293. this._babylonGamepads[newGamepad.index] = newGamepad;
  80294. return newGamepad;
  80295. };
  80296. GamepadManager.prototype._startMonitoringGamepads = function () {
  80297. if (!this._isMonitoring) {
  80298. this._isMonitoring = true;
  80299. //back-comp
  80300. if (!this._scene) {
  80301. this._checkGamepadsStatus();
  80302. }
  80303. }
  80304. };
  80305. GamepadManager.prototype._stopMonitoringGamepads = function () {
  80306. this._isMonitoring = false;
  80307. };
  80308. /** @hidden */
  80309. GamepadManager.prototype._checkGamepadsStatus = function () {
  80310. var _this = this;
  80311. // Hack to be compatible Chrome
  80312. this._updateGamepadObjects();
  80313. for (var i in this._babylonGamepads) {
  80314. var gamepad = this._babylonGamepads[i];
  80315. if (!gamepad || !gamepad.isConnected) {
  80316. continue;
  80317. }
  80318. gamepad.update();
  80319. }
  80320. if (this._isMonitoring && !this._scene) {
  80321. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  80322. }
  80323. };
  80324. // This function is called only on Chrome, which does not properly support
  80325. // connection/disconnection events and forces you to recopy again the gamepad object
  80326. GamepadManager.prototype._updateGamepadObjects = function () {
  80327. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  80328. for (var i = 0; i < gamepads.length; i++) {
  80329. var gamepad = gamepads[i];
  80330. if (gamepad) {
  80331. if (!this._babylonGamepads[gamepad.index]) {
  80332. var newGamepad = this._addNewGamepad(gamepad);
  80333. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80334. }
  80335. else {
  80336. // Forced to copy again this object for Chrome for unknown reason
  80337. this._babylonGamepads[i].browserGamepad = gamepad;
  80338. if (!this._babylonGamepads[i].isConnected) {
  80339. this._babylonGamepads[i]._isConnected = true;
  80340. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  80341. }
  80342. }
  80343. }
  80344. }
  80345. };
  80346. return GamepadManager;
  80347. }());
  80348. BABYLON.GamepadManager = GamepadManager;
  80349. })(BABYLON || (BABYLON = {}));
  80350. //# sourceMappingURL=babylon.gamepadManager.js.map
  80351. var BABYLON;
  80352. (function (BABYLON) {
  80353. /**
  80354. * Represents a gamepad control stick position
  80355. */
  80356. var StickValues = /** @class */ (function () {
  80357. /**
  80358. * Initializes the gamepad x and y control stick values
  80359. * @param x The x component of the gamepad control stick value
  80360. * @param y The y component of the gamepad control stick value
  80361. */
  80362. function StickValues(
  80363. /**
  80364. * The x component of the control stick
  80365. */
  80366. x,
  80367. /**
  80368. * The y component of the control stick
  80369. */
  80370. y) {
  80371. this.x = x;
  80372. this.y = y;
  80373. }
  80374. return StickValues;
  80375. }());
  80376. BABYLON.StickValues = StickValues;
  80377. /**
  80378. * Represents a gamepad
  80379. */
  80380. var Gamepad = /** @class */ (function () {
  80381. /**
  80382. * Initializes the gamepad
  80383. * @param id The id of the gamepad
  80384. * @param index The index of the gamepad
  80385. * @param browserGamepad The browser gamepad
  80386. * @param leftStickX The x component of the left joystick
  80387. * @param leftStickY The y component of the left joystick
  80388. * @param rightStickX The x component of the right joystick
  80389. * @param rightStickY The y component of the right joystick
  80390. */
  80391. function Gamepad(
  80392. /**
  80393. * The id of the gamepad
  80394. */
  80395. id,
  80396. /**
  80397. * The index of the gamepad
  80398. */
  80399. index,
  80400. /**
  80401. * The browser gamepad
  80402. */
  80403. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  80404. if (leftStickX === void 0) { leftStickX = 0; }
  80405. if (leftStickY === void 0) { leftStickY = 1; }
  80406. if (rightStickX === void 0) { rightStickX = 2; }
  80407. if (rightStickY === void 0) { rightStickY = 3; }
  80408. this.id = id;
  80409. this.index = index;
  80410. this.browserGamepad = browserGamepad;
  80411. this._leftStick = { x: 0, y: 0 };
  80412. this._rightStick = { x: 0, y: 0 };
  80413. /** @hidden */
  80414. this._isConnected = true;
  80415. /**
  80416. * Specifies whether the left control stick should be Y-inverted
  80417. */
  80418. this._invertLeftStickY = false;
  80419. this.type = Gamepad.GAMEPAD;
  80420. this._leftStickAxisX = leftStickX;
  80421. this._leftStickAxisY = leftStickY;
  80422. this._rightStickAxisX = rightStickX;
  80423. this._rightStickAxisY = rightStickY;
  80424. if (this.browserGamepad.axes.length >= 2) {
  80425. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80426. }
  80427. if (this.browserGamepad.axes.length >= 4) {
  80428. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80429. }
  80430. }
  80431. Object.defineProperty(Gamepad.prototype, "isConnected", {
  80432. /**
  80433. * Specifies if the gamepad has been connected
  80434. */
  80435. get: function () {
  80436. return this._isConnected;
  80437. },
  80438. enumerable: true,
  80439. configurable: true
  80440. });
  80441. /**
  80442. * Callback triggered when the left joystick has changed
  80443. * @param callback
  80444. */
  80445. Gamepad.prototype.onleftstickchanged = function (callback) {
  80446. this._onleftstickchanged = callback;
  80447. };
  80448. /**
  80449. * Callback triggered when the right joystick has changed
  80450. * @param callback
  80451. */
  80452. Gamepad.prototype.onrightstickchanged = function (callback) {
  80453. this._onrightstickchanged = callback;
  80454. };
  80455. Object.defineProperty(Gamepad.prototype, "leftStick", {
  80456. /**
  80457. * Gets the left joystick
  80458. */
  80459. get: function () {
  80460. return this._leftStick;
  80461. },
  80462. /**
  80463. * Sets the left joystick values
  80464. */
  80465. set: function (newValues) {
  80466. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  80467. this._onleftstickchanged(newValues);
  80468. }
  80469. this._leftStick = newValues;
  80470. },
  80471. enumerable: true,
  80472. configurable: true
  80473. });
  80474. Object.defineProperty(Gamepad.prototype, "rightStick", {
  80475. /**
  80476. * Gets the right joystick
  80477. */
  80478. get: function () {
  80479. return this._rightStick;
  80480. },
  80481. /**
  80482. * Sets the right joystick value
  80483. */
  80484. set: function (newValues) {
  80485. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  80486. this._onrightstickchanged(newValues);
  80487. }
  80488. this._rightStick = newValues;
  80489. },
  80490. enumerable: true,
  80491. configurable: true
  80492. });
  80493. /**
  80494. * Updates the gamepad joystick positions
  80495. */
  80496. Gamepad.prototype.update = function () {
  80497. if (this._leftStick) {
  80498. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80499. if (this._invertLeftStickY) {
  80500. this.leftStick.y *= -1;
  80501. }
  80502. }
  80503. if (this._rightStick) {
  80504. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80505. }
  80506. };
  80507. /**
  80508. * Disposes the gamepad
  80509. */
  80510. Gamepad.prototype.dispose = function () {
  80511. };
  80512. /**
  80513. * Represents a gamepad controller
  80514. */
  80515. Gamepad.GAMEPAD = 0;
  80516. /**
  80517. * Represents a generic controller
  80518. */
  80519. Gamepad.GENERIC = 1;
  80520. /**
  80521. * Represents an XBox controller
  80522. */
  80523. Gamepad.XBOX = 2;
  80524. /**
  80525. * Represents a pose-enabled controller
  80526. */
  80527. Gamepad.POSE_ENABLED = 3;
  80528. return Gamepad;
  80529. }());
  80530. BABYLON.Gamepad = Gamepad;
  80531. /**
  80532. * Represents a generic gamepad
  80533. */
  80534. var GenericPad = /** @class */ (function (_super) {
  80535. __extends(GenericPad, _super);
  80536. /**
  80537. * Initializes the generic gamepad
  80538. * @param id The id of the generic gamepad
  80539. * @param index The index of the generic gamepad
  80540. * @param browserGamepad The browser gamepad
  80541. */
  80542. function GenericPad(id, index, browserGamepad) {
  80543. var _this = _super.call(this, id, index, browserGamepad) || this;
  80544. /**
  80545. * Observable triggered when a button has been pressed
  80546. */
  80547. _this.onButtonDownObservable = new BABYLON.Observable();
  80548. /**
  80549. * Observable triggered when a button has been released
  80550. */
  80551. _this.onButtonUpObservable = new BABYLON.Observable();
  80552. _this.type = Gamepad.GENERIC;
  80553. _this._buttons = new Array(browserGamepad.buttons.length);
  80554. return _this;
  80555. }
  80556. /**
  80557. * Callback triggered when a button has been pressed
  80558. * @param callback Called when a button has been pressed
  80559. */
  80560. GenericPad.prototype.onbuttondown = function (callback) {
  80561. this._onbuttondown = callback;
  80562. };
  80563. /**
  80564. * Callback triggered when a button has been released
  80565. * @param callback Called when a button has been released
  80566. */
  80567. GenericPad.prototype.onbuttonup = function (callback) {
  80568. this._onbuttonup = callback;
  80569. };
  80570. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  80571. if (newValue !== currentValue) {
  80572. if (newValue === 1) {
  80573. if (this._onbuttondown) {
  80574. this._onbuttondown(buttonIndex);
  80575. }
  80576. this.onButtonDownObservable.notifyObservers(buttonIndex);
  80577. }
  80578. if (newValue === 0) {
  80579. if (this._onbuttonup) {
  80580. this._onbuttonup(buttonIndex);
  80581. }
  80582. this.onButtonUpObservable.notifyObservers(buttonIndex);
  80583. }
  80584. }
  80585. return newValue;
  80586. };
  80587. /**
  80588. * Updates the generic gamepad
  80589. */
  80590. GenericPad.prototype.update = function () {
  80591. _super.prototype.update.call(this);
  80592. for (var index = 0; index < this._buttons.length; index++) {
  80593. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  80594. }
  80595. };
  80596. /**
  80597. * Disposes the generic gamepad
  80598. */
  80599. GenericPad.prototype.dispose = function () {
  80600. _super.prototype.dispose.call(this);
  80601. this.onButtonDownObservable.clear();
  80602. this.onButtonUpObservable.clear();
  80603. };
  80604. return GenericPad;
  80605. }(Gamepad));
  80606. BABYLON.GenericPad = GenericPad;
  80607. })(BABYLON || (BABYLON = {}));
  80608. //# sourceMappingURL=babylon.gamepad.js.map
  80609. var BABYLON;
  80610. (function (BABYLON) {
  80611. /**
  80612. * Defines supported buttons for XBox360 compatible gamepads
  80613. */
  80614. var Xbox360Button;
  80615. (function (Xbox360Button) {
  80616. /** A */
  80617. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  80618. /** B */
  80619. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  80620. /** X */
  80621. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  80622. /** Y */
  80623. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  80624. /** Start */
  80625. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  80626. /** Back */
  80627. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  80628. /** Left button */
  80629. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  80630. /** Right button */
  80631. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  80632. /** Left stick */
  80633. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  80634. /** Right stick */
  80635. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  80636. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  80637. /** Defines values for XBox360 DPad */
  80638. var Xbox360Dpad;
  80639. (function (Xbox360Dpad) {
  80640. /** Up */
  80641. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  80642. /** Down */
  80643. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  80644. /** Left */
  80645. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  80646. /** Right */
  80647. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  80648. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  80649. /**
  80650. * Defines a XBox360 gamepad
  80651. */
  80652. var Xbox360Pad = /** @class */ (function (_super) {
  80653. __extends(Xbox360Pad, _super);
  80654. /**
  80655. * Creates a new XBox360 gamepad object
  80656. * @param id defines the id of this gamepad
  80657. * @param index defines its index
  80658. * @param gamepad defines the internal HTML gamepad object
  80659. * @param xboxOne defines if it is a XBox One gamepad
  80660. */
  80661. function Xbox360Pad(id, index, gamepad, xboxOne) {
  80662. if (xboxOne === void 0) { xboxOne = false; }
  80663. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  80664. _this._leftTrigger = 0;
  80665. _this._rightTrigger = 0;
  80666. /** Observable raised when a button is pressed */
  80667. _this.onButtonDownObservable = new BABYLON.Observable();
  80668. /** Observable raised when a button is released */
  80669. _this.onButtonUpObservable = new BABYLON.Observable();
  80670. /** Observable raised when a pad is pressed */
  80671. _this.onPadDownObservable = new BABYLON.Observable();
  80672. /** Observable raised when a pad is released */
  80673. _this.onPadUpObservable = new BABYLON.Observable();
  80674. _this._buttonA = 0;
  80675. _this._buttonB = 0;
  80676. _this._buttonX = 0;
  80677. _this._buttonY = 0;
  80678. _this._buttonBack = 0;
  80679. _this._buttonStart = 0;
  80680. _this._buttonLB = 0;
  80681. _this._buttonRB = 0;
  80682. _this._buttonLeftStick = 0;
  80683. _this._buttonRightStick = 0;
  80684. _this._dPadUp = 0;
  80685. _this._dPadDown = 0;
  80686. _this._dPadLeft = 0;
  80687. _this._dPadRight = 0;
  80688. _this._isXboxOnePad = false;
  80689. _this.type = BABYLON.Gamepad.XBOX;
  80690. _this._isXboxOnePad = xboxOne;
  80691. return _this;
  80692. }
  80693. /**
  80694. * Defines the callback to call when left trigger is pressed
  80695. * @param callback defines the callback to use
  80696. */
  80697. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  80698. this._onlefttriggerchanged = callback;
  80699. };
  80700. /**
  80701. * Defines the callback to call when right trigger is pressed
  80702. * @param callback defines the callback to use
  80703. */
  80704. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  80705. this._onrighttriggerchanged = callback;
  80706. };
  80707. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  80708. /**
  80709. * Gets the left trigger value
  80710. */
  80711. get: function () {
  80712. return this._leftTrigger;
  80713. },
  80714. /**
  80715. * Sets the left trigger value
  80716. */
  80717. set: function (newValue) {
  80718. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  80719. this._onlefttriggerchanged(newValue);
  80720. }
  80721. this._leftTrigger = newValue;
  80722. },
  80723. enumerable: true,
  80724. configurable: true
  80725. });
  80726. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  80727. /**
  80728. * Gets the right trigger value
  80729. */
  80730. get: function () {
  80731. return this._rightTrigger;
  80732. },
  80733. /**
  80734. * Sets the right trigger value
  80735. */
  80736. set: function (newValue) {
  80737. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  80738. this._onrighttriggerchanged(newValue);
  80739. }
  80740. this._rightTrigger = newValue;
  80741. },
  80742. enumerable: true,
  80743. configurable: true
  80744. });
  80745. /**
  80746. * Defines the callback to call when a button is pressed
  80747. * @param callback defines the callback to use
  80748. */
  80749. Xbox360Pad.prototype.onbuttondown = function (callback) {
  80750. this._onbuttondown = callback;
  80751. };
  80752. /**
  80753. * Defines the callback to call when a button is released
  80754. * @param callback defines the callback to use
  80755. */
  80756. Xbox360Pad.prototype.onbuttonup = function (callback) {
  80757. this._onbuttonup = callback;
  80758. };
  80759. /**
  80760. * Defines the callback to call when a pad is pressed
  80761. * @param callback defines the callback to use
  80762. */
  80763. Xbox360Pad.prototype.ondpaddown = function (callback) {
  80764. this._ondpaddown = callback;
  80765. };
  80766. /**
  80767. * Defines the callback to call when a pad is released
  80768. * @param callback defines the callback to use
  80769. */
  80770. Xbox360Pad.prototype.ondpadup = function (callback) {
  80771. this._ondpadup = callback;
  80772. };
  80773. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  80774. if (newValue !== currentValue) {
  80775. if (newValue === 1) {
  80776. if (this._onbuttondown) {
  80777. this._onbuttondown(buttonType);
  80778. }
  80779. this.onButtonDownObservable.notifyObservers(buttonType);
  80780. }
  80781. if (newValue === 0) {
  80782. if (this._onbuttonup) {
  80783. this._onbuttonup(buttonType);
  80784. }
  80785. this.onButtonUpObservable.notifyObservers(buttonType);
  80786. }
  80787. }
  80788. return newValue;
  80789. };
  80790. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  80791. if (newValue !== currentValue) {
  80792. if (newValue === 1) {
  80793. if (this._ondpaddown) {
  80794. this._ondpaddown(buttonType);
  80795. }
  80796. this.onPadDownObservable.notifyObservers(buttonType);
  80797. }
  80798. if (newValue === 0) {
  80799. if (this._ondpadup) {
  80800. this._ondpadup(buttonType);
  80801. }
  80802. this.onPadUpObservable.notifyObservers(buttonType);
  80803. }
  80804. }
  80805. return newValue;
  80806. };
  80807. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  80808. /**
  80809. * Gets the value of the `A` button
  80810. */
  80811. get: function () {
  80812. return this._buttonA;
  80813. },
  80814. /**
  80815. * Sets the value of the `A` button
  80816. */
  80817. set: function (value) {
  80818. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  80819. },
  80820. enumerable: true,
  80821. configurable: true
  80822. });
  80823. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  80824. /**
  80825. * Gets the value of the `B` button
  80826. */
  80827. get: function () {
  80828. return this._buttonB;
  80829. },
  80830. /**
  80831. * Sets the value of the `B` button
  80832. */
  80833. set: function (value) {
  80834. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  80835. },
  80836. enumerable: true,
  80837. configurable: true
  80838. });
  80839. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  80840. /**
  80841. * Gets the value of the `X` button
  80842. */
  80843. get: function () {
  80844. return this._buttonX;
  80845. },
  80846. /**
  80847. * Sets the value of the `X` button
  80848. */
  80849. set: function (value) {
  80850. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  80851. },
  80852. enumerable: true,
  80853. configurable: true
  80854. });
  80855. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  80856. /**
  80857. * Gets the value of the `Y` button
  80858. */
  80859. get: function () {
  80860. return this._buttonY;
  80861. },
  80862. /**
  80863. * Sets the value of the `Y` button
  80864. */
  80865. set: function (value) {
  80866. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  80867. },
  80868. enumerable: true,
  80869. configurable: true
  80870. });
  80871. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  80872. /**
  80873. * Gets the value of the `Start` button
  80874. */
  80875. get: function () {
  80876. return this._buttonStart;
  80877. },
  80878. /**
  80879. * Sets the value of the `Start` button
  80880. */
  80881. set: function (value) {
  80882. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  80883. },
  80884. enumerable: true,
  80885. configurable: true
  80886. });
  80887. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  80888. /**
  80889. * Gets the value of the `Back` button
  80890. */
  80891. get: function () {
  80892. return this._buttonBack;
  80893. },
  80894. /**
  80895. * Sets the value of the `Back` button
  80896. */
  80897. set: function (value) {
  80898. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  80899. },
  80900. enumerable: true,
  80901. configurable: true
  80902. });
  80903. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  80904. /**
  80905. * Gets the value of the `Left` button
  80906. */
  80907. get: function () {
  80908. return this._buttonLB;
  80909. },
  80910. /**
  80911. * Sets the value of the `Left` button
  80912. */
  80913. set: function (value) {
  80914. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  80915. },
  80916. enumerable: true,
  80917. configurable: true
  80918. });
  80919. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  80920. /**
  80921. * Gets the value of the `Right` button
  80922. */
  80923. get: function () {
  80924. return this._buttonRB;
  80925. },
  80926. /**
  80927. * Sets the value of the `Right` button
  80928. */
  80929. set: function (value) {
  80930. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  80931. },
  80932. enumerable: true,
  80933. configurable: true
  80934. });
  80935. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  80936. /**
  80937. * Gets the value of the Left joystick
  80938. */
  80939. get: function () {
  80940. return this._buttonLeftStick;
  80941. },
  80942. /**
  80943. * Sets the value of the Left joystick
  80944. */
  80945. set: function (value) {
  80946. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  80947. },
  80948. enumerable: true,
  80949. configurable: true
  80950. });
  80951. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  80952. /**
  80953. * Gets the value of the Right joystick
  80954. */
  80955. get: function () {
  80956. return this._buttonRightStick;
  80957. },
  80958. /**
  80959. * Sets the value of the Right joystick
  80960. */
  80961. set: function (value) {
  80962. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  80963. },
  80964. enumerable: true,
  80965. configurable: true
  80966. });
  80967. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  80968. /**
  80969. * Gets the value of D-pad up
  80970. */
  80971. get: function () {
  80972. return this._dPadUp;
  80973. },
  80974. /**
  80975. * Sets the value of D-pad up
  80976. */
  80977. set: function (value) {
  80978. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  80979. },
  80980. enumerable: true,
  80981. configurable: true
  80982. });
  80983. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  80984. /**
  80985. * Gets the value of D-pad down
  80986. */
  80987. get: function () {
  80988. return this._dPadDown;
  80989. },
  80990. /**
  80991. * Sets the value of D-pad down
  80992. */
  80993. set: function (value) {
  80994. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  80995. },
  80996. enumerable: true,
  80997. configurable: true
  80998. });
  80999. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  81000. /**
  81001. * Gets the value of D-pad left
  81002. */
  81003. get: function () {
  81004. return this._dPadLeft;
  81005. },
  81006. /**
  81007. * Sets the value of D-pad left
  81008. */
  81009. set: function (value) {
  81010. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  81011. },
  81012. enumerable: true,
  81013. configurable: true
  81014. });
  81015. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  81016. /**
  81017. * Gets the value of D-pad right
  81018. */
  81019. get: function () {
  81020. return this._dPadRight;
  81021. },
  81022. /**
  81023. * Sets the value of D-pad right
  81024. */
  81025. set: function (value) {
  81026. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  81027. },
  81028. enumerable: true,
  81029. configurable: true
  81030. });
  81031. /**
  81032. * Force the gamepad to synchronize with device values
  81033. */
  81034. Xbox360Pad.prototype.update = function () {
  81035. _super.prototype.update.call(this);
  81036. if (this._isXboxOnePad) {
  81037. this.buttonA = this.browserGamepad.buttons[0].value;
  81038. this.buttonB = this.browserGamepad.buttons[1].value;
  81039. this.buttonX = this.browserGamepad.buttons[2].value;
  81040. this.buttonY = this.browserGamepad.buttons[3].value;
  81041. this.buttonLB = this.browserGamepad.buttons[4].value;
  81042. this.buttonRB = this.browserGamepad.buttons[5].value;
  81043. this.leftTrigger = this.browserGamepad.axes[2];
  81044. this.rightTrigger = this.browserGamepad.axes[5];
  81045. this.buttonBack = this.browserGamepad.buttons[9].value;
  81046. this.buttonStart = this.browserGamepad.buttons[8].value;
  81047. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  81048. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  81049. this.dPadUp = this.browserGamepad.buttons[11].value;
  81050. this.dPadDown = this.browserGamepad.buttons[12].value;
  81051. this.dPadLeft = this.browserGamepad.buttons[13].value;
  81052. this.dPadRight = this.browserGamepad.buttons[14].value;
  81053. }
  81054. else {
  81055. this.buttonA = this.browserGamepad.buttons[0].value;
  81056. this.buttonB = this.browserGamepad.buttons[1].value;
  81057. this.buttonX = this.browserGamepad.buttons[2].value;
  81058. this.buttonY = this.browserGamepad.buttons[3].value;
  81059. this.buttonLB = this.browserGamepad.buttons[4].value;
  81060. this.buttonRB = this.browserGamepad.buttons[5].value;
  81061. this.leftTrigger = this.browserGamepad.buttons[6].value;
  81062. this.rightTrigger = this.browserGamepad.buttons[7].value;
  81063. this.buttonBack = this.browserGamepad.buttons[8].value;
  81064. this.buttonStart = this.browserGamepad.buttons[9].value;
  81065. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  81066. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  81067. this.dPadUp = this.browserGamepad.buttons[12].value;
  81068. this.dPadDown = this.browserGamepad.buttons[13].value;
  81069. this.dPadLeft = this.browserGamepad.buttons[14].value;
  81070. this.dPadRight = this.browserGamepad.buttons[15].value;
  81071. }
  81072. };
  81073. /**
  81074. * Disposes the gamepad
  81075. */
  81076. Xbox360Pad.prototype.dispose = function () {
  81077. _super.prototype.dispose.call(this);
  81078. this.onButtonDownObservable.clear();
  81079. this.onButtonUpObservable.clear();
  81080. this.onPadDownObservable.clear();
  81081. this.onPadUpObservable.clear();
  81082. };
  81083. return Xbox360Pad;
  81084. }(BABYLON.Gamepad));
  81085. BABYLON.Xbox360Pad = Xbox360Pad;
  81086. })(BABYLON || (BABYLON = {}));
  81087. //# sourceMappingURL=babylon.xboxGamepad.js.map
  81088. var BABYLON;
  81089. (function (BABYLON) {
  81090. /**
  81091. * Defines the types of pose enabled controllers that are supported
  81092. */
  81093. var PoseEnabledControllerType;
  81094. (function (PoseEnabledControllerType) {
  81095. /**
  81096. * HTC Vive
  81097. */
  81098. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  81099. /**
  81100. * Oculus Rift
  81101. */
  81102. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  81103. /**
  81104. * Windows mixed reality
  81105. */
  81106. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  81107. /**
  81108. * Samsung gear VR
  81109. */
  81110. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  81111. /**
  81112. * Google Daydream
  81113. */
  81114. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  81115. /**
  81116. * Generic
  81117. */
  81118. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  81119. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  81120. /**
  81121. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  81122. */
  81123. var PoseEnabledControllerHelper = /** @class */ (function () {
  81124. function PoseEnabledControllerHelper() {
  81125. }
  81126. /**
  81127. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  81128. * @param vrGamepad the gamepad to initialized
  81129. * @returns a vr controller of the type the gamepad identified as
  81130. */
  81131. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  81132. // Oculus Touch
  81133. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  81134. return new BABYLON.OculusTouchController(vrGamepad);
  81135. }
  81136. // Windows Mixed Reality controllers
  81137. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  81138. return new BABYLON.WindowsMotionController(vrGamepad);
  81139. }
  81140. // HTC Vive
  81141. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  81142. return new BABYLON.ViveController(vrGamepad);
  81143. }
  81144. // Samsung/Oculus Gear VR or Oculus Go
  81145. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  81146. return new BABYLON.GearVRController(vrGamepad);
  81147. }
  81148. // Google Daydream
  81149. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  81150. return new BABYLON.DaydreamController(vrGamepad);
  81151. }
  81152. // Generic
  81153. else {
  81154. return new BABYLON.GenericController(vrGamepad);
  81155. }
  81156. };
  81157. return PoseEnabledControllerHelper;
  81158. }());
  81159. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  81160. /**
  81161. * Defines the PoseEnabledController object that contains state of a vr capable controller
  81162. */
  81163. var PoseEnabledController = /** @class */ (function (_super) {
  81164. __extends(PoseEnabledController, _super);
  81165. /**
  81166. * Creates a new PoseEnabledController from a gamepad
  81167. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  81168. */
  81169. function PoseEnabledController(browserGamepad) {
  81170. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  81171. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81172. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81173. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  81174. /**
  81175. * The device position in babylon space
  81176. */
  81177. _this.devicePosition = BABYLON.Vector3.Zero();
  81178. /**
  81179. * The device rotation in babylon space
  81180. */
  81181. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  81182. /**
  81183. * The scale factor of the device in babylon space
  81184. */
  81185. _this.deviceScaleFactor = 1;
  81186. // Used to convert 6dof controllers to 3dof
  81187. _this._trackPosition = true;
  81188. _this._maxRotationDistFromHeadset = Math.PI / 5;
  81189. _this._draggedRoomRotation = 0;
  81190. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  81191. /**
  81192. * Internal, matrix used to convert room space to babylon space
  81193. * @hidden
  81194. */
  81195. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81196. /**
  81197. * Node to be used when casting a ray from the controller
  81198. * @hidden
  81199. */
  81200. _this._pointingPoseNode = null;
  81201. _this._workingMatrix = BABYLON.Matrix.Identity();
  81202. /**
  81203. * @hidden
  81204. */
  81205. _this._meshAttachedObservable = new BABYLON.Observable();
  81206. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  81207. _this.controllerType = PoseEnabledControllerType.GENERIC;
  81208. _this.position = BABYLON.Vector3.Zero();
  81209. _this.rotationQuaternion = new BABYLON.Quaternion();
  81210. _this._calculatedPosition = BABYLON.Vector3.Zero();
  81211. _this._calculatedRotation = new BABYLON.Quaternion();
  81212. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  81213. return _this;
  81214. }
  81215. /**
  81216. * @hidden
  81217. */
  81218. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  81219. if (this._trackPosition) {
  81220. this._calculatedPosition.copyFrom(fixedPosition);
  81221. this._trackPosition = false;
  81222. }
  81223. };
  81224. /**
  81225. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  81226. */
  81227. PoseEnabledController.prototype.update = function () {
  81228. _super.prototype.update.call(this);
  81229. this._updatePoseAndMesh();
  81230. };
  81231. /**
  81232. * Updates only the pose device and mesh without doing any button event checking
  81233. */
  81234. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  81235. var pose = this.browserGamepad.pose;
  81236. this.updateFromDevice(pose);
  81237. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  81238. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  81239. camera._computeDevicePosition();
  81240. this._deviceToWorld.setTranslation(camera.devicePosition);
  81241. if (camera.deviceRotationQuaternion) {
  81242. var camera = camera;
  81243. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  81244. // Find the radian distance away that the headset is from the controllers rotation
  81245. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  81246. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  81247. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  81248. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  81249. this._draggedRoomRotation += rotationAmount;
  81250. // Rotate controller around headset
  81251. var sin = Math.sin(-rotationAmount);
  81252. var cos = Math.cos(-rotationAmount);
  81253. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  81254. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  81255. }
  81256. }
  81257. }
  81258. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  81259. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  81260. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81261. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  81262. if (this._mesh) {
  81263. this._mesh.position.copyFrom(this.devicePosition);
  81264. if (this._mesh.rotationQuaternion) {
  81265. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  81266. }
  81267. }
  81268. };
  81269. /**
  81270. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  81271. * @param poseData raw pose fromthe device
  81272. */
  81273. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  81274. if (poseData) {
  81275. this.rawPose = poseData;
  81276. if (poseData.position) {
  81277. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  81278. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  81279. this._deviceRoomPosition.z *= -1;
  81280. }
  81281. if (this._trackPosition) {
  81282. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  81283. }
  81284. this._calculatedPosition.addInPlace(this.position);
  81285. }
  81286. var pose = this.rawPose;
  81287. if (poseData.orientation && pose.orientation) {
  81288. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  81289. if (this._mesh) {
  81290. if (this._mesh.getScene().useRightHandedSystem) {
  81291. this._deviceRoomRotationQuaternion.z *= -1;
  81292. this._deviceRoomRotationQuaternion.w *= -1;
  81293. }
  81294. else {
  81295. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  81296. }
  81297. }
  81298. // if the camera is set, rotate to the camera's rotation
  81299. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  81300. }
  81301. }
  81302. };
  81303. /**
  81304. * Attaches a mesh to the controller
  81305. * @param mesh the mesh to be attached
  81306. */
  81307. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  81308. if (this._mesh) {
  81309. this._mesh.parent = null;
  81310. }
  81311. this._mesh = mesh;
  81312. if (this._poseControlledCamera) {
  81313. this._mesh.parent = this._poseControlledCamera;
  81314. }
  81315. if (!this._mesh.rotationQuaternion) {
  81316. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  81317. }
  81318. // 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
  81319. this._updatePoseAndMesh();
  81320. if (this._pointingPoseNode) {
  81321. var parents = [];
  81322. var obj = this._pointingPoseNode;
  81323. while (obj.parent) {
  81324. parents.push(obj.parent);
  81325. obj = obj.parent;
  81326. }
  81327. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  81328. }
  81329. this._meshAttachedObservable.notifyObservers(mesh);
  81330. };
  81331. /**
  81332. * Attaches the controllers mesh to a camera
  81333. * @param camera the camera the mesh should be attached to
  81334. */
  81335. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  81336. this._poseControlledCamera = camera;
  81337. if (this._mesh) {
  81338. this._mesh.parent = this._poseControlledCamera;
  81339. }
  81340. };
  81341. /**
  81342. * Disposes of the controller
  81343. */
  81344. PoseEnabledController.prototype.dispose = function () {
  81345. if (this._mesh) {
  81346. this._mesh.dispose();
  81347. }
  81348. this._mesh = null;
  81349. _super.prototype.dispose.call(this);
  81350. };
  81351. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  81352. /**
  81353. * The mesh that is attached to the controller
  81354. */
  81355. get: function () {
  81356. return this._mesh;
  81357. },
  81358. enumerable: true,
  81359. configurable: true
  81360. });
  81361. /**
  81362. * Gets the ray of the controller in the direction the controller is pointing
  81363. * @param length the length the resulting ray should be
  81364. * @returns a ray in the direction the controller is pointing
  81365. */
  81366. PoseEnabledController.prototype.getForwardRay = function (length) {
  81367. if (length === void 0) { length = 100; }
  81368. if (!this.mesh) {
  81369. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  81370. }
  81371. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  81372. var origin = m.getTranslation();
  81373. var forward = new BABYLON.Vector3(0, 0, -1);
  81374. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81375. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81376. return new BABYLON.Ray(origin, direction, length);
  81377. };
  81378. /**
  81379. * Name of the child mesh that can be used to cast a ray from the controller
  81380. */
  81381. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  81382. return PoseEnabledController;
  81383. }(BABYLON.Gamepad));
  81384. BABYLON.PoseEnabledController = PoseEnabledController;
  81385. })(BABYLON || (BABYLON = {}));
  81386. //# sourceMappingURL=babylon.poseEnabledController.js.map
  81387. var BABYLON;
  81388. (function (BABYLON) {
  81389. /**
  81390. * Defines the WebVRController object that represents controllers tracked in 3D space
  81391. */
  81392. var WebVRController = /** @class */ (function (_super) {
  81393. __extends(WebVRController, _super);
  81394. /**
  81395. * Creates a new WebVRController from a gamepad
  81396. * @param vrGamepad the gamepad that the WebVRController should be created from
  81397. */
  81398. function WebVRController(vrGamepad) {
  81399. var _this = _super.call(this, vrGamepad) || this;
  81400. // Observables
  81401. /**
  81402. * Fired when the trigger state has changed
  81403. */
  81404. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  81405. /**
  81406. * Fired when the main button state has changed
  81407. */
  81408. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  81409. /**
  81410. * Fired when the secondary button state has changed
  81411. */
  81412. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  81413. /**
  81414. * Fired when the pad state has changed
  81415. */
  81416. _this.onPadStateChangedObservable = new BABYLON.Observable();
  81417. /**
  81418. * Fired when controllers stick values have changed
  81419. */
  81420. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  81421. /**
  81422. * X and Y axis corrisponding to the controllers joystick
  81423. */
  81424. _this.pad = { x: 0, y: 0 };
  81425. // avoid GC, store state in a tmp object
  81426. _this._changes = {
  81427. pressChanged: false,
  81428. touchChanged: false,
  81429. valueChanged: false,
  81430. changed: false
  81431. };
  81432. _this._buttons = new Array(vrGamepad.buttons.length);
  81433. _this.hand = vrGamepad.hand;
  81434. return _this;
  81435. }
  81436. /**
  81437. * Fired when a controller button's state has changed
  81438. * @param callback the callback containing the button that was modified
  81439. */
  81440. WebVRController.prototype.onButtonStateChange = function (callback) {
  81441. this._onButtonStateChange = callback;
  81442. };
  81443. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  81444. /**
  81445. * The default controller model for the controller
  81446. */
  81447. get: function () {
  81448. return this._defaultModel;
  81449. },
  81450. enumerable: true,
  81451. configurable: true
  81452. });
  81453. /**
  81454. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  81455. */
  81456. WebVRController.prototype.update = function () {
  81457. _super.prototype.update.call(this);
  81458. for (var index = 0; index < this._buttons.length; index++) {
  81459. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  81460. }
  81461. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  81462. this.pad.x = this.leftStick.x;
  81463. this.pad.y = this.leftStick.y;
  81464. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  81465. }
  81466. };
  81467. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  81468. if (!newState) {
  81469. newState = {
  81470. pressed: false,
  81471. touched: false,
  81472. value: 0
  81473. };
  81474. }
  81475. if (!currentState) {
  81476. this._buttons[buttonIndex] = {
  81477. pressed: newState.pressed,
  81478. touched: newState.touched,
  81479. value: newState.value
  81480. };
  81481. return;
  81482. }
  81483. this._checkChanges(newState, currentState);
  81484. if (this._changes.changed) {
  81485. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  81486. this._handleButtonChange(buttonIndex, newState, this._changes);
  81487. }
  81488. this._buttons[buttonIndex].pressed = newState.pressed;
  81489. this._buttons[buttonIndex].touched = newState.touched;
  81490. // oculus triggers are never 0, thou not touched.
  81491. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  81492. };
  81493. WebVRController.prototype._checkChanges = function (newState, currentState) {
  81494. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  81495. this._changes.touchChanged = newState.touched !== currentState.touched;
  81496. this._changes.valueChanged = newState.value !== currentState.value;
  81497. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  81498. return this._changes;
  81499. };
  81500. /**
  81501. * Disposes of th webVRCOntroller
  81502. */
  81503. WebVRController.prototype.dispose = function () {
  81504. _super.prototype.dispose.call(this);
  81505. this.onTriggerStateChangedObservable.clear();
  81506. this.onMainButtonStateChangedObservable.clear();
  81507. this.onSecondaryButtonStateChangedObservable.clear();
  81508. this.onPadStateChangedObservable.clear();
  81509. this.onPadValuesChangedObservable.clear();
  81510. };
  81511. return WebVRController;
  81512. }(BABYLON.PoseEnabledController));
  81513. BABYLON.WebVRController = WebVRController;
  81514. })(BABYLON || (BABYLON = {}));
  81515. //# sourceMappingURL=babylon.webVRController.js.map
  81516. var BABYLON;
  81517. (function (BABYLON) {
  81518. /**
  81519. * Oculus Touch Controller
  81520. */
  81521. var OculusTouchController = /** @class */ (function (_super) {
  81522. __extends(OculusTouchController, _super);
  81523. /**
  81524. * Creates a new OculusTouchController from a gamepad
  81525. * @param vrGamepad the gamepad that the controller should be created from
  81526. */
  81527. function OculusTouchController(vrGamepad) {
  81528. var _this = _super.call(this, vrGamepad) || this;
  81529. /**
  81530. * Fired when the secondary trigger on this controller is modified
  81531. */
  81532. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  81533. /**
  81534. * Fired when the thumb rest on this controller is modified
  81535. */
  81536. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  81537. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  81538. return _this;
  81539. }
  81540. /**
  81541. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81542. * @param scene scene in which to add meshes
  81543. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81544. */
  81545. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81546. var _this = this;
  81547. var meshName;
  81548. // Hand
  81549. if (this.hand === 'left') {
  81550. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  81551. }
  81552. else { // Right is the default if no hand is specified
  81553. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  81554. }
  81555. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  81556. /*
  81557. Parent Mesh name: oculus_touch_left
  81558. - body
  81559. - trigger
  81560. - thumbstick
  81561. - grip
  81562. - button_y
  81563. - button_x
  81564. - button_enter
  81565. */
  81566. _this._defaultModel = newMeshes[1];
  81567. _this.attachToMesh(_this._defaultModel);
  81568. if (meshLoaded) {
  81569. meshLoaded(_this._defaultModel);
  81570. }
  81571. });
  81572. };
  81573. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  81574. /**
  81575. * Fired when the A button on this controller is modified
  81576. */
  81577. get: function () {
  81578. if (this.hand === 'right') {
  81579. return this.onMainButtonStateChangedObservable;
  81580. }
  81581. else {
  81582. throw new Error('No A button on left hand');
  81583. }
  81584. },
  81585. enumerable: true,
  81586. configurable: true
  81587. });
  81588. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  81589. /**
  81590. * Fired when the B button on this controller is modified
  81591. */
  81592. get: function () {
  81593. if (this.hand === 'right') {
  81594. return this.onSecondaryButtonStateChangedObservable;
  81595. }
  81596. else {
  81597. throw new Error('No B button on left hand');
  81598. }
  81599. },
  81600. enumerable: true,
  81601. configurable: true
  81602. });
  81603. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  81604. /**
  81605. * Fired when the X button on this controller is modified
  81606. */
  81607. get: function () {
  81608. if (this.hand === 'left') {
  81609. return this.onMainButtonStateChangedObservable;
  81610. }
  81611. else {
  81612. throw new Error('No X button on right hand');
  81613. }
  81614. },
  81615. enumerable: true,
  81616. configurable: true
  81617. });
  81618. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  81619. /**
  81620. * Fired when the Y button on this controller is modified
  81621. */
  81622. get: function () {
  81623. if (this.hand === 'left') {
  81624. return this.onSecondaryButtonStateChangedObservable;
  81625. }
  81626. else {
  81627. throw new Error('No Y button on right hand');
  81628. }
  81629. },
  81630. enumerable: true,
  81631. configurable: true
  81632. });
  81633. /**
  81634. * Called once for each button that changed state since the last frame
  81635. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  81636. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  81637. * 2) secondary trigger (same)
  81638. * 3) A (right) X (left), touch, pressed = value
  81639. * 4) B / Y
  81640. * 5) thumb rest
  81641. * @param buttonIdx Which button index changed
  81642. * @param state New state of the button
  81643. * @param changes Which properties on the state changed since last frame
  81644. */
  81645. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81646. var notifyObject = state; //{ state: state, changes: changes };
  81647. var triggerDirection = this.hand === 'right' ? -1 : 1;
  81648. switch (buttonIdx) {
  81649. case 0:
  81650. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81651. return;
  81652. case 1: // index trigger
  81653. if (this._defaultModel) {
  81654. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  81655. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  81656. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  81657. }
  81658. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81659. return;
  81660. case 2: // secondary trigger
  81661. if (this._defaultModel) {
  81662. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  81663. }
  81664. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  81665. return;
  81666. case 3:
  81667. if (this._defaultModel) {
  81668. if (notifyObject.pressed) {
  81669. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  81670. }
  81671. else {
  81672. (this._defaultModel.getChildren()[1]).position.y = 0;
  81673. }
  81674. }
  81675. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81676. return;
  81677. case 4:
  81678. if (this._defaultModel) {
  81679. if (notifyObject.pressed) {
  81680. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81681. }
  81682. else {
  81683. (this._defaultModel.getChildren()[2]).position.y = 0;
  81684. }
  81685. }
  81686. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81687. return;
  81688. case 5:
  81689. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  81690. return;
  81691. }
  81692. };
  81693. /**
  81694. * Base Url for the controller model.
  81695. */
  81696. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  81697. /**
  81698. * File name for the left controller model.
  81699. */
  81700. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  81701. /**
  81702. * File name for the right controller model.
  81703. */
  81704. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  81705. return OculusTouchController;
  81706. }(BABYLON.WebVRController));
  81707. BABYLON.OculusTouchController = OculusTouchController;
  81708. })(BABYLON || (BABYLON = {}));
  81709. //# sourceMappingURL=babylon.oculusTouchController.js.map
  81710. var BABYLON;
  81711. (function (BABYLON) {
  81712. /**
  81713. * Vive Controller
  81714. */
  81715. var ViveController = /** @class */ (function (_super) {
  81716. __extends(ViveController, _super);
  81717. /**
  81718. * Creates a new ViveController from a gamepad
  81719. * @param vrGamepad the gamepad that the controller should be created from
  81720. */
  81721. function ViveController(vrGamepad) {
  81722. var _this = _super.call(this, vrGamepad) || this;
  81723. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  81724. _this._invertLeftStickY = true;
  81725. return _this;
  81726. }
  81727. /**
  81728. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81729. * @param scene scene in which to add meshes
  81730. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81731. */
  81732. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81733. var _this = this;
  81734. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  81735. /*
  81736. Parent Mesh name: ViveWand
  81737. - body
  81738. - r_gripper
  81739. - l_gripper
  81740. - menu_button
  81741. - system_button
  81742. - trackpad
  81743. - trigger
  81744. - LED
  81745. */
  81746. _this._defaultModel = newMeshes[1];
  81747. _this.attachToMesh(_this._defaultModel);
  81748. if (meshLoaded) {
  81749. meshLoaded(_this._defaultModel);
  81750. }
  81751. });
  81752. };
  81753. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  81754. /**
  81755. * Fired when the left button on this controller is modified
  81756. */
  81757. get: function () {
  81758. return this.onMainButtonStateChangedObservable;
  81759. },
  81760. enumerable: true,
  81761. configurable: true
  81762. });
  81763. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  81764. /**
  81765. * Fired when the right button on this controller is modified
  81766. */
  81767. get: function () {
  81768. return this.onMainButtonStateChangedObservable;
  81769. },
  81770. enumerable: true,
  81771. configurable: true
  81772. });
  81773. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  81774. /**
  81775. * Fired when the menu button on this controller is modified
  81776. */
  81777. get: function () {
  81778. return this.onSecondaryButtonStateChangedObservable;
  81779. },
  81780. enumerable: true,
  81781. configurable: true
  81782. });
  81783. /**
  81784. * Called once for each button that changed state since the last frame
  81785. * Vive mapping:
  81786. * 0: touchpad
  81787. * 1: trigger
  81788. * 2: left AND right buttons
  81789. * 3: menu button
  81790. * @param buttonIdx Which button index changed
  81791. * @param state New state of the button
  81792. * @param changes Which properties on the state changed since last frame
  81793. */
  81794. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81795. var notifyObject = state; //{ state: state, changes: changes };
  81796. switch (buttonIdx) {
  81797. case 0:
  81798. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81799. return;
  81800. case 1: // index trigger
  81801. if (this._defaultModel) {
  81802. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  81803. }
  81804. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81805. return;
  81806. case 2: // left AND right button
  81807. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81808. return;
  81809. case 3:
  81810. if (this._defaultModel) {
  81811. if (notifyObject.pressed) {
  81812. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81813. }
  81814. else {
  81815. (this._defaultModel.getChildren()[2]).position.y = 0;
  81816. }
  81817. }
  81818. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81819. return;
  81820. }
  81821. };
  81822. /**
  81823. * Base Url for the controller model.
  81824. */
  81825. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  81826. /**
  81827. * File name for the controller model.
  81828. */
  81829. ViveController.MODEL_FILENAME = 'wand.babylon';
  81830. return ViveController;
  81831. }(BABYLON.WebVRController));
  81832. BABYLON.ViveController = ViveController;
  81833. })(BABYLON || (BABYLON = {}));
  81834. //# sourceMappingURL=babylon.viveController.js.map
  81835. var BABYLON;
  81836. (function (BABYLON) {
  81837. /**
  81838. * Generic Controller
  81839. */
  81840. var GenericController = /** @class */ (function (_super) {
  81841. __extends(GenericController, _super);
  81842. /**
  81843. * Creates a new GenericController from a gamepad
  81844. * @param vrGamepad the gamepad that the controller should be created from
  81845. */
  81846. function GenericController(vrGamepad) {
  81847. return _super.call(this, vrGamepad) || this;
  81848. }
  81849. /**
  81850. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81851. * @param scene scene in which to add meshes
  81852. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81853. */
  81854. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81855. var _this = this;
  81856. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  81857. _this._defaultModel = newMeshes[1];
  81858. _this.attachToMesh(_this._defaultModel);
  81859. if (meshLoaded) {
  81860. meshLoaded(_this._defaultModel);
  81861. }
  81862. });
  81863. };
  81864. /**
  81865. * Called once for each button that changed state since the last frame
  81866. * @param buttonIdx Which button index changed
  81867. * @param state New state of the button
  81868. * @param changes Which properties on the state changed since last frame
  81869. */
  81870. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81871. console.log("Button id: " + buttonIdx + "state: ");
  81872. console.dir(state);
  81873. };
  81874. /**
  81875. * Base Url for the controller model.
  81876. */
  81877. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81878. /**
  81879. * File name for the controller model.
  81880. */
  81881. GenericController.MODEL_FILENAME = 'generic.babylon';
  81882. return GenericController;
  81883. }(BABYLON.WebVRController));
  81884. BABYLON.GenericController = GenericController;
  81885. })(BABYLON || (BABYLON = {}));
  81886. //# sourceMappingURL=babylon.genericController.js.map
  81887. var BABYLON;
  81888. (function (BABYLON) {
  81889. /**
  81890. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  81891. */
  81892. var LoadedMeshInfo = /** @class */ (function () {
  81893. function LoadedMeshInfo() {
  81894. /**
  81895. * Map of the button meshes contained in the controller
  81896. */
  81897. this.buttonMeshes = {};
  81898. /**
  81899. * Map of the axis meshes contained in the controller
  81900. */
  81901. this.axisMeshes = {};
  81902. }
  81903. return LoadedMeshInfo;
  81904. }());
  81905. /**
  81906. * Defines the WindowsMotionController object that the state of the windows motion controller
  81907. */
  81908. var WindowsMotionController = /** @class */ (function (_super) {
  81909. __extends(WindowsMotionController, _super);
  81910. /**
  81911. * Creates a new WindowsMotionController from a gamepad
  81912. * @param vrGamepad the gamepad that the controller should be created from
  81913. */
  81914. function WindowsMotionController(vrGamepad) {
  81915. var _this = _super.call(this, vrGamepad) || this;
  81916. _this._mapping = {
  81917. // Semantic button names
  81918. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  81919. // A mapping of the button name to glTF model node name
  81920. // that should be transformed by button value.
  81921. buttonMeshNames: {
  81922. 'trigger': 'SELECT',
  81923. 'menu': 'MENU',
  81924. 'grip': 'GRASP',
  81925. 'thumbstick': 'THUMBSTICK_PRESS',
  81926. 'trackpad': 'TOUCHPAD_PRESS'
  81927. },
  81928. // This mapping is used to translate from the Motion Controller to Babylon semantics
  81929. buttonObservableNames: {
  81930. 'trigger': 'onTriggerStateChangedObservable',
  81931. 'menu': 'onSecondaryButtonStateChangedObservable',
  81932. 'grip': 'onMainButtonStateChangedObservable',
  81933. 'thumbstick': 'onPadStateChangedObservable',
  81934. 'trackpad': 'onTrackpadChangedObservable'
  81935. },
  81936. // A mapping of the axis name to glTF model node name
  81937. // that should be transformed by axis value.
  81938. // This array mirrors the browserGamepad.axes array, such that
  81939. // the mesh corresponding to axis 0 is in this array index 0.
  81940. axisMeshNames: [
  81941. 'THUMBSTICK_X',
  81942. 'THUMBSTICK_Y',
  81943. 'TOUCHPAD_TOUCH_X',
  81944. 'TOUCHPAD_TOUCH_Y'
  81945. ],
  81946. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  81947. };
  81948. /**
  81949. * Fired when the trackpad on this controller is clicked
  81950. */
  81951. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  81952. /**
  81953. * Fired when the trackpad on this controller is modified
  81954. */
  81955. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  81956. /**
  81957. * The current x and y values of this controller's trackpad
  81958. */
  81959. _this.trackpad = { x: 0, y: 0 };
  81960. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  81961. _this._loadedMeshInfo = null;
  81962. return _this;
  81963. }
  81964. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  81965. /**
  81966. * Fired when the trigger on this controller is modified
  81967. */
  81968. get: function () {
  81969. return this.onTriggerStateChangedObservable;
  81970. },
  81971. enumerable: true,
  81972. configurable: true
  81973. });
  81974. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  81975. /**
  81976. * Fired when the menu button on this controller is modified
  81977. */
  81978. get: function () {
  81979. return this.onSecondaryButtonStateChangedObservable;
  81980. },
  81981. enumerable: true,
  81982. configurable: true
  81983. });
  81984. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  81985. /**
  81986. * Fired when the grip button on this controller is modified
  81987. */
  81988. get: function () {
  81989. return this.onMainButtonStateChangedObservable;
  81990. },
  81991. enumerable: true,
  81992. configurable: true
  81993. });
  81994. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  81995. /**
  81996. * Fired when the thumbstick button on this controller is modified
  81997. */
  81998. get: function () {
  81999. return this.onPadStateChangedObservable;
  82000. },
  82001. enumerable: true,
  82002. configurable: true
  82003. });
  82004. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  82005. /**
  82006. * Fired when the touchpad button on this controller is modified
  82007. */
  82008. get: function () {
  82009. return this.onTrackpadChangedObservable;
  82010. },
  82011. enumerable: true,
  82012. configurable: true
  82013. });
  82014. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  82015. /**
  82016. * Fired when the touchpad values on this controller are modified
  82017. */
  82018. get: function () {
  82019. return this.onTrackpadValuesChangedObservable;
  82020. },
  82021. enumerable: true,
  82022. configurable: true
  82023. });
  82024. WindowsMotionController.prototype._updateTrackpad = function () {
  82025. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  82026. this.trackpad.x = this.browserGamepad["axes"][2];
  82027. this.trackpad.y = this.browserGamepad["axes"][3];
  82028. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  82029. }
  82030. };
  82031. /**
  82032. * Called once per frame by the engine.
  82033. */
  82034. WindowsMotionController.prototype.update = function () {
  82035. _super.prototype.update.call(this);
  82036. if (this.browserGamepad.axes) {
  82037. this._updateTrackpad();
  82038. // Only need to animate axes if there is a loaded mesh
  82039. if (this._loadedMeshInfo) {
  82040. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  82041. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  82042. }
  82043. }
  82044. }
  82045. };
  82046. /**
  82047. * Called once for each button that changed state since the last frame
  82048. * @param buttonIdx Which button index changed
  82049. * @param state New state of the button
  82050. * @param changes Which properties on the state changed since last frame
  82051. */
  82052. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82053. var buttonName = this._mapping.buttons[buttonIdx];
  82054. if (!buttonName) {
  82055. return;
  82056. }
  82057. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  82058. this._updateTrackpad();
  82059. // Only emit events for buttons that we know how to map from index to name
  82060. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  82061. if (observable) {
  82062. observable.notifyObservers(state);
  82063. }
  82064. this._lerpButtonTransform(buttonName, state.value);
  82065. };
  82066. /**
  82067. * Moves the buttons on the controller mesh based on their current state
  82068. * @param buttonName the name of the button to move
  82069. * @param buttonValue the value of the button which determines the buttons new position
  82070. */
  82071. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  82072. // If there is no loaded mesh, there is nothing to transform.
  82073. if (!this._loadedMeshInfo) {
  82074. return;
  82075. }
  82076. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  82077. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  82078. return;
  82079. }
  82080. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  82081. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  82082. };
  82083. /**
  82084. * Moves the axis on the controller mesh based on its current state
  82085. * @param axis the index of the axis
  82086. * @param axisValue the value of the axis which determines the meshes new position
  82087. * @hidden
  82088. */
  82089. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  82090. if (!this._loadedMeshInfo) {
  82091. return;
  82092. }
  82093. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  82094. if (!meshInfo) {
  82095. return;
  82096. }
  82097. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  82098. return;
  82099. }
  82100. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  82101. var lerpValue = axisValue * 0.5 + 0.5;
  82102. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  82103. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  82104. };
  82105. /**
  82106. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82107. * @param scene scene in which to add meshes
  82108. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82109. */
  82110. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  82111. var _this = this;
  82112. if (forceDefault === void 0) { forceDefault = false; }
  82113. var path;
  82114. var filename;
  82115. // Checking if GLB loader is present
  82116. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  82117. // Determine the device specific folder based on the ID suffix
  82118. var device = 'default';
  82119. if (this.id && !forceDefault) {
  82120. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  82121. device = ((match && match[0]) || device);
  82122. }
  82123. // Hand
  82124. if (this.hand === 'left') {
  82125. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  82126. }
  82127. else { // Right is the default if no hand is specified
  82128. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  82129. }
  82130. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  82131. }
  82132. else {
  82133. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  82134. path = BABYLON.GenericController.MODEL_BASE_URL;
  82135. filename = BABYLON.GenericController.MODEL_FILENAME;
  82136. }
  82137. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  82138. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  82139. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  82140. if (!_this._loadedMeshInfo) {
  82141. return;
  82142. }
  82143. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  82144. _this.attachToMesh(_this._defaultModel);
  82145. if (meshLoaded) {
  82146. meshLoaded(_this._defaultModel);
  82147. }
  82148. }, null, function (scene, message) {
  82149. BABYLON.Tools.Log(message);
  82150. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  82151. if (!forceDefault) {
  82152. _this.initControllerMesh(scene, meshLoaded, true);
  82153. }
  82154. });
  82155. };
  82156. /**
  82157. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  82158. * can be transformed by button presses and axes values, based on this._mapping.
  82159. *
  82160. * @param scene scene in which the meshes exist
  82161. * @param meshes list of meshes that make up the controller model to process
  82162. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  82163. */
  82164. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  82165. var loadedMeshInfo = null;
  82166. // Create a new mesh to contain the glTF hierarchy
  82167. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  82168. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  82169. var childMesh = null;
  82170. for (var i = 0; i < meshes.length; i++) {
  82171. var mesh = meshes[i];
  82172. if (!mesh.parent) {
  82173. // Exclude controller meshes from picking results
  82174. mesh.isPickable = false;
  82175. // Handle root node, attach to the new parentMesh
  82176. childMesh = mesh;
  82177. break;
  82178. }
  82179. }
  82180. if (childMesh) {
  82181. childMesh.setParent(parentMesh);
  82182. // Create our mesh info. Note that this method will always return non-null.
  82183. loadedMeshInfo = this.createMeshInfo(parentMesh);
  82184. }
  82185. else {
  82186. BABYLON.Tools.Warn('Could not find root node in model file.');
  82187. }
  82188. return loadedMeshInfo;
  82189. };
  82190. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  82191. var loadedMeshInfo = new LoadedMeshInfo();
  82192. var i;
  82193. loadedMeshInfo.rootNode = rootNode;
  82194. // Reset the caches
  82195. loadedMeshInfo.buttonMeshes = {};
  82196. loadedMeshInfo.axisMeshes = {};
  82197. // Button Meshes
  82198. for (i = 0; i < this._mapping.buttons.length; i++) {
  82199. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  82200. if (!buttonMeshName) {
  82201. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  82202. continue;
  82203. }
  82204. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  82205. if (!buttonMesh) {
  82206. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  82207. continue;
  82208. }
  82209. var buttonMeshInfo = {
  82210. index: i,
  82211. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  82212. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  82213. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  82214. };
  82215. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  82216. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  82217. }
  82218. else {
  82219. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  82220. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  82221. '(VALUE: ' + !!buttonMeshInfo.value +
  82222. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  82223. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  82224. ')');
  82225. }
  82226. }
  82227. // Axis Meshes
  82228. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  82229. var axisMeshName = this._mapping.axisMeshNames[i];
  82230. if (!axisMeshName) {
  82231. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  82232. continue;
  82233. }
  82234. var axisMesh = getChildByName(rootNode, axisMeshName);
  82235. if (!axisMesh) {
  82236. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  82237. continue;
  82238. }
  82239. var axisMeshInfo = {
  82240. index: i,
  82241. value: getImmediateChildByName(axisMesh, 'VALUE'),
  82242. min: getImmediateChildByName(axisMesh, 'MIN'),
  82243. max: getImmediateChildByName(axisMesh, 'MAX')
  82244. };
  82245. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  82246. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  82247. }
  82248. else {
  82249. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  82250. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  82251. '(VALUE: ' + !!axisMeshInfo.value +
  82252. ', MIN: ' + !!axisMeshInfo.min +
  82253. ', MAX:' + !!axisMeshInfo.max +
  82254. ')');
  82255. }
  82256. }
  82257. // Pointing Ray
  82258. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  82259. if (!loadedMeshInfo.pointingPoseNode) {
  82260. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  82261. }
  82262. else {
  82263. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  82264. }
  82265. return loadedMeshInfo;
  82266. // Look through all children recursively. This will return null if no mesh exists with the given name.
  82267. function getChildByName(node, name) {
  82268. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  82269. }
  82270. // Look through only immediate children. This will return null if no mesh exists with the given name.
  82271. function getImmediateChildByName(node, name) {
  82272. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  82273. }
  82274. };
  82275. /**
  82276. * Gets the ray of the controller in the direction the controller is pointing
  82277. * @param length the length the resulting ray should be
  82278. * @returns a ray in the direction the controller is pointing
  82279. */
  82280. WindowsMotionController.prototype.getForwardRay = function (length) {
  82281. if (length === void 0) { length = 100; }
  82282. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  82283. return _super.prototype.getForwardRay.call(this, length);
  82284. }
  82285. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  82286. var origin = m.getTranslation();
  82287. var forward = new BABYLON.Vector3(0, 0, -1);
  82288. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82289. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82290. return new BABYLON.Ray(origin, direction, length);
  82291. };
  82292. /**
  82293. * Disposes of the controller
  82294. */
  82295. WindowsMotionController.prototype.dispose = function () {
  82296. _super.prototype.dispose.call(this);
  82297. this.onTrackpadChangedObservable.clear();
  82298. };
  82299. /**
  82300. * The base url used to load the left and right controller models
  82301. */
  82302. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  82303. /**
  82304. * The name of the left controller model file
  82305. */
  82306. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  82307. /**
  82308. * The name of the right controller model file
  82309. */
  82310. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  82311. /**
  82312. * The controller name prefix for this controller type
  82313. */
  82314. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  82315. /**
  82316. * The controller id pattern for this controller type
  82317. */
  82318. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  82319. return WindowsMotionController;
  82320. }(BABYLON.WebVRController));
  82321. BABYLON.WindowsMotionController = WindowsMotionController;
  82322. })(BABYLON || (BABYLON = {}));
  82323. //# sourceMappingURL=babylon.windowsMotionController.js.map
  82324. var BABYLON;
  82325. (function (BABYLON) {
  82326. /**
  82327. * Gear VR Controller
  82328. */
  82329. var GearVRController = /** @class */ (function (_super) {
  82330. __extends(GearVRController, _super);
  82331. /**
  82332. * Creates a new GearVRController from a gamepad
  82333. * @param vrGamepad the gamepad that the controller should be created from
  82334. */
  82335. function GearVRController(vrGamepad) {
  82336. var _this = _super.call(this, vrGamepad) || this;
  82337. _this._buttonIndexToObservableNameMap = [
  82338. 'onTrackpadChangedObservable',
  82339. 'onTriggerStateChangedObservable' // Trigger
  82340. ];
  82341. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  82342. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  82343. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  82344. _this._disableTrackPosition(_this._calculatedPosition);
  82345. return _this;
  82346. }
  82347. /**
  82348. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82349. * @param scene scene in which to add meshes
  82350. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82351. */
  82352. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82353. var _this = this;
  82354. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  82355. // Offset the controller so it will rotate around the users wrist
  82356. var mesh = new BABYLON.Mesh("", scene);
  82357. newMeshes[1].parent = mesh;
  82358. newMeshes[1].position.z = -0.15;
  82359. _this._defaultModel = mesh;
  82360. _this.attachToMesh(_this._defaultModel);
  82361. if (meshLoaded) {
  82362. meshLoaded(_this._defaultModel);
  82363. }
  82364. });
  82365. };
  82366. /**
  82367. * Called once for each button that changed state since the last frame
  82368. * @param buttonIdx Which button index changed
  82369. * @param state New state of the button
  82370. * @param changes Which properties on the state changed since last frame
  82371. */
  82372. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82373. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  82374. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  82375. // Only emit events for buttons that we know how to map from index to observable
  82376. var observable = this[observableName];
  82377. if (observable) {
  82378. observable.notifyObservers(state);
  82379. }
  82380. }
  82381. };
  82382. /**
  82383. * Base Url for the controller model.
  82384. */
  82385. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82386. /**
  82387. * File name for the controller model.
  82388. */
  82389. GearVRController.MODEL_FILENAME = 'generic.babylon';
  82390. /**
  82391. * Gamepad Id prefix used to identify this controller.
  82392. */
  82393. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  82394. return GearVRController;
  82395. }(BABYLON.WebVRController));
  82396. BABYLON.GearVRController = GearVRController;
  82397. })(BABYLON || (BABYLON = {}));
  82398. //# sourceMappingURL=babylon.gearVRController.js.map
  82399. var BABYLON;
  82400. (function (BABYLON) {
  82401. /**
  82402. * Google Daydream controller
  82403. */
  82404. var DaydreamController = /** @class */ (function (_super) {
  82405. __extends(DaydreamController, _super);
  82406. /**
  82407. * Creates a new DaydreamController from a gamepad
  82408. * @param vrGamepad the gamepad that the controller should be created from
  82409. */
  82410. function DaydreamController(vrGamepad) {
  82411. var _this = _super.call(this, vrGamepad) || this;
  82412. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  82413. return _this;
  82414. }
  82415. /**
  82416. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82417. * @param scene scene in which to add meshes
  82418. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82419. */
  82420. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82421. var _this = this;
  82422. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  82423. _this._defaultModel = newMeshes[1];
  82424. _this.attachToMesh(_this._defaultModel);
  82425. if (meshLoaded) {
  82426. meshLoaded(_this._defaultModel);
  82427. }
  82428. });
  82429. };
  82430. /**
  82431. * Called once for each button that changed state since the last frame
  82432. * @param buttonIdx Which button index changed
  82433. * @param state New state of the button
  82434. * @param changes Which properties on the state changed since last frame
  82435. */
  82436. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82437. // Daydream controller only has 1 GamepadButton (on the trackpad).
  82438. if (buttonIdx === 0) {
  82439. var observable = this.onTriggerStateChangedObservable;
  82440. if (observable) {
  82441. observable.notifyObservers(state);
  82442. }
  82443. }
  82444. else {
  82445. // If the app or home buttons are ever made available
  82446. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  82447. }
  82448. };
  82449. /**
  82450. * Base Url for the controller model.
  82451. */
  82452. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82453. /**
  82454. * File name for the controller model.
  82455. */
  82456. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  82457. /**
  82458. * Gamepad Id prefix used to identify Daydream Controller.
  82459. */
  82460. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  82461. return DaydreamController;
  82462. }(BABYLON.WebVRController));
  82463. BABYLON.DaydreamController = DaydreamController;
  82464. })(BABYLON || (BABYLON = {}));
  82465. //# sourceMappingURL=babylon.daydreamController.js.map
  82466. var BABYLON;
  82467. (function (BABYLON) {
  82468. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  82469. get: function () {
  82470. if (!this._gamepadManager) {
  82471. this._gamepadManager = new BABYLON.GamepadManager(this);
  82472. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  82473. if (!component) {
  82474. component = new GamepadSystemSceneComponent(this);
  82475. this._addComponent(component);
  82476. }
  82477. }
  82478. return this._gamepadManager;
  82479. },
  82480. enumerable: true,
  82481. configurable: true
  82482. });
  82483. /**
  82484. * Adds a gamepad to the free camera inputs manager
  82485. */
  82486. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  82487. this.add(new BABYLON.FreeCameraGamepadInput());
  82488. return this;
  82489. };
  82490. /**
  82491. * Adds a gamepad to the arc rotate camera inputs manager
  82492. */
  82493. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  82494. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  82495. return this;
  82496. };
  82497. /**
  82498. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  82499. */
  82500. var GamepadSystemSceneComponent = /** @class */ (function () {
  82501. /**
  82502. * Creates a new instance of the component for the given scene
  82503. * @param scene Defines the scene to register the component in
  82504. */
  82505. function GamepadSystemSceneComponent(scene) {
  82506. /**
  82507. * The component name helpfull to identify the component in the list of scene components.
  82508. */
  82509. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  82510. this.scene = scene;
  82511. }
  82512. /**
  82513. * Registers the component in a given scene
  82514. */
  82515. GamepadSystemSceneComponent.prototype.register = function () {
  82516. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  82517. };
  82518. /**
  82519. * Rebuilds the elements related to this component in case of
  82520. * context lost for instance.
  82521. */
  82522. GamepadSystemSceneComponent.prototype.rebuild = function () {
  82523. // Nothing to do for gamepads
  82524. };
  82525. /**
  82526. * Disposes the component and the associated ressources
  82527. */
  82528. GamepadSystemSceneComponent.prototype.dispose = function () {
  82529. var gamepadManager = this.scene._gamepadManager;
  82530. if (gamepadManager) {
  82531. gamepadManager.dispose();
  82532. this.scene._gamepadManager = null;
  82533. }
  82534. };
  82535. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  82536. var gamepadManager = this.scene._gamepadManager;
  82537. if (gamepadManager && gamepadManager._isMonitoring) {
  82538. gamepadManager._checkGamepadsStatus();
  82539. }
  82540. };
  82541. return GamepadSystemSceneComponent;
  82542. }());
  82543. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  82544. })(BABYLON || (BABYLON = {}));
  82545. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  82546. var BABYLON;
  82547. (function (BABYLON) {
  82548. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  82549. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  82550. });
  82551. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  82552. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  82553. });
  82554. /**
  82555. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  82556. * an arc rotate version arcFollowCamera are available.
  82557. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82558. */
  82559. var FollowCamera = /** @class */ (function (_super) {
  82560. __extends(FollowCamera, _super);
  82561. /**
  82562. * Instantiates the follow camera.
  82563. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82564. * @param name Define the name of the camera in the scene
  82565. * @param position Define the position of the camera
  82566. * @param scene Define the scene the camera belong to
  82567. * @param lockedTarget Define the target of the camera
  82568. */
  82569. function FollowCamera(name, position, scene, lockedTarget) {
  82570. if (lockedTarget === void 0) { lockedTarget = null; }
  82571. var _this = _super.call(this, name, position, scene) || this;
  82572. /**
  82573. * Distance the follow camera should follow an object at
  82574. */
  82575. _this.radius = 12;
  82576. /**
  82577. * Define a rotation offset between the camera and the object it follows
  82578. */
  82579. _this.rotationOffset = 0;
  82580. /**
  82581. * Define a height offset between the camera and the object it follows.
  82582. * It can help following an object from the top (like a car chaing a plane)
  82583. */
  82584. _this.heightOffset = 4;
  82585. /**
  82586. * Define how fast the camera can accelerate to follow it s target.
  82587. */
  82588. _this.cameraAcceleration = 0.05;
  82589. /**
  82590. * Define the speed limit of the camera following an object.
  82591. */
  82592. _this.maxCameraSpeed = 20;
  82593. _this.lockedTarget = lockedTarget;
  82594. return _this;
  82595. }
  82596. FollowCamera.prototype._follow = function (cameraTarget) {
  82597. if (!cameraTarget) {
  82598. return;
  82599. }
  82600. var yRotation;
  82601. if (cameraTarget.rotationQuaternion) {
  82602. var rotMatrix = new BABYLON.Matrix();
  82603. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  82604. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  82605. }
  82606. else {
  82607. yRotation = cameraTarget.rotation.y;
  82608. }
  82609. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  82610. var targetPosition = cameraTarget.getAbsolutePosition();
  82611. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  82612. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  82613. var dx = targetX - this.position.x;
  82614. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  82615. var dz = (targetZ) - this.position.z;
  82616. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  82617. var vy = dy * this.cameraAcceleration;
  82618. var vz = dz * this.cameraAcceleration * 2;
  82619. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  82620. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82621. }
  82622. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  82623. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82624. }
  82625. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  82626. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82627. }
  82628. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  82629. this.setTarget(targetPosition);
  82630. };
  82631. /** @hidden */
  82632. FollowCamera.prototype._checkInputs = function () {
  82633. _super.prototype._checkInputs.call(this);
  82634. if (this.lockedTarget) {
  82635. this._follow(this.lockedTarget);
  82636. }
  82637. };
  82638. /**
  82639. * Gets the camera class name.
  82640. * @returns the class name
  82641. */
  82642. FollowCamera.prototype.getClassName = function () {
  82643. return "FollowCamera";
  82644. };
  82645. __decorate([
  82646. BABYLON.serialize()
  82647. ], FollowCamera.prototype, "radius", void 0);
  82648. __decorate([
  82649. BABYLON.serialize()
  82650. ], FollowCamera.prototype, "rotationOffset", void 0);
  82651. __decorate([
  82652. BABYLON.serialize()
  82653. ], FollowCamera.prototype, "heightOffset", void 0);
  82654. __decorate([
  82655. BABYLON.serialize()
  82656. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  82657. __decorate([
  82658. BABYLON.serialize()
  82659. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  82660. __decorate([
  82661. BABYLON.serializeAsMeshReference("lockedTargetId")
  82662. ], FollowCamera.prototype, "lockedTarget", void 0);
  82663. return FollowCamera;
  82664. }(BABYLON.TargetCamera));
  82665. BABYLON.FollowCamera = FollowCamera;
  82666. /**
  82667. * Arc Rotate version of the follow camera.
  82668. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  82669. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82670. */
  82671. var ArcFollowCamera = /** @class */ (function (_super) {
  82672. __extends(ArcFollowCamera, _super);
  82673. /**
  82674. * Instantiates a new ArcFollowCamera
  82675. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82676. * @param name Define the name of the camera
  82677. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  82678. * @param beta Define the rotation angle of the camera around the elevation axis
  82679. * @param radius Define the radius of the camera from its target point
  82680. * @param target Define the target of the camera
  82681. * @param scene Define the scene the camera belongs to
  82682. */
  82683. function ArcFollowCamera(name,
  82684. /** The longitudinal angle of the camera */
  82685. alpha,
  82686. /** The latitudinal angle of the camera */
  82687. beta,
  82688. /** The radius of the camera from its target */
  82689. radius,
  82690. /** Define the camera target (the messh it should follow) */
  82691. target, scene) {
  82692. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  82693. _this.alpha = alpha;
  82694. _this.beta = beta;
  82695. _this.radius = radius;
  82696. _this.target = target;
  82697. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  82698. _this._follow();
  82699. return _this;
  82700. }
  82701. ArcFollowCamera.prototype._follow = function () {
  82702. if (!this.target) {
  82703. return;
  82704. }
  82705. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  82706. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  82707. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  82708. var targetPosition = this.target.getAbsolutePosition();
  82709. this.position = targetPosition.add(this._cartesianCoordinates);
  82710. this.setTarget(targetPosition);
  82711. };
  82712. /** @hidden */
  82713. ArcFollowCamera.prototype._checkInputs = function () {
  82714. _super.prototype._checkInputs.call(this);
  82715. this._follow();
  82716. };
  82717. /**
  82718. * Returns the class name of the object.
  82719. * It is mostly used internally for serialization purposes.
  82720. */
  82721. ArcFollowCamera.prototype.getClassName = function () {
  82722. return "ArcFollowCamera";
  82723. };
  82724. return ArcFollowCamera;
  82725. }(BABYLON.TargetCamera));
  82726. BABYLON.ArcFollowCamera = ArcFollowCamera;
  82727. })(BABYLON || (BABYLON = {}));
  82728. //# sourceMappingURL=babylon.followCamera.js.map
  82729. var BABYLON;
  82730. (function (BABYLON) {
  82731. /**
  82732. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  82733. * which still works and will still be found in many Playgrounds.
  82734. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82735. */
  82736. var UniversalCamera = /** @class */ (function (_super) {
  82737. __extends(UniversalCamera, _super);
  82738. /**
  82739. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  82740. * which still works and will still be found in many Playgrounds.
  82741. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82742. * @param name Define the name of the camera in the scene
  82743. * @param position Define the start position of the camera in the scene
  82744. * @param scene Define the scene the camera belongs to
  82745. */
  82746. function UniversalCamera(name, position, scene) {
  82747. var _this = _super.call(this, name, position, scene) || this;
  82748. _this.inputs.addGamepad();
  82749. return _this;
  82750. }
  82751. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  82752. /**
  82753. * Defines the gamepad rotation sensiblity.
  82754. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82755. */
  82756. get: function () {
  82757. var gamepad = this.inputs.attached["gamepad"];
  82758. if (gamepad) {
  82759. return gamepad.gamepadAngularSensibility;
  82760. }
  82761. return 0;
  82762. },
  82763. set: function (value) {
  82764. var gamepad = this.inputs.attached["gamepad"];
  82765. if (gamepad) {
  82766. gamepad.gamepadAngularSensibility = value;
  82767. }
  82768. },
  82769. enumerable: true,
  82770. configurable: true
  82771. });
  82772. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  82773. /**
  82774. * Defines the gamepad move sensiblity.
  82775. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82776. */
  82777. get: function () {
  82778. var gamepad = this.inputs.attached["gamepad"];
  82779. if (gamepad) {
  82780. return gamepad.gamepadMoveSensibility;
  82781. }
  82782. return 0;
  82783. },
  82784. set: function (value) {
  82785. var gamepad = this.inputs.attached["gamepad"];
  82786. if (gamepad) {
  82787. gamepad.gamepadMoveSensibility = value;
  82788. }
  82789. },
  82790. enumerable: true,
  82791. configurable: true
  82792. });
  82793. /**
  82794. * Gets the current object class name.
  82795. * @return the class name
  82796. */
  82797. UniversalCamera.prototype.getClassName = function () {
  82798. return "UniversalCamera";
  82799. };
  82800. return UniversalCamera;
  82801. }(BABYLON.TouchCamera));
  82802. BABYLON.UniversalCamera = UniversalCamera;
  82803. })(BABYLON || (BABYLON = {}));
  82804. //# sourceMappingURL=babylon.universalCamera.js.map
  82805. var BABYLON;
  82806. (function (BABYLON) {
  82807. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  82808. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  82809. });
  82810. /**
  82811. * This represents a FPS type of camera. This is only here for back compat purpose.
  82812. * Please use the UniversalCamera instead as both are identical.
  82813. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82814. */
  82815. var GamepadCamera = /** @class */ (function (_super) {
  82816. __extends(GamepadCamera, _super);
  82817. /**
  82818. * Instantiates a new Gamepad Camera
  82819. * This represents a FPS type of camera. This is only here for back compat purpose.
  82820. * Please use the UniversalCamera instead as both are identical.
  82821. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82822. * @param name Define the name of the camera in the scene
  82823. * @param position Define the start position of the camera in the scene
  82824. * @param scene Define the scene the camera belongs to
  82825. */
  82826. function GamepadCamera(name, position, scene) {
  82827. return _super.call(this, name, position, scene) || this;
  82828. }
  82829. /**
  82830. * Gets the current object class name.
  82831. * @return the class name
  82832. */
  82833. GamepadCamera.prototype.getClassName = function () {
  82834. return "GamepadCamera";
  82835. };
  82836. return GamepadCamera;
  82837. }(BABYLON.UniversalCamera));
  82838. BABYLON.GamepadCamera = GamepadCamera;
  82839. })(BABYLON || (BABYLON = {}));
  82840. //# sourceMappingURL=babylon.gamepadCamera.js.map
  82841. var BABYLON;
  82842. (function (BABYLON) {
  82843. /**
  82844. * PostProcessRenderPipelineManager class
  82845. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82846. */
  82847. var PostProcessRenderPipelineManager = /** @class */ (function () {
  82848. /**
  82849. * Initializes a PostProcessRenderPipelineManager
  82850. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82851. */
  82852. function PostProcessRenderPipelineManager() {
  82853. this._renderPipelines = {};
  82854. }
  82855. /**
  82856. * Adds a pipeline to the manager
  82857. * @param renderPipeline The pipeline to add
  82858. */
  82859. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  82860. this._renderPipelines[renderPipeline._name] = renderPipeline;
  82861. };
  82862. /**
  82863. * Attaches a camera to the pipeline
  82864. * @param renderPipelineName The name of the pipeline to attach to
  82865. * @param cameras the camera to attach
  82866. * @param unique if the camera can be attached multiple times to the pipeline
  82867. */
  82868. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  82869. if (unique === void 0) { unique = false; }
  82870. var renderPipeline = this._renderPipelines[renderPipelineName];
  82871. if (!renderPipeline) {
  82872. return;
  82873. }
  82874. renderPipeline._attachCameras(cameras, unique);
  82875. };
  82876. /**
  82877. * Detaches a camera from the pipeline
  82878. * @param renderPipelineName The name of the pipeline to detach from
  82879. * @param cameras the camera to detach
  82880. */
  82881. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  82882. var renderPipeline = this._renderPipelines[renderPipelineName];
  82883. if (!renderPipeline) {
  82884. return;
  82885. }
  82886. renderPipeline._detachCameras(cameras);
  82887. };
  82888. /**
  82889. * Enables an effect by name on a pipeline
  82890. * @param renderPipelineName the name of the pipeline to enable the effect in
  82891. * @param renderEffectName the name of the effect to enable
  82892. * @param cameras the cameras that the effect should be enabled on
  82893. */
  82894. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82895. var renderPipeline = this._renderPipelines[renderPipelineName];
  82896. if (!renderPipeline) {
  82897. return;
  82898. }
  82899. renderPipeline._enableEffect(renderEffectName, cameras);
  82900. };
  82901. /**
  82902. * Disables an effect by name on a pipeline
  82903. * @param renderPipelineName the name of the pipeline to disable the effect in
  82904. * @param renderEffectName the name of the effect to disable
  82905. * @param cameras the cameras that the effect should be disabled on
  82906. */
  82907. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82908. var renderPipeline = this._renderPipelines[renderPipelineName];
  82909. if (!renderPipeline) {
  82910. return;
  82911. }
  82912. renderPipeline._disableEffect(renderEffectName, cameras);
  82913. };
  82914. /**
  82915. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  82916. */
  82917. PostProcessRenderPipelineManager.prototype.update = function () {
  82918. for (var renderPipelineName in this._renderPipelines) {
  82919. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82920. var pipeline = this._renderPipelines[renderPipelineName];
  82921. if (!pipeline.isSupported) {
  82922. pipeline.dispose();
  82923. delete this._renderPipelines[renderPipelineName];
  82924. }
  82925. else {
  82926. pipeline._update();
  82927. }
  82928. }
  82929. }
  82930. };
  82931. /** @hidden */
  82932. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  82933. for (var renderPipelineName in this._renderPipelines) {
  82934. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82935. var pipeline = this._renderPipelines[renderPipelineName];
  82936. pipeline._rebuild();
  82937. }
  82938. }
  82939. };
  82940. /**
  82941. * Disposes of the manager and pipelines
  82942. */
  82943. PostProcessRenderPipelineManager.prototype.dispose = function () {
  82944. for (var renderPipelineName in this._renderPipelines) {
  82945. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82946. var pipeline = this._renderPipelines[renderPipelineName];
  82947. pipeline.dispose();
  82948. }
  82949. }
  82950. };
  82951. return PostProcessRenderPipelineManager;
  82952. }());
  82953. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  82954. })(BABYLON || (BABYLON = {}));
  82955. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  82956. var BABYLON;
  82957. (function (BABYLON) {
  82958. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  82959. get: function () {
  82960. if (!this._postProcessRenderPipelineManager) {
  82961. // Register the G Buffer component to the scene.
  82962. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  82963. if (!component) {
  82964. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  82965. this._addComponent(component);
  82966. }
  82967. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  82968. }
  82969. return this._postProcessRenderPipelineManager;
  82970. },
  82971. enumerable: true,
  82972. configurable: true
  82973. });
  82974. /**
  82975. * Defines the Render Pipeline scene component responsible to rendering pipelines
  82976. */
  82977. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  82978. /**
  82979. * Creates a new instance of the component for the given scene
  82980. * @param scene Defines the scene to register the component in
  82981. */
  82982. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  82983. /**
  82984. * The component name helpfull to identify the component in the list of scene components.
  82985. */
  82986. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  82987. this.scene = scene;
  82988. }
  82989. /**
  82990. * Registers the component in a given scene
  82991. */
  82992. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  82993. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  82994. };
  82995. /**
  82996. * Rebuilds the elements related to this component in case of
  82997. * context lost for instance.
  82998. */
  82999. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  83000. if (this.scene._postProcessRenderPipelineManager) {
  83001. this.scene._postProcessRenderPipelineManager._rebuild();
  83002. }
  83003. };
  83004. /**
  83005. * Disposes the component and the associated ressources
  83006. */
  83007. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  83008. if (this.scene._postProcessRenderPipelineManager) {
  83009. this.scene._postProcessRenderPipelineManager.dispose();
  83010. }
  83011. };
  83012. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83013. if (this.scene._postProcessRenderPipelineManager) {
  83014. this.scene._postProcessRenderPipelineManager.update();
  83015. }
  83016. };
  83017. return PostProcessRenderPipelineManagerSceneComponent;
  83018. }());
  83019. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  83020. })(BABYLON || (BABYLON = {}));
  83021. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  83022. var BABYLON;
  83023. (function (BABYLON) {
  83024. /**
  83025. * This represents a set of one or more post processes in Babylon.
  83026. * A post process can be used to apply a shader to a texture after it is rendered.
  83027. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83028. */
  83029. var PostProcessRenderEffect = /** @class */ (function () {
  83030. /**
  83031. * Instantiates a post process render effect.
  83032. * A post process can be used to apply a shader to a texture after it is rendered.
  83033. * @param engine The engine the effect is tied to
  83034. * @param name The name of the effect
  83035. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  83036. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  83037. */
  83038. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  83039. this._name = name;
  83040. this._singleInstance = singleInstance || true;
  83041. this._getPostProcesses = getPostProcesses;
  83042. this._cameras = {};
  83043. this._indicesForCamera = {};
  83044. this._postProcesses = {};
  83045. }
  83046. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  83047. /**
  83048. * Checks if all the post processes in the effect are supported.
  83049. */
  83050. get: function () {
  83051. for (var index in this._postProcesses) {
  83052. if (this._postProcesses.hasOwnProperty(index)) {
  83053. var pps = this._postProcesses[index];
  83054. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  83055. if (!pps[ppIndex].isSupported) {
  83056. return false;
  83057. }
  83058. }
  83059. }
  83060. }
  83061. return true;
  83062. },
  83063. enumerable: true,
  83064. configurable: true
  83065. });
  83066. /**
  83067. * Updates the current state of the effect
  83068. * @hidden
  83069. */
  83070. PostProcessRenderEffect.prototype._update = function () {
  83071. };
  83072. /**
  83073. * Attaches the effect on cameras
  83074. * @param cameras The camera to attach to.
  83075. * @hidden
  83076. */
  83077. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  83078. var _this = this;
  83079. var cameraKey;
  83080. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83081. if (!cams) {
  83082. return;
  83083. }
  83084. for (var i = 0; i < cams.length; i++) {
  83085. var camera = cams[i];
  83086. var cameraName = camera.name;
  83087. if (this._singleInstance) {
  83088. cameraKey = 0;
  83089. }
  83090. else {
  83091. cameraKey = cameraName;
  83092. }
  83093. if (!this._postProcesses[cameraKey]) {
  83094. var postProcess = this._getPostProcesses();
  83095. if (postProcess) {
  83096. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  83097. }
  83098. }
  83099. if (!this._indicesForCamera[cameraName]) {
  83100. this._indicesForCamera[cameraName] = [];
  83101. }
  83102. this._postProcesses[cameraKey].forEach(function (postProcess) {
  83103. var index = camera.attachPostProcess(postProcess);
  83104. _this._indicesForCamera[cameraName].push(index);
  83105. });
  83106. if (!this._cameras[cameraName]) {
  83107. this._cameras[cameraName] = camera;
  83108. }
  83109. }
  83110. };
  83111. /**
  83112. * Detatches the effect on cameras
  83113. * @param cameras The camera to detatch from.
  83114. * @hidden
  83115. */
  83116. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  83117. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83118. if (!cams) {
  83119. return;
  83120. }
  83121. for (var i = 0; i < cams.length; i++) {
  83122. var camera = cams[i];
  83123. var cameraName = camera.name;
  83124. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83125. camera.detachPostProcess(postProcess);
  83126. });
  83127. if (this._cameras[cameraName]) {
  83128. //this._indicesForCamera.splice(index, 1);
  83129. this._cameras[cameraName] = null;
  83130. }
  83131. }
  83132. };
  83133. /**
  83134. * Enables the effect on given cameras
  83135. * @param cameras The camera to enable.
  83136. * @hidden
  83137. */
  83138. PostProcessRenderEffect.prototype._enable = function (cameras) {
  83139. var _this = this;
  83140. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83141. if (!cams) {
  83142. return;
  83143. }
  83144. for (var i = 0; i < cams.length; i++) {
  83145. var camera = cams[i];
  83146. var cameraName = camera.name;
  83147. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  83148. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  83149. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83150. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  83151. });
  83152. }
  83153. }
  83154. }
  83155. };
  83156. /**
  83157. * Disables the effect on the given cameras
  83158. * @param cameras The camera to disable.
  83159. * @hidden
  83160. */
  83161. PostProcessRenderEffect.prototype._disable = function (cameras) {
  83162. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83163. if (!cams) {
  83164. return;
  83165. }
  83166. for (var i = 0; i < cams.length; i++) {
  83167. var camera = cams[i];
  83168. var cameraName = camera.name;
  83169. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  83170. camera.detachPostProcess(postProcess);
  83171. });
  83172. }
  83173. };
  83174. /**
  83175. * Gets a list of the post processes contained in the effect.
  83176. * @param camera The camera to get the post processes on.
  83177. * @returns The list of the post processes in the effect.
  83178. */
  83179. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  83180. if (this._singleInstance) {
  83181. return this._postProcesses[0];
  83182. }
  83183. else {
  83184. if (!camera) {
  83185. return null;
  83186. }
  83187. return this._postProcesses[camera.name];
  83188. }
  83189. };
  83190. return PostProcessRenderEffect;
  83191. }());
  83192. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  83193. })(BABYLON || (BABYLON = {}));
  83194. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  83195. var BABYLON;
  83196. (function (BABYLON) {
  83197. /**
  83198. * PostProcessRenderPipeline
  83199. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  83200. */
  83201. var PostProcessRenderPipeline = /** @class */ (function () {
  83202. /**
  83203. * Initializes a PostProcessRenderPipeline
  83204. * @param engine engine to add the pipeline to
  83205. * @param name name of the pipeline
  83206. */
  83207. function PostProcessRenderPipeline(engine, name) {
  83208. this.engine = engine;
  83209. this._name = name;
  83210. this._renderEffects = {};
  83211. this._renderEffectsForIsolatedPass = new Array();
  83212. this._cameras = [];
  83213. }
  83214. /**
  83215. * "PostProcessRenderPipeline"
  83216. * @returns "PostProcessRenderPipeline"
  83217. */
  83218. PostProcessRenderPipeline.prototype.getClassName = function () {
  83219. return "PostProcessRenderPipeline";
  83220. };
  83221. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  83222. /**
  83223. * If all the render effects in the pipeline are support
  83224. */
  83225. get: function () {
  83226. for (var renderEffectName in this._renderEffects) {
  83227. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83228. if (!this._renderEffects[renderEffectName].isSupported) {
  83229. return false;
  83230. }
  83231. }
  83232. }
  83233. return true;
  83234. },
  83235. enumerable: true,
  83236. configurable: true
  83237. });
  83238. /**
  83239. * Adds an effect to the pipeline
  83240. * @param renderEffect the effect to add
  83241. */
  83242. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  83243. this._renderEffects[renderEffect._name] = renderEffect;
  83244. };
  83245. // private
  83246. /** @hidden */
  83247. PostProcessRenderPipeline.prototype._rebuild = function () {
  83248. };
  83249. /** @hidden */
  83250. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  83251. var renderEffects = this._renderEffects[renderEffectName];
  83252. if (!renderEffects) {
  83253. return;
  83254. }
  83255. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83256. };
  83257. /** @hidden */
  83258. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  83259. var renderEffects = this._renderEffects[renderEffectName];
  83260. if (!renderEffects) {
  83261. return;
  83262. }
  83263. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83264. };
  83265. /** @hidden */
  83266. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  83267. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83268. if (!cams) {
  83269. return;
  83270. }
  83271. var indicesToDelete = [];
  83272. var i;
  83273. for (i = 0; i < cams.length; i++) {
  83274. var camera = cams[i];
  83275. var cameraName = camera.name;
  83276. if (this._cameras.indexOf(camera) === -1) {
  83277. this._cameras[cameraName] = camera;
  83278. }
  83279. else if (unique) {
  83280. indicesToDelete.push(i);
  83281. }
  83282. }
  83283. for (i = 0; i < indicesToDelete.length; i++) {
  83284. cameras.splice(indicesToDelete[i], 1);
  83285. }
  83286. for (var renderEffectName in this._renderEffects) {
  83287. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83288. this._renderEffects[renderEffectName]._attachCameras(cams);
  83289. }
  83290. }
  83291. };
  83292. /** @hidden */
  83293. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  83294. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83295. if (!cams) {
  83296. return;
  83297. }
  83298. for (var renderEffectName in this._renderEffects) {
  83299. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83300. this._renderEffects[renderEffectName]._detachCameras(cams);
  83301. }
  83302. }
  83303. for (var i = 0; i < cams.length; i++) {
  83304. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  83305. }
  83306. };
  83307. /** @hidden */
  83308. PostProcessRenderPipeline.prototype._update = function () {
  83309. for (var renderEffectName in this._renderEffects) {
  83310. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83311. this._renderEffects[renderEffectName]._update();
  83312. }
  83313. }
  83314. for (var i = 0; i < this._cameras.length; i++) {
  83315. var cameraName = this._cameras[i].name;
  83316. if (this._renderEffectsForIsolatedPass[cameraName]) {
  83317. this._renderEffectsForIsolatedPass[cameraName]._update();
  83318. }
  83319. }
  83320. };
  83321. /** @hidden */
  83322. PostProcessRenderPipeline.prototype._reset = function () {
  83323. this._renderEffects = {};
  83324. this._renderEffectsForIsolatedPass = new Array();
  83325. };
  83326. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  83327. // 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)
  83328. var effectKeys = Object.keys(this._renderEffects);
  83329. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  83330. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  83331. if (postProcesses) {
  83332. postProcesses[0].samples = sampleCount;
  83333. return true;
  83334. }
  83335. }
  83336. return false;
  83337. };
  83338. /**
  83339. * Disposes of the pipeline
  83340. */
  83341. PostProcessRenderPipeline.prototype.dispose = function () {
  83342. // Must be implemented by children
  83343. };
  83344. __decorate([
  83345. BABYLON.serialize()
  83346. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  83347. return PostProcessRenderPipeline;
  83348. }());
  83349. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  83350. })(BABYLON || (BABYLON = {}));
  83351. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  83352. var BABYLON;
  83353. (function (BABYLON) {
  83354. /**
  83355. * This represents a depth renderer in Babylon.
  83356. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  83357. */
  83358. var DepthRenderer = /** @class */ (function () {
  83359. /**
  83360. * Instantiates a depth renderer
  83361. * @param scene The scene the renderer belongs to
  83362. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  83363. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  83364. */
  83365. function DepthRenderer(scene, type, camera) {
  83366. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  83367. if (camera === void 0) { camera = null; }
  83368. var _this = this;
  83369. /**
  83370. * Specifiess that the depth renderer will only be used within
  83371. * the camera it is created for.
  83372. * This can help forcing its rendering during the camera processing.
  83373. */
  83374. this.useOnlyInActiveCamera = false;
  83375. this._scene = scene;
  83376. // Register the G Buffer component to the scene.
  83377. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  83378. if (!component) {
  83379. component = new BABYLON.DepthRendererSceneComponent(scene);
  83380. scene._addComponent(component);
  83381. }
  83382. this._camera = camera;
  83383. var engine = scene.getEngine();
  83384. // Render target
  83385. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  83386. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83387. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83388. this._depthMap.refreshRate = 1;
  83389. this._depthMap.renderParticles = false;
  83390. this._depthMap.renderList = null;
  83391. // Camera to get depth map from to support multiple concurrent cameras
  83392. this._depthMap.activeCamera = this._camera;
  83393. this._depthMap.ignoreCameraViewport = true;
  83394. this._depthMap.useCameraPostProcesses = false;
  83395. // set default depth value to 1.0 (far away)
  83396. this._depthMap.onClearObservable.add(function (engine) {
  83397. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  83398. });
  83399. // Custom render function
  83400. var renderSubMesh = function (subMesh) {
  83401. var mesh = subMesh.getRenderingMesh();
  83402. var scene = _this._scene;
  83403. var engine = scene.getEngine();
  83404. var material = subMesh.getMaterial();
  83405. if (!material) {
  83406. return;
  83407. }
  83408. // Culling and reverse (right handed system)
  83409. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83410. // Managing instances
  83411. var batch = mesh._getInstancesRenderList(subMesh._id);
  83412. if (batch.mustReturn) {
  83413. return;
  83414. }
  83415. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83416. var camera = _this._camera || scene.activeCamera;
  83417. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  83418. engine.enableEffect(_this._effect);
  83419. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83420. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83421. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  83422. // Alpha test
  83423. if (material && material.needAlphaTesting()) {
  83424. var alphaTexture = material.getAlphaTestTexture();
  83425. if (alphaTexture) {
  83426. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83427. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83428. }
  83429. }
  83430. // Bones
  83431. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83432. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83433. }
  83434. // Draw
  83435. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83436. }
  83437. };
  83438. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83439. var index;
  83440. if (depthOnlySubMeshes.length) {
  83441. engine.setColorWrite(false);
  83442. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83443. renderSubMesh(depthOnlySubMeshes.data[index]);
  83444. }
  83445. engine.setColorWrite(true);
  83446. }
  83447. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83448. renderSubMesh(opaqueSubMeshes.data[index]);
  83449. }
  83450. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83451. renderSubMesh(alphaTestSubMeshes.data[index]);
  83452. }
  83453. };
  83454. }
  83455. /**
  83456. * Creates the depth rendering effect and checks if the effect is ready.
  83457. * @param subMesh The submesh to be used to render the depth map of
  83458. * @param useInstances If multiple world instances should be used
  83459. * @returns if the depth renderer is ready to render the depth map
  83460. */
  83461. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  83462. var material = subMesh.getMaterial();
  83463. if (material.disableDepthWrite) {
  83464. return false;
  83465. }
  83466. var defines = [];
  83467. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83468. var mesh = subMesh.getMesh();
  83469. // Alpha test
  83470. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  83471. defines.push("#define ALPHATEST");
  83472. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83473. attribs.push(BABYLON.VertexBuffer.UVKind);
  83474. defines.push("#define UV1");
  83475. }
  83476. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83477. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83478. defines.push("#define UV2");
  83479. }
  83480. }
  83481. // Bones
  83482. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83483. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83484. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83485. if (mesh.numBoneInfluencers > 4) {
  83486. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83487. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83488. }
  83489. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83490. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83491. }
  83492. else {
  83493. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83494. }
  83495. // Instances
  83496. if (useInstances) {
  83497. defines.push("#define INSTANCES");
  83498. attribs.push("world0");
  83499. attribs.push("world1");
  83500. attribs.push("world2");
  83501. attribs.push("world3");
  83502. }
  83503. // Get correct effect
  83504. var join = defines.join("\n");
  83505. if (this._cachedDefines !== join) {
  83506. this._cachedDefines = join;
  83507. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  83508. }
  83509. return this._effect.isReady();
  83510. };
  83511. /**
  83512. * Gets the texture which the depth map will be written to.
  83513. * @returns The depth map texture
  83514. */
  83515. DepthRenderer.prototype.getDepthMap = function () {
  83516. return this._depthMap;
  83517. };
  83518. /**
  83519. * Disposes of the depth renderer.
  83520. */
  83521. DepthRenderer.prototype.dispose = function () {
  83522. this._depthMap.dispose();
  83523. };
  83524. return DepthRenderer;
  83525. }());
  83526. BABYLON.DepthRenderer = DepthRenderer;
  83527. })(BABYLON || (BABYLON = {}));
  83528. //# sourceMappingURL=babylon.depthRenderer.js.map
  83529. var BABYLON;
  83530. (function (BABYLON) {
  83531. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  83532. camera = camera || this.activeCamera;
  83533. if (!camera) {
  83534. throw "No camera available to enable depth renderer";
  83535. }
  83536. if (!this._depthRenderer) {
  83537. this._depthRenderer = {};
  83538. }
  83539. if (!this._depthRenderer[camera.id]) {
  83540. var textureType = 0;
  83541. if (this.getEngine().getCaps().textureHalfFloatRender) {
  83542. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83543. }
  83544. else if (this.getEngine().getCaps().textureFloatRender) {
  83545. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83546. }
  83547. else {
  83548. throw "Depth renderer does not support int texture type";
  83549. }
  83550. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  83551. }
  83552. return this._depthRenderer[camera.id];
  83553. };
  83554. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  83555. camera = camera || this.activeCamera;
  83556. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  83557. return;
  83558. }
  83559. this._depthRenderer[camera.id].dispose();
  83560. delete this._depthRenderer[camera.id];
  83561. };
  83562. /**
  83563. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  83564. * in several rendering techniques.
  83565. */
  83566. var DepthRendererSceneComponent = /** @class */ (function () {
  83567. /**
  83568. * Creates a new instance of the component for the given scene
  83569. * @param scene Defines the scene to register the component in
  83570. */
  83571. function DepthRendererSceneComponent(scene) {
  83572. /**
  83573. * The component name helpfull to identify the component in the list of scene components.
  83574. */
  83575. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  83576. this.scene = scene;
  83577. }
  83578. /**
  83579. * Registers the component in a given scene
  83580. */
  83581. DepthRendererSceneComponent.prototype.register = function () {
  83582. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  83583. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  83584. };
  83585. /**
  83586. * Rebuilds the elements related to this component in case of
  83587. * context lost for instance.
  83588. */
  83589. DepthRendererSceneComponent.prototype.rebuild = function () {
  83590. // Nothing to do for this component
  83591. };
  83592. /**
  83593. * Disposes the component and the associated ressources
  83594. */
  83595. DepthRendererSceneComponent.prototype.dispose = function () {
  83596. for (var key in this.scene._depthRenderer) {
  83597. this.scene._depthRenderer[key].dispose();
  83598. }
  83599. };
  83600. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83601. if (this.scene._depthRenderer) {
  83602. for (var key in this.scene._depthRenderer) {
  83603. var depthRenderer = this.scene._depthRenderer[key];
  83604. if (!depthRenderer.useOnlyInActiveCamera) {
  83605. renderTargets.push(depthRenderer.getDepthMap());
  83606. }
  83607. }
  83608. }
  83609. };
  83610. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  83611. if (this.scene._depthRenderer) {
  83612. for (var key in this.scene._depthRenderer) {
  83613. var depthRenderer = this.scene._depthRenderer[key];
  83614. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  83615. renderTargets.push(depthRenderer.getDepthMap());
  83616. }
  83617. }
  83618. }
  83619. };
  83620. return DepthRendererSceneComponent;
  83621. }());
  83622. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  83623. })(BABYLON || (BABYLON = {}));
  83624. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  83625. var BABYLON;
  83626. (function (BABYLON) {
  83627. /**
  83628. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  83629. */
  83630. var GeometryBufferRenderer = /** @class */ (function () {
  83631. /**
  83632. * Creates a new G Buffer for the scene
  83633. * @param scene The scene the buffer belongs to
  83634. * @param ratio How big is the buffer related to the main canvas.
  83635. */
  83636. function GeometryBufferRenderer(scene, ratio) {
  83637. if (ratio === void 0) { ratio = 1; }
  83638. this._enablePosition = false;
  83639. this._scene = scene;
  83640. this._ratio = ratio;
  83641. // Register the G Buffer component to the scene.
  83642. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  83643. if (!component) {
  83644. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  83645. scene._addComponent(component);
  83646. }
  83647. // Render target
  83648. this._createRenderTargets();
  83649. }
  83650. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  83651. /**
  83652. * Set the render list (meshes to be rendered) used in the G buffer.
  83653. */
  83654. set: function (meshes) {
  83655. this._multiRenderTarget.renderList = meshes;
  83656. },
  83657. enumerable: true,
  83658. configurable: true
  83659. });
  83660. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  83661. /**
  83662. * Gets wether or not G buffer are supported by the running hardware.
  83663. * This requires draw buffer supports
  83664. */
  83665. get: function () {
  83666. return this._multiRenderTarget.isSupported;
  83667. },
  83668. enumerable: true,
  83669. configurable: true
  83670. });
  83671. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  83672. /**
  83673. * Gets wether or not position are enabled for the G buffer.
  83674. */
  83675. get: function () {
  83676. return this._enablePosition;
  83677. },
  83678. /**
  83679. * Sets wether or not position are enabled for the G buffer.
  83680. */
  83681. set: function (enable) {
  83682. this._enablePosition = enable;
  83683. this.dispose();
  83684. this._createRenderTargets();
  83685. },
  83686. enumerable: true,
  83687. configurable: true
  83688. });
  83689. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  83690. /**
  83691. * Gets the scene associated with the buffer.
  83692. */
  83693. get: function () {
  83694. return this._scene;
  83695. },
  83696. enumerable: true,
  83697. configurable: true
  83698. });
  83699. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  83700. /**
  83701. * Gets the ratio used by the buffer during its creation.
  83702. * How big is the buffer related to the main canvas.
  83703. */
  83704. get: function () {
  83705. return this._ratio;
  83706. },
  83707. enumerable: true,
  83708. configurable: true
  83709. });
  83710. /**
  83711. * Checks wether everything is ready to render a submesh to the G buffer.
  83712. * @param subMesh the submesh to check readiness for
  83713. * @param useInstances is the mesh drawn using instance or not
  83714. * @returns true if ready otherwise false
  83715. */
  83716. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  83717. var material = subMesh.getMaterial();
  83718. if (material && material.disableDepthWrite) {
  83719. return false;
  83720. }
  83721. var defines = [];
  83722. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83723. var mesh = subMesh.getMesh();
  83724. // Alpha test
  83725. if (material && material.needAlphaTesting()) {
  83726. defines.push("#define ALPHATEST");
  83727. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83728. attribs.push(BABYLON.VertexBuffer.UVKind);
  83729. defines.push("#define UV1");
  83730. }
  83731. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83732. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83733. defines.push("#define UV2");
  83734. }
  83735. }
  83736. // Buffers
  83737. if (this._enablePosition) {
  83738. defines.push("#define POSITION");
  83739. }
  83740. // Bones
  83741. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83742. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83743. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83744. if (mesh.numBoneInfluencers > 4) {
  83745. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83746. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83747. }
  83748. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83749. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83750. }
  83751. else {
  83752. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83753. }
  83754. // Instances
  83755. if (useInstances) {
  83756. defines.push("#define INSTANCES");
  83757. attribs.push("world0");
  83758. attribs.push("world1");
  83759. attribs.push("world2");
  83760. attribs.push("world3");
  83761. }
  83762. // Get correct effect
  83763. var join = defines.join("\n");
  83764. if (this._cachedDefines !== join) {
  83765. this._cachedDefines = join;
  83766. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  83767. }
  83768. return this._effect.isReady();
  83769. };
  83770. /**
  83771. * Gets the current underlying G Buffer.
  83772. * @returns the buffer
  83773. */
  83774. GeometryBufferRenderer.prototype.getGBuffer = function () {
  83775. return this._multiRenderTarget;
  83776. };
  83777. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  83778. /**
  83779. * Gets the number of samples used to render the buffer (anti aliasing).
  83780. */
  83781. get: function () {
  83782. return this._multiRenderTarget.samples;
  83783. },
  83784. /**
  83785. * Sets the number of samples used to render the buffer (anti aliasing).
  83786. */
  83787. set: function (value) {
  83788. this._multiRenderTarget.samples = value;
  83789. },
  83790. enumerable: true,
  83791. configurable: true
  83792. });
  83793. /**
  83794. * Disposes the renderer and frees up associated resources.
  83795. */
  83796. GeometryBufferRenderer.prototype.dispose = function () {
  83797. this.getGBuffer().dispose();
  83798. };
  83799. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  83800. var _this = this;
  83801. var engine = this._scene.getEngine();
  83802. var count = this._enablePosition ? 3 : 2;
  83803. 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 });
  83804. if (!this.isSupported) {
  83805. return;
  83806. }
  83807. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83808. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83809. this._multiRenderTarget.refreshRate = 1;
  83810. this._multiRenderTarget.renderParticles = false;
  83811. this._multiRenderTarget.renderList = null;
  83812. // set default depth value to 1.0 (far away)
  83813. this._multiRenderTarget.onClearObservable.add(function (engine) {
  83814. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  83815. });
  83816. // Custom render function
  83817. var renderSubMesh = function (subMesh) {
  83818. var mesh = subMesh.getRenderingMesh();
  83819. var scene = _this._scene;
  83820. var engine = scene.getEngine();
  83821. var material = subMesh.getMaterial();
  83822. if (!material) {
  83823. return;
  83824. }
  83825. // Culling
  83826. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83827. // Managing instances
  83828. var batch = mesh._getInstancesRenderList(subMesh._id);
  83829. if (batch.mustReturn) {
  83830. return;
  83831. }
  83832. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83833. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  83834. engine.enableEffect(_this._effect);
  83835. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83836. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83837. _this._effect.setMatrix("view", scene.getViewMatrix());
  83838. // Alpha test
  83839. if (material && material.needAlphaTesting()) {
  83840. var alphaTexture = material.getAlphaTestTexture();
  83841. if (alphaTexture) {
  83842. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83843. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83844. }
  83845. }
  83846. // Bones
  83847. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83848. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83849. }
  83850. // Draw
  83851. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83852. }
  83853. };
  83854. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83855. var index;
  83856. if (depthOnlySubMeshes.length) {
  83857. engine.setColorWrite(false);
  83858. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83859. renderSubMesh(depthOnlySubMeshes.data[index]);
  83860. }
  83861. engine.setColorWrite(true);
  83862. }
  83863. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83864. renderSubMesh(opaqueSubMeshes.data[index]);
  83865. }
  83866. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83867. renderSubMesh(alphaTestSubMeshes.data[index]);
  83868. }
  83869. };
  83870. };
  83871. return GeometryBufferRenderer;
  83872. }());
  83873. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  83874. })(BABYLON || (BABYLON = {}));
  83875. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  83876. var BABYLON;
  83877. (function (BABYLON) {
  83878. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  83879. get: function () {
  83880. this._geometryBufferRenderer;
  83881. },
  83882. set: function (value) {
  83883. if (value && value.isSupported) {
  83884. this._geometryBufferRenderer = value;
  83885. }
  83886. },
  83887. enumerable: true,
  83888. configurable: true
  83889. });
  83890. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  83891. if (ratio === void 0) { ratio = 1; }
  83892. if (this._geometryBufferRenderer) {
  83893. return this._geometryBufferRenderer;
  83894. }
  83895. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  83896. if (!this._geometryBufferRenderer.isSupported) {
  83897. this._geometryBufferRenderer = null;
  83898. }
  83899. return this._geometryBufferRenderer;
  83900. };
  83901. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  83902. if (!this._geometryBufferRenderer) {
  83903. return;
  83904. }
  83905. this._geometryBufferRenderer.dispose();
  83906. this._geometryBufferRenderer = null;
  83907. };
  83908. /**
  83909. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  83910. * in several rendering techniques.
  83911. */
  83912. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  83913. /**
  83914. * Creates a new instance of the component for the given scene
  83915. * @param scene Defines the scene to register the component in
  83916. */
  83917. function GeometryBufferRendererSceneComponent(scene) {
  83918. /**
  83919. * The component name helpful to identify the component in the list of scene components.
  83920. */
  83921. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  83922. this.scene = scene;
  83923. }
  83924. /**
  83925. * Registers the component in a given scene
  83926. */
  83927. GeometryBufferRendererSceneComponent.prototype.register = function () {
  83928. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  83929. };
  83930. /**
  83931. * Rebuilds the elements related to this component in case of
  83932. * context lost for instance.
  83933. */
  83934. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  83935. // Nothing to do for this component
  83936. };
  83937. /**
  83938. * Disposes the component and the associated ressources
  83939. */
  83940. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  83941. // Nothing to do for this component
  83942. };
  83943. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83944. if (this.scene._geometryBufferRenderer) {
  83945. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  83946. }
  83947. };
  83948. return GeometryBufferRendererSceneComponent;
  83949. }());
  83950. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  83951. })(BABYLON || (BABYLON = {}));
  83952. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  83953. var BABYLON;
  83954. (function (BABYLON) {
  83955. /**
  83956. * Render pipeline to produce ssao effect
  83957. */
  83958. var SSAORenderingPipeline = /** @class */ (function (_super) {
  83959. __extends(SSAORenderingPipeline, _super);
  83960. /**
  83961. * @constructor
  83962. * @param name - The rendering pipeline name
  83963. * @param scene - The scene linked to this pipeline
  83964. * @param 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 }
  83965. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  83966. */
  83967. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  83968. var _this = _super.call(this, scene.getEngine(), name) || this;
  83969. // Members
  83970. /**
  83971. * @ignore
  83972. * The PassPostProcess id in the pipeline that contains the original scene color
  83973. */
  83974. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83975. /**
  83976. * @ignore
  83977. * The SSAO PostProcess id in the pipeline
  83978. */
  83979. _this.SSAORenderEffect = "SSAORenderEffect";
  83980. /**
  83981. * @ignore
  83982. * The horizontal blur PostProcess id in the pipeline
  83983. */
  83984. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83985. /**
  83986. * @ignore
  83987. * The vertical blur PostProcess id in the pipeline
  83988. */
  83989. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83990. /**
  83991. * @ignore
  83992. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83993. */
  83994. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83995. /**
  83996. * The output strength of the SSAO post-process. Default value is 1.0.
  83997. */
  83998. _this.totalStrength = 1.0;
  83999. /**
  84000. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  84001. */
  84002. _this.radius = 0.0001;
  84003. /**
  84004. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  84005. * Must not be equal to fallOff and superior to fallOff.
  84006. * Default value is 0.975
  84007. */
  84008. _this.area = 0.0075;
  84009. /**
  84010. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  84011. * Must not be equal to area and inferior to area.
  84012. * Default value is 0.0
  84013. */
  84014. _this.fallOff = 0.000001;
  84015. /**
  84016. * The base color of the SSAO post-process
  84017. * The final result is "base + ssao" between [0, 1]
  84018. */
  84019. _this.base = 0.5;
  84020. _this._firstUpdate = true;
  84021. _this._scene = scene;
  84022. // Set up assets
  84023. _this._createRandomTexture();
  84024. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84025. var ssaoRatio = ratio.ssaoRatio || ratio;
  84026. var combineRatio = ratio.combineRatio || ratio;
  84027. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  84028. _this._createSSAOPostProcess(ssaoRatio);
  84029. _this._createBlurPostProcess(ssaoRatio);
  84030. _this._createSSAOCombinePostProcess(combineRatio);
  84031. // Set up pipeline
  84032. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  84033. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84034. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84035. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84036. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84037. // Finish
  84038. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84039. if (cameras) {
  84040. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84041. }
  84042. return _this;
  84043. }
  84044. // Public Methods
  84045. /**
  84046. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84047. */
  84048. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84049. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84050. for (var i = 0; i < this._scene.cameras.length; i++) {
  84051. var camera = this._scene.cameras[i];
  84052. this._originalColorPostProcess.dispose(camera);
  84053. this._ssaoPostProcess.dispose(camera);
  84054. this._blurHPostProcess.dispose(camera);
  84055. this._blurVPostProcess.dispose(camera);
  84056. this._ssaoCombinePostProcess.dispose(camera);
  84057. }
  84058. this._randomTexture.dispose();
  84059. if (disableDepthRender) {
  84060. this._scene.disableDepthRenderer();
  84061. }
  84062. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84063. _super.prototype.dispose.call(this);
  84064. };
  84065. // Private Methods
  84066. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  84067. var _this = this;
  84068. var size = 16;
  84069. 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);
  84070. 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);
  84071. this._blurHPostProcess.onActivateObservable.add(function () {
  84072. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  84073. _this._blurHPostProcess.kernel = size * dw;
  84074. });
  84075. this._blurVPostProcess.onActivateObservable.add(function () {
  84076. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  84077. _this._blurVPostProcess.kernel = size * dw;
  84078. });
  84079. };
  84080. /** @hidden */
  84081. SSAORenderingPipeline.prototype._rebuild = function () {
  84082. this._firstUpdate = true;
  84083. _super.prototype._rebuild.call(this);
  84084. };
  84085. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84086. var _this = this;
  84087. var numSamples = 16;
  84088. var sampleSphere = [
  84089. 0.5381, 0.1856, -0.4319,
  84090. 0.1379, 0.2486, 0.4430,
  84091. 0.3371, 0.5679, -0.0057,
  84092. -0.6999, -0.0451, -0.0019,
  84093. 0.0689, -0.1598, -0.8547,
  84094. 0.0560, 0.0069, -0.1843,
  84095. -0.0146, 0.1402, 0.0762,
  84096. 0.0100, -0.1924, -0.0344,
  84097. -0.3577, -0.5301, -0.4358,
  84098. -0.3169, 0.1063, 0.0158,
  84099. 0.0103, -0.5869, 0.0046,
  84100. -0.0897, -0.4940, 0.3287,
  84101. 0.7119, -0.0154, -0.0918,
  84102. -0.0533, 0.0596, -0.5411,
  84103. 0.0352, -0.0631, 0.5460,
  84104. -0.4776, 0.2847, -0.0271
  84105. ];
  84106. var samplesFactor = 1.0 / numSamples;
  84107. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  84108. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84109. "area", "fallOff", "base", "range", "viewport"
  84110. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84111. this._ssaoPostProcess.onApply = function (effect) {
  84112. if (_this._firstUpdate) {
  84113. effect.setArray3("sampleSphere", sampleSphere);
  84114. effect.setFloat("samplesFactor", samplesFactor);
  84115. effect.setFloat("randTextureTiles", 4.0);
  84116. }
  84117. effect.setFloat("totalStrength", _this.totalStrength);
  84118. effect.setFloat("radius", _this.radius);
  84119. effect.setFloat("area", _this.area);
  84120. effect.setFloat("fallOff", _this.fallOff);
  84121. effect.setFloat("base", _this.base);
  84122. effect.setTexture("textureSampler", _this._depthTexture);
  84123. effect.setTexture("randomSampler", _this._randomTexture);
  84124. };
  84125. };
  84126. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84127. var _this = this;
  84128. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84129. this._ssaoCombinePostProcess.onApply = function (effect) {
  84130. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  84131. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84132. };
  84133. };
  84134. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  84135. var size = 512;
  84136. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84137. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84138. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84139. var context = this._randomTexture.getContext();
  84140. var rand = function (min, max) {
  84141. return Math.random() * (max - min) + min;
  84142. };
  84143. var randVector = BABYLON.Vector3.Zero();
  84144. for (var x = 0; x < size; x++) {
  84145. for (var y = 0; y < size; y++) {
  84146. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  84147. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  84148. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  84149. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84150. context.fillRect(x, y, 1, 1);
  84151. }
  84152. }
  84153. this._randomTexture.update(false);
  84154. };
  84155. __decorate([
  84156. BABYLON.serialize()
  84157. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  84158. __decorate([
  84159. BABYLON.serialize()
  84160. ], SSAORenderingPipeline.prototype, "radius", void 0);
  84161. __decorate([
  84162. BABYLON.serialize()
  84163. ], SSAORenderingPipeline.prototype, "area", void 0);
  84164. __decorate([
  84165. BABYLON.serialize()
  84166. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  84167. __decorate([
  84168. BABYLON.serialize()
  84169. ], SSAORenderingPipeline.prototype, "base", void 0);
  84170. return SSAORenderingPipeline;
  84171. }(BABYLON.PostProcessRenderPipeline));
  84172. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  84173. })(BABYLON || (BABYLON = {}));
  84174. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  84175. var BABYLON;
  84176. (function (BABYLON) {
  84177. /**
  84178. * Render pipeline to produce ssao effect
  84179. */
  84180. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  84181. __extends(SSAO2RenderingPipeline, _super);
  84182. /**
  84183. * @constructor
  84184. * @param name The rendering pipeline name
  84185. * @param scene The scene linked to this pipeline
  84186. * @param 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 }
  84187. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84188. */
  84189. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  84190. var _this = _super.call(this, scene.getEngine(), name) || this;
  84191. // Members
  84192. /**
  84193. * @ignore
  84194. * The PassPostProcess id in the pipeline that contains the original scene color
  84195. */
  84196. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  84197. /**
  84198. * @ignore
  84199. * The SSAO PostProcess id in the pipeline
  84200. */
  84201. _this.SSAORenderEffect = "SSAORenderEffect";
  84202. /**
  84203. * @ignore
  84204. * The horizontal blur PostProcess id in the pipeline
  84205. */
  84206. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  84207. /**
  84208. * @ignore
  84209. * The vertical blur PostProcess id in the pipeline
  84210. */
  84211. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  84212. /**
  84213. * @ignore
  84214. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  84215. */
  84216. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  84217. /**
  84218. * The output strength of the SSAO post-process. Default value is 1.0.
  84219. */
  84220. _this.totalStrength = 1.0;
  84221. /**
  84222. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  84223. */
  84224. _this.maxZ = 100.0;
  84225. /**
  84226. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  84227. */
  84228. _this.minZAspect = 0.2;
  84229. _this._samples = 8;
  84230. _this._textureSamples = 1;
  84231. _this._expensiveBlur = true;
  84232. /**
  84233. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  84234. */
  84235. _this.radius = 2.0;
  84236. /**
  84237. * The base color of the SSAO post-process
  84238. * The final result is "base + ssao" between [0, 1]
  84239. */
  84240. _this.base = 0;
  84241. _this._firstUpdate = true;
  84242. _this._bits = new Uint32Array(1);
  84243. _this._scene = scene;
  84244. _this._ratio = ratio;
  84245. if (!_this.isSupported) {
  84246. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  84247. return _this;
  84248. }
  84249. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  84250. var blurRatio = _this._ratio.blurRatio || ratio;
  84251. // Set up assets
  84252. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  84253. _this._createRandomTexture();
  84254. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  84255. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  84256. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  84257. _this._originalColorPostProcess.samples = _this.textureSamples;
  84258. _this._createSSAOPostProcess(1.0);
  84259. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  84260. _this._createSSAOCombinePostProcess(blurRatio);
  84261. // Set up pipeline
  84262. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  84263. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84264. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84265. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84266. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84267. // Finish
  84268. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84269. if (cameras) {
  84270. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84271. }
  84272. return _this;
  84273. }
  84274. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  84275. get: function () {
  84276. return this._samples;
  84277. },
  84278. /**
  84279. * Number of samples used for the SSAO calculations. Default value is 8
  84280. */
  84281. set: function (n) {
  84282. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  84283. this._samples = n;
  84284. this._sampleSphere = this._generateHemisphere();
  84285. this._firstUpdate = true;
  84286. },
  84287. enumerable: true,
  84288. configurable: true
  84289. });
  84290. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  84291. get: function () {
  84292. return this._textureSamples;
  84293. },
  84294. /**
  84295. * Number of samples to use for antialiasing
  84296. */
  84297. set: function (n) {
  84298. this._textureSamples = n;
  84299. this._originalColorPostProcess.samples = n;
  84300. this._blurHPostProcess.samples = n;
  84301. this._blurVPostProcess.samples = n;
  84302. this._ssaoPostProcess.samples = n;
  84303. this._ssaoCombinePostProcess.samples = n;
  84304. },
  84305. enumerable: true,
  84306. configurable: true
  84307. });
  84308. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  84309. get: function () {
  84310. return this._expensiveBlur;
  84311. },
  84312. /**
  84313. * If bilateral blur should be used
  84314. */
  84315. set: function (b) {
  84316. 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"]);
  84317. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  84318. this._expensiveBlur = b;
  84319. this._firstUpdate = true;
  84320. },
  84321. enumerable: true,
  84322. configurable: true
  84323. });
  84324. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  84325. /**
  84326. * Support test.
  84327. */
  84328. get: function () {
  84329. var engine = BABYLON.Engine.LastCreatedEngine;
  84330. if (!engine) {
  84331. return false;
  84332. }
  84333. return engine.getCaps().drawBuffersExtension;
  84334. },
  84335. enumerable: true,
  84336. configurable: true
  84337. });
  84338. // Public Methods
  84339. /**
  84340. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84341. */
  84342. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  84343. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  84344. for (var i = 0; i < this._scene.cameras.length; i++) {
  84345. var camera = this._scene.cameras[i];
  84346. this._originalColorPostProcess.dispose(camera);
  84347. this._ssaoPostProcess.dispose(camera);
  84348. this._blurHPostProcess.dispose(camera);
  84349. this._blurVPostProcess.dispose(camera);
  84350. this._ssaoCombinePostProcess.dispose(camera);
  84351. }
  84352. this._randomTexture.dispose();
  84353. if (disableGeometryBufferRenderer) {
  84354. this._scene.disableGeometryBufferRenderer();
  84355. }
  84356. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84357. _super.prototype.dispose.call(this);
  84358. };
  84359. // Private Methods
  84360. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  84361. var _this = this;
  84362. this._samplerOffsets = [];
  84363. var expensive = this.expensiveBlur;
  84364. for (var i = -8; i < 8; i++) {
  84365. this._samplerOffsets.push(i * 2 + 0.5);
  84366. }
  84367. 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");
  84368. this._blurHPostProcess.onApply = function (effect) {
  84369. if (!_this._scene.activeCamera) {
  84370. return;
  84371. }
  84372. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  84373. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84374. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84375. effect.setFloat("radius", _this.radius);
  84376. effect.setTexture("depthSampler", _this._depthTexture);
  84377. if (_this._firstUpdate) {
  84378. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84379. }
  84380. };
  84381. 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");
  84382. this._blurVPostProcess.onApply = function (effect) {
  84383. if (!_this._scene.activeCamera) {
  84384. return;
  84385. }
  84386. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  84387. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84388. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84389. effect.setFloat("radius", _this.radius);
  84390. effect.setTexture("depthSampler", _this._depthTexture);
  84391. if (_this._firstUpdate) {
  84392. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84393. _this._firstUpdate = false;
  84394. }
  84395. };
  84396. this._blurHPostProcess.samples = this.textureSamples;
  84397. this._blurVPostProcess.samples = this.textureSamples;
  84398. };
  84399. /** @hidden */
  84400. SSAO2RenderingPipeline.prototype._rebuild = function () {
  84401. this._firstUpdate = true;
  84402. _super.prototype._rebuild.call(this);
  84403. };
  84404. //Van der Corput radical inverse
  84405. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  84406. this._bits[0] = i;
  84407. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  84408. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  84409. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  84410. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  84411. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  84412. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  84413. };
  84414. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  84415. return [i / n, this._radicalInverse_VdC(i)];
  84416. };
  84417. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  84418. var phi = v * 2.0 * Math.PI;
  84419. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  84420. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  84421. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  84422. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  84423. };
  84424. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  84425. var numSamples = this.samples;
  84426. var result = [];
  84427. var vector;
  84428. var i = 0;
  84429. while (i < numSamples) {
  84430. if (numSamples < 16) {
  84431. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  84432. }
  84433. else {
  84434. var rand = this._hammersley(i, numSamples);
  84435. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  84436. }
  84437. result.push(vector.x, vector.y, vector.z);
  84438. i++;
  84439. }
  84440. return result;
  84441. };
  84442. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84443. var _this = this;
  84444. var numSamples = this.samples;
  84445. this._sampleSphere = this._generateHemisphere();
  84446. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  84447. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84448. "base", "range", "projection", "near", "far", "texelSize",
  84449. "xViewport", "yViewport", "maxZ", "minZAspect"
  84450. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84451. this._ssaoPostProcess.onApply = function (effect) {
  84452. if (_this._firstUpdate) {
  84453. effect.setArray3("sampleSphere", _this._sampleSphere);
  84454. effect.setFloat("randTextureTiles", 32.0);
  84455. }
  84456. if (!_this._scene.activeCamera) {
  84457. return;
  84458. }
  84459. effect.setFloat("samplesFactor", 1 / _this.samples);
  84460. effect.setFloat("totalStrength", _this.totalStrength);
  84461. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  84462. effect.setFloat("radius", _this.radius);
  84463. effect.setFloat("maxZ", _this.maxZ);
  84464. effect.setFloat("minZAspect", _this.minZAspect);
  84465. effect.setFloat("base", _this.base);
  84466. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84467. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84468. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  84469. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  84470. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  84471. effect.setTexture("textureSampler", _this._depthTexture);
  84472. effect.setTexture("normalSampler", _this._normalTexture);
  84473. effect.setTexture("randomSampler", _this._randomTexture);
  84474. };
  84475. this._ssaoPostProcess.samples = this.textureSamples;
  84476. };
  84477. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84478. var _this = this;
  84479. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84480. this._ssaoCombinePostProcess.onApply = function (effect) {
  84481. var viewport = _this._scene.activeCamera.viewport;
  84482. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  84483. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84484. };
  84485. this._ssaoCombinePostProcess.samples = this.textureSamples;
  84486. };
  84487. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  84488. var size = 128;
  84489. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84490. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84491. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84492. var context = this._randomTexture.getContext();
  84493. var rand = function (min, max) {
  84494. return Math.random() * (max - min) + min;
  84495. };
  84496. var randVector = BABYLON.Vector3.Zero();
  84497. for (var x = 0; x < size; x++) {
  84498. for (var y = 0; y < size; y++) {
  84499. randVector.x = rand(0.0, 1.0);
  84500. randVector.y = rand(0.0, 1.0);
  84501. randVector.z = 0.0;
  84502. randVector.normalize();
  84503. randVector.scaleInPlace(255);
  84504. randVector.x = Math.floor(randVector.x);
  84505. randVector.y = Math.floor(randVector.y);
  84506. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84507. context.fillRect(x, y, 1, 1);
  84508. }
  84509. }
  84510. this._randomTexture.update(false);
  84511. };
  84512. /**
  84513. * Serialize the rendering pipeline (Used when exporting)
  84514. * @returns the serialized object
  84515. */
  84516. SSAO2RenderingPipeline.prototype.serialize = function () {
  84517. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84518. serializationObject.customType = "SSAO2RenderingPipeline";
  84519. return serializationObject;
  84520. };
  84521. /**
  84522. * Parse the serialized pipeline
  84523. * @param source Source pipeline.
  84524. * @param scene The scene to load the pipeline to.
  84525. * @param rootUrl The URL of the serialized pipeline.
  84526. * @returns An instantiated pipeline from the serialized object.
  84527. */
  84528. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  84529. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84530. };
  84531. __decorate([
  84532. BABYLON.serialize()
  84533. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  84534. __decorate([
  84535. BABYLON.serialize()
  84536. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  84537. __decorate([
  84538. BABYLON.serialize()
  84539. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  84540. __decorate([
  84541. BABYLON.serialize("samples")
  84542. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  84543. __decorate([
  84544. BABYLON.serialize("textureSamples")
  84545. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  84546. __decorate([
  84547. BABYLON.serialize()
  84548. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  84549. __decorate([
  84550. BABYLON.serialize("expensiveBlur")
  84551. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  84552. __decorate([
  84553. BABYLON.serialize()
  84554. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  84555. __decorate([
  84556. BABYLON.serialize()
  84557. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  84558. return SSAO2RenderingPipeline;
  84559. }(BABYLON.PostProcessRenderPipeline));
  84560. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  84561. })(BABYLON || (BABYLON = {}));
  84562. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  84563. var BABYLON;
  84564. (function (BABYLON) {
  84565. /**
  84566. * BABYLON.JS Chromatic Aberration GLSL Shader
  84567. * Author: Olivier Guyot
  84568. * Separates very slightly R, G and B colors on the edges of the screen
  84569. * Inspired by Francois Tarlier & Martins Upitis
  84570. */
  84571. var LensRenderingPipeline = /** @class */ (function (_super) {
  84572. __extends(LensRenderingPipeline, _super);
  84573. /**
  84574. * @constructor
  84575. *
  84576. * Effect parameters are as follow:
  84577. * {
  84578. * chromatic_aberration: number; // from 0 to x (1 for realism)
  84579. * edge_blur: number; // from 0 to x (1 for realism)
  84580. * distortion: number; // from 0 to x (1 for realism)
  84581. * grain_amount: number; // from 0 to 1
  84582. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  84583. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  84584. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  84585. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  84586. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  84587. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  84588. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  84589. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  84590. * }
  84591. * Note: if an effect parameter is unset, effect is disabled
  84592. *
  84593. * @param name The rendering pipeline name
  84594. * @param parameters - An object containing all parameters (see above)
  84595. * @param scene The scene linked to this pipeline
  84596. * @param 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)
  84597. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84598. */
  84599. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  84600. if (ratio === void 0) { ratio = 1.0; }
  84601. var _this = _super.call(this, scene.getEngine(), name) || this;
  84602. // Lens effects can be of the following:
  84603. // - chromatic aberration (slight shift of RGB colors)
  84604. // - blur on the edge of the lens
  84605. // - lens distortion
  84606. // - depth-of-field blur & highlights enhancing
  84607. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  84608. // - grain effect (noise or custom texture)
  84609. // Two additional texture samplers are needed:
  84610. // - depth map (for depth-of-field)
  84611. // - grain texture
  84612. /**
  84613. * @ignore
  84614. * The chromatic aberration PostProcess id in the pipeline
  84615. */
  84616. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  84617. /**
  84618. * @ignore
  84619. * The highlights enhancing PostProcess id in the pipeline
  84620. */
  84621. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  84622. /**
  84623. * @ignore
  84624. * The depth-of-field PostProcess id in the pipeline
  84625. */
  84626. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  84627. _this._scene = scene;
  84628. // Fetch texture samplers
  84629. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84630. if (parameters.grain_texture) {
  84631. _this._grainTexture = parameters.grain_texture;
  84632. }
  84633. else {
  84634. _this._createGrainTexture();
  84635. }
  84636. // save parameters
  84637. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  84638. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  84639. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  84640. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  84641. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  84642. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  84643. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  84644. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  84645. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  84646. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  84647. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  84648. // Create effects
  84649. _this._createChromaticAberrationPostProcess(ratio);
  84650. _this._createHighlightsPostProcess(ratio);
  84651. _this._createDepthOfFieldPostProcess(ratio / 4);
  84652. // Set up pipeline
  84653. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  84654. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  84655. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  84656. if (_this._highlightsGain === -1) {
  84657. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  84658. }
  84659. // Finish
  84660. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84661. if (cameras) {
  84662. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84663. }
  84664. return _this;
  84665. }
  84666. // public methods (self explanatory)
  84667. /**
  84668. * Sets the amount of blur at the edges
  84669. * @param amount blur amount
  84670. */
  84671. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  84672. /**
  84673. * Sets edge blur to 0
  84674. */
  84675. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  84676. /**
  84677. * Sets the amout of grain
  84678. * @param amount Amount of grain
  84679. */
  84680. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  84681. /**
  84682. * Set grain amount to 0
  84683. */
  84684. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  84685. /**
  84686. * Sets the chromatic aberration amount
  84687. * @param amount amount of chromatic aberration
  84688. */
  84689. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  84690. /**
  84691. * Sets chromatic aberration amount to 0
  84692. */
  84693. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  84694. /**
  84695. * Sets the EdgeDistortion amount
  84696. * @param amount amount of EdgeDistortion
  84697. */
  84698. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  84699. /**
  84700. * Sets edge distortion to 0
  84701. */
  84702. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  84703. /**
  84704. * Sets the FocusDistance amount
  84705. * @param amount amount of FocusDistance
  84706. */
  84707. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  84708. /**
  84709. * Disables depth of field
  84710. */
  84711. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  84712. /**
  84713. * Sets the Aperture amount
  84714. * @param amount amount of Aperture
  84715. */
  84716. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  84717. /**
  84718. * Sets the DarkenOutOfFocus amount
  84719. * @param amount amount of DarkenOutOfFocus
  84720. */
  84721. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  84722. /**
  84723. * Creates a pentagon bokeh effect
  84724. */
  84725. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  84726. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  84727. };
  84728. /**
  84729. * Disables the pentagon bokeh effect
  84730. */
  84731. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  84732. this._highlightsPostProcess.updateEffect();
  84733. };
  84734. /**
  84735. * Enables noise blur
  84736. */
  84737. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  84738. /**
  84739. * Disables noise blur
  84740. */
  84741. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  84742. /**
  84743. * Sets the HighlightsGain amount
  84744. * @param amount amount of HighlightsGain
  84745. */
  84746. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  84747. this._highlightsGain = amount;
  84748. };
  84749. /**
  84750. * Sets the HighlightsThreshold amount
  84751. * @param amount amount of HighlightsThreshold
  84752. */
  84753. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  84754. if (this._highlightsGain === -1) {
  84755. this._highlightsGain = 1.0;
  84756. }
  84757. this._highlightsThreshold = amount;
  84758. };
  84759. /**
  84760. * Disables highlights
  84761. */
  84762. LensRenderingPipeline.prototype.disableHighlights = function () {
  84763. this._highlightsGain = -1;
  84764. };
  84765. /**
  84766. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  84767. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  84768. */
  84769. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84770. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84771. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84772. this._chromaticAberrationPostProcess = null;
  84773. this._highlightsPostProcess = null;
  84774. this._depthOfFieldPostProcess = null;
  84775. this._grainTexture.dispose();
  84776. if (disableDepthRender) {
  84777. this._scene.disableDepthRenderer();
  84778. }
  84779. };
  84780. // colors shifting and distortion
  84781. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  84782. var _this = this;
  84783. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  84784. [], // samplers
  84785. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84786. this._chromaticAberrationPostProcess.onApply = function (effect) {
  84787. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  84788. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84789. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84790. effect.setFloat('radialIntensity', 1);
  84791. effect.setFloat2('direction', 17, 17);
  84792. effect.setFloat2('centerPosition', 0.5, 0.5);
  84793. };
  84794. };
  84795. // highlights enhancing
  84796. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  84797. var _this = this;
  84798. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  84799. [], // samplers
  84800. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  84801. this._highlightsPostProcess.onApply = function (effect) {
  84802. effect.setFloat('gain', _this._highlightsGain);
  84803. effect.setFloat('threshold', _this._highlightsThreshold);
  84804. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  84805. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84806. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84807. };
  84808. };
  84809. // colors shifting and distortion
  84810. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  84811. var _this = this;
  84812. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  84813. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  84814. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  84815. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84816. this._depthOfFieldPostProcess.onApply = function (effect) {
  84817. effect.setTexture("depthSampler", _this._depthTexture);
  84818. effect.setTexture("grainSampler", _this._grainTexture);
  84819. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  84820. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  84821. effect.setFloat('grain_amount', _this._grainAmount);
  84822. effect.setBool('blur_noise', _this._blurNoise);
  84823. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84824. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84825. effect.setFloat('distortion', _this._distortion);
  84826. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  84827. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  84828. effect.setFloat('aperture', _this._dofAperture);
  84829. effect.setFloat('darken', _this._dofDarken);
  84830. effect.setFloat('edge_blur', _this._edgeBlur);
  84831. effect.setBool('highlights', (_this._highlightsGain !== -1));
  84832. if (_this._scene.activeCamera) {
  84833. effect.setFloat('near', _this._scene.activeCamera.minZ);
  84834. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  84835. }
  84836. };
  84837. };
  84838. // creates a black and white random noise texture, 512x512
  84839. LensRenderingPipeline.prototype._createGrainTexture = function () {
  84840. var size = 512;
  84841. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84842. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84843. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84844. var context = this._grainTexture.getContext();
  84845. var rand = function (min, max) {
  84846. return Math.random() * (max - min) + min;
  84847. };
  84848. var value;
  84849. for (var x = 0; x < size; x++) {
  84850. for (var y = 0; y < size; y++) {
  84851. value = Math.floor(rand(0.42, 0.58) * 255);
  84852. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  84853. context.fillRect(x, y, 1, 1);
  84854. }
  84855. }
  84856. this._grainTexture.update(false);
  84857. };
  84858. return LensRenderingPipeline;
  84859. }(BABYLON.PostProcessRenderPipeline));
  84860. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  84861. })(BABYLON || (BABYLON = {}));
  84862. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  84863. var BABYLON;
  84864. (function (BABYLON) {
  84865. /**
  84866. * Standard rendering pipeline
  84867. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84868. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  84869. */
  84870. var StandardRenderingPipeline = /** @class */ (function (_super) {
  84871. __extends(StandardRenderingPipeline, _super);
  84872. /**
  84873. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84874. * @constructor
  84875. * @param name The rendering pipeline name
  84876. * @param scene The scene linked to this pipeline
  84877. * @param 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)
  84878. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  84879. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84880. */
  84881. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  84882. if (originalPostProcess === void 0) { originalPostProcess = null; }
  84883. var _this = _super.call(this, scene.getEngine(), name) || this;
  84884. /**
  84885. * Post-process used to down scale an image x4
  84886. */
  84887. _this.downSampleX4PostProcess = null;
  84888. /**
  84889. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  84890. */
  84891. _this.brightPassPostProcess = null;
  84892. /**
  84893. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  84894. */
  84895. _this.blurHPostProcesses = [];
  84896. /**
  84897. * Post-process array storing all the vertical blur post-processes used by the pipeline
  84898. */
  84899. _this.blurVPostProcesses = [];
  84900. /**
  84901. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  84902. */
  84903. _this.textureAdderPostProcess = null;
  84904. /**
  84905. * Post-process used to create volumetric lighting effect
  84906. */
  84907. _this.volumetricLightPostProcess = null;
  84908. /**
  84909. * Post-process used to smooth the previous volumetric light post-process on the X axis
  84910. */
  84911. _this.volumetricLightSmoothXPostProcess = null;
  84912. /**
  84913. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  84914. */
  84915. _this.volumetricLightSmoothYPostProcess = null;
  84916. /**
  84917. * Post-process used to merge the volumetric light effect and the real scene color
  84918. */
  84919. _this.volumetricLightMergePostProces = null;
  84920. /**
  84921. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  84922. */
  84923. _this.volumetricLightFinalPostProcess = null;
  84924. /**
  84925. * Base post-process used to calculate the average luminance of the final image for HDR
  84926. */
  84927. _this.luminancePostProcess = null;
  84928. /**
  84929. * Post-processes used to create down sample post-processes in order to get
  84930. * the average luminance of the final image for HDR
  84931. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  84932. */
  84933. _this.luminanceDownSamplePostProcesses = [];
  84934. /**
  84935. * Post-process used to create a HDR effect (light adaptation)
  84936. */
  84937. _this.hdrPostProcess = null;
  84938. /**
  84939. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  84940. */
  84941. _this.textureAdderFinalPostProcess = null;
  84942. /**
  84943. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  84944. */
  84945. _this.lensFlareFinalPostProcess = null;
  84946. /**
  84947. * Post-process used to merge the final HDR post-process and the real scene color
  84948. */
  84949. _this.hdrFinalPostProcess = null;
  84950. /**
  84951. * Post-process used to create a lens flare effect
  84952. */
  84953. _this.lensFlarePostProcess = null;
  84954. /**
  84955. * Post-process that merges the result of the lens flare post-process and the real scene color
  84956. */
  84957. _this.lensFlareComposePostProcess = null;
  84958. /**
  84959. * Post-process used to create a motion blur effect
  84960. */
  84961. _this.motionBlurPostProcess = null;
  84962. /**
  84963. * Post-process used to create a depth of field effect
  84964. */
  84965. _this.depthOfFieldPostProcess = null;
  84966. /**
  84967. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  84968. */
  84969. _this.fxaaPostProcess = null;
  84970. // Values
  84971. /**
  84972. * Represents the brightness threshold in order to configure the illuminated surfaces
  84973. */
  84974. _this.brightThreshold = 1.0;
  84975. /**
  84976. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  84977. */
  84978. _this.blurWidth = 512.0;
  84979. /**
  84980. * Sets if the blur for highlighted surfaces must be only horizontal
  84981. */
  84982. _this.horizontalBlur = false;
  84983. /**
  84984. * Sets the overall exposure used by the pipeline
  84985. */
  84986. _this.exposure = 1.0;
  84987. /**
  84988. * Texture used typically to simulate "dirty" on camera lens
  84989. */
  84990. _this.lensTexture = null;
  84991. /**
  84992. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  84993. */
  84994. _this.volumetricLightCoefficient = 0.2;
  84995. /**
  84996. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  84997. */
  84998. _this.volumetricLightPower = 4.0;
  84999. /**
  85000. * Used the set the blur intensity to smooth the volumetric lights
  85001. */
  85002. _this.volumetricLightBlurScale = 64.0;
  85003. /**
  85004. * Light (spot or directional) used to generate the volumetric lights rays
  85005. * The source light must have a shadow generate so the pipeline can get its
  85006. * depth map
  85007. */
  85008. _this.sourceLight = null;
  85009. /**
  85010. * For eye adaptation, represents the minimum luminance the eye can see
  85011. */
  85012. _this.hdrMinimumLuminance = 1.0;
  85013. /**
  85014. * For eye adaptation, represents the decrease luminance speed
  85015. */
  85016. _this.hdrDecreaseRate = 0.5;
  85017. /**
  85018. * For eye adaptation, represents the increase luminance speed
  85019. */
  85020. _this.hdrIncreaseRate = 0.5;
  85021. /**
  85022. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  85023. */
  85024. _this.lensColorTexture = null;
  85025. /**
  85026. * The overall strengh for the lens flare effect
  85027. */
  85028. _this.lensFlareStrength = 20.0;
  85029. /**
  85030. * Dispersion coefficient for lens flare ghosts
  85031. */
  85032. _this.lensFlareGhostDispersal = 1.4;
  85033. /**
  85034. * Main lens flare halo width
  85035. */
  85036. _this.lensFlareHaloWidth = 0.7;
  85037. /**
  85038. * Based on the lens distortion effect, defines how much the lens flare result
  85039. * is distorted
  85040. */
  85041. _this.lensFlareDistortionStrength = 16.0;
  85042. /**
  85043. * Lens star texture must be used to simulate rays on the flares and is available
  85044. * in the documentation
  85045. */
  85046. _this.lensStarTexture = null;
  85047. /**
  85048. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  85049. * flare effect by taking account of the dirt texture
  85050. */
  85051. _this.lensFlareDirtTexture = null;
  85052. /**
  85053. * Represents the focal length for the depth of field effect
  85054. */
  85055. _this.depthOfFieldDistance = 10.0;
  85056. /**
  85057. * Represents the blur intensity for the blurred part of the depth of field effect
  85058. */
  85059. _this.depthOfFieldBlurWidth = 64.0;
  85060. /**
  85061. * For motion blur, defines how much the image is blurred by the movement
  85062. */
  85063. _this.motionStrength = 1.0;
  85064. /**
  85065. * List of animations for the pipeline (IAnimatable implementation)
  85066. */
  85067. _this.animations = [];
  85068. _this._currentDepthOfFieldSource = null;
  85069. _this._hdrCurrentLuminance = 1.0;
  85070. // Getters and setters
  85071. _this._bloomEnabled = false;
  85072. _this._depthOfFieldEnabled = false;
  85073. _this._vlsEnabled = false;
  85074. _this._lensFlareEnabled = false;
  85075. _this._hdrEnabled = false;
  85076. _this._motionBlurEnabled = false;
  85077. _this._fxaaEnabled = false;
  85078. _this._motionBlurSamples = 64.0;
  85079. _this._volumetricLightStepsCount = 50.0;
  85080. _this._samples = 1;
  85081. _this._cameras = cameras || [];
  85082. // Initialize
  85083. _this._scene = scene;
  85084. _this._basePostProcess = originalPostProcess;
  85085. _this._ratio = ratio;
  85086. // Misc
  85087. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85088. // Finish
  85089. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85090. _this._buildPipeline();
  85091. return _this;
  85092. }
  85093. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  85094. /**
  85095. * @ignore
  85096. * Specifies if the bloom pipeline is enabled
  85097. */
  85098. get: function () {
  85099. return this._bloomEnabled;
  85100. },
  85101. set: function (enabled) {
  85102. if (this._bloomEnabled === enabled) {
  85103. return;
  85104. }
  85105. this._bloomEnabled = enabled;
  85106. this._buildPipeline();
  85107. },
  85108. enumerable: true,
  85109. configurable: true
  85110. });
  85111. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  85112. /**
  85113. * @ignore
  85114. * Specifies if the depth of field pipeline is enabed
  85115. */
  85116. get: function () {
  85117. return this._depthOfFieldEnabled;
  85118. },
  85119. set: function (enabled) {
  85120. if (this._depthOfFieldEnabled === enabled) {
  85121. return;
  85122. }
  85123. this._depthOfFieldEnabled = enabled;
  85124. this._buildPipeline();
  85125. },
  85126. enumerable: true,
  85127. configurable: true
  85128. });
  85129. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  85130. /**
  85131. * @ignore
  85132. * Specifies if the lens flare pipeline is enabed
  85133. */
  85134. get: function () {
  85135. return this._lensFlareEnabled;
  85136. },
  85137. set: function (enabled) {
  85138. if (this._lensFlareEnabled === enabled) {
  85139. return;
  85140. }
  85141. this._lensFlareEnabled = enabled;
  85142. this._buildPipeline();
  85143. },
  85144. enumerable: true,
  85145. configurable: true
  85146. });
  85147. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  85148. /**
  85149. * @ignore
  85150. * Specifies if the HDR pipeline is enabled
  85151. */
  85152. get: function () {
  85153. return this._hdrEnabled;
  85154. },
  85155. set: function (enabled) {
  85156. if (this._hdrEnabled === enabled) {
  85157. return;
  85158. }
  85159. this._hdrEnabled = enabled;
  85160. this._buildPipeline();
  85161. },
  85162. enumerable: true,
  85163. configurable: true
  85164. });
  85165. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  85166. /**
  85167. * @ignore
  85168. * Specifies if the volumetric lights scattering effect is enabled
  85169. */
  85170. get: function () {
  85171. return this._vlsEnabled;
  85172. },
  85173. set: function (enabled) {
  85174. if (this._vlsEnabled === enabled) {
  85175. return;
  85176. }
  85177. if (enabled) {
  85178. var geometry = this._scene.enableGeometryBufferRenderer();
  85179. if (!geometry) {
  85180. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  85181. return;
  85182. }
  85183. }
  85184. this._vlsEnabled = enabled;
  85185. this._buildPipeline();
  85186. },
  85187. enumerable: true,
  85188. configurable: true
  85189. });
  85190. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  85191. /**
  85192. * @ignore
  85193. * Specifies if the motion blur effect is enabled
  85194. */
  85195. get: function () {
  85196. return this._motionBlurEnabled;
  85197. },
  85198. set: function (enabled) {
  85199. if (this._motionBlurEnabled === enabled) {
  85200. return;
  85201. }
  85202. this._motionBlurEnabled = enabled;
  85203. this._buildPipeline();
  85204. },
  85205. enumerable: true,
  85206. configurable: true
  85207. });
  85208. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  85209. /**
  85210. * Specifies if anti-aliasing is enabled
  85211. */
  85212. get: function () {
  85213. return this._fxaaEnabled;
  85214. },
  85215. set: function (enabled) {
  85216. if (this._fxaaEnabled === enabled) {
  85217. return;
  85218. }
  85219. this._fxaaEnabled = enabled;
  85220. this._buildPipeline();
  85221. },
  85222. enumerable: true,
  85223. configurable: true
  85224. });
  85225. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  85226. /**
  85227. * Specifies the number of steps used to calculate the volumetric lights
  85228. * Typically in interval [50, 200]
  85229. */
  85230. get: function () {
  85231. return this._volumetricLightStepsCount;
  85232. },
  85233. set: function (count) {
  85234. if (this.volumetricLightPostProcess) {
  85235. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  85236. }
  85237. this._volumetricLightStepsCount = count;
  85238. },
  85239. enumerable: true,
  85240. configurable: true
  85241. });
  85242. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  85243. /**
  85244. * Specifies the number of samples used for the motion blur effect
  85245. * Typically in interval [16, 64]
  85246. */
  85247. get: function () {
  85248. return this._motionBlurSamples;
  85249. },
  85250. set: function (samples) {
  85251. if (this.motionBlurPostProcess) {
  85252. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  85253. }
  85254. this._motionBlurSamples = samples;
  85255. },
  85256. enumerable: true,
  85257. configurable: true
  85258. });
  85259. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  85260. /**
  85261. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85262. */
  85263. get: function () {
  85264. return this._samples;
  85265. },
  85266. set: function (sampleCount) {
  85267. if (this._samples === sampleCount) {
  85268. return;
  85269. }
  85270. this._samples = sampleCount;
  85271. this._buildPipeline();
  85272. },
  85273. enumerable: true,
  85274. configurable: true
  85275. });
  85276. StandardRenderingPipeline.prototype._buildPipeline = function () {
  85277. var _this = this;
  85278. var ratio = this._ratio;
  85279. var scene = this._scene;
  85280. this._disposePostProcesses();
  85281. this._reset();
  85282. // Create pass post-process
  85283. if (!this._basePostProcess) {
  85284. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  85285. this.originalPostProcess.onApply = function (effect) {
  85286. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  85287. };
  85288. }
  85289. else {
  85290. this.originalPostProcess = this._basePostProcess;
  85291. }
  85292. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  85293. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  85294. }
  85295. this._currentDepthOfFieldSource = this.originalPostProcess;
  85296. if (this._bloomEnabled) {
  85297. // Create down sample X4 post-process
  85298. this._createDownSampleX4PostProcess(scene, ratio / 2);
  85299. // Create bright pass post-process
  85300. this._createBrightPassPostProcess(scene, ratio / 2);
  85301. // Create gaussian blur post-processes (down sampling blurs)
  85302. this._createBlurPostProcesses(scene, ratio / 4, 1);
  85303. // Create texture adder post-process
  85304. this._createTextureAdderPostProcess(scene, ratio);
  85305. // Create depth-of-field source post-process
  85306. 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);
  85307. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  85308. }
  85309. if (this._vlsEnabled) {
  85310. // Create volumetric light
  85311. this._createVolumetricLightPostProcess(scene, ratio);
  85312. // Create volumetric light final post-process
  85313. 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);
  85314. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  85315. }
  85316. if (this._lensFlareEnabled) {
  85317. // Create lens flare post-process
  85318. this._createLensFlarePostProcess(scene, ratio);
  85319. // Create depth-of-field source post-process post lens-flare and disable it now
  85320. 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);
  85321. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  85322. }
  85323. if (this._hdrEnabled) {
  85324. // Create luminance
  85325. this._createLuminancePostProcesses(scene, this._floatTextureType);
  85326. // Create HDR
  85327. this._createHdrPostProcess(scene, ratio);
  85328. // Create depth-of-field source post-process post hdr and disable it now
  85329. 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);
  85330. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  85331. }
  85332. if (this._depthOfFieldEnabled) {
  85333. // Create gaussian blur used by depth-of-field
  85334. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  85335. // Create depth-of-field post-process
  85336. this._createDepthOfFieldPostProcess(scene, ratio);
  85337. }
  85338. if (this._motionBlurEnabled) {
  85339. // Create motion blur post-process
  85340. this._createMotionBlurPostProcess(scene, ratio);
  85341. }
  85342. if (this._fxaaEnabled) {
  85343. // Create fxaa post-process
  85344. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  85346. }
  85347. if (this._cameras !== null) {
  85348. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85349. }
  85350. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  85351. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85352. }
  85353. };
  85354. // Down Sample X4 Post-Processs
  85355. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  85356. var _this = this;
  85357. var downSampleX4Offsets = new Array(32);
  85358. 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);
  85359. this.downSampleX4PostProcess.onApply = function (effect) {
  85360. var id = 0;
  85361. var width = _this.downSampleX4PostProcess.width;
  85362. var height = _this.downSampleX4PostProcess.height;
  85363. for (var i = -2; i < 2; i++) {
  85364. for (var j = -2; j < 2; j++) {
  85365. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  85366. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  85367. id += 2;
  85368. }
  85369. }
  85370. effect.setArray2("dsOffsets", downSampleX4Offsets);
  85371. };
  85372. // Add to pipeline
  85373. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  85374. };
  85375. // Brightpass Post-Process
  85376. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  85377. var _this = this;
  85378. var brightOffsets = new Array(8);
  85379. 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);
  85380. this.brightPassPostProcess.onApply = function (effect) {
  85381. var sU = (1.0 / _this.brightPassPostProcess.width);
  85382. var sV = (1.0 / _this.brightPassPostProcess.height);
  85383. brightOffsets[0] = -0.5 * sU;
  85384. brightOffsets[1] = 0.5 * sV;
  85385. brightOffsets[2] = 0.5 * sU;
  85386. brightOffsets[3] = 0.5 * sV;
  85387. brightOffsets[4] = -0.5 * sU;
  85388. brightOffsets[5] = -0.5 * sV;
  85389. brightOffsets[6] = 0.5 * sU;
  85390. brightOffsets[7] = -0.5 * sV;
  85391. effect.setArray2("dsOffsets", brightOffsets);
  85392. effect.setFloat("brightThreshold", _this.brightThreshold);
  85393. };
  85394. // Add to pipeline
  85395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  85396. };
  85397. // Create blur H&V post-processes
  85398. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  85399. var _this = this;
  85400. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  85401. var engine = scene.getEngine();
  85402. 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);
  85403. 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);
  85404. blurX.onActivateObservable.add(function () {
  85405. var dw = blurX.width / engine.getRenderWidth();
  85406. blurX.kernel = _this[blurWidthKey] * dw;
  85407. });
  85408. blurY.onActivateObservable.add(function () {
  85409. var dw = blurY.height / engine.getRenderHeight();
  85410. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  85411. });
  85412. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  85413. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  85414. this.blurHPostProcesses.push(blurX);
  85415. this.blurVPostProcesses.push(blurY);
  85416. };
  85417. // Create texture adder post-process
  85418. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  85419. var _this = this;
  85420. 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);
  85421. this.textureAdderPostProcess.onApply = function (effect) {
  85422. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  85423. effect.setTexture("lensSampler", _this.lensTexture);
  85424. effect.setFloat("exposure", _this.exposure);
  85425. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  85426. };
  85427. // Add to pipeline
  85428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  85429. };
  85430. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  85431. var _this = this;
  85432. var geometryRenderer = scene.enableGeometryBufferRenderer();
  85433. geometryRenderer.enablePosition = true;
  85434. var geometry = geometryRenderer.getGBuffer();
  85435. // Base post-process
  85436. 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));
  85437. var depthValues = BABYLON.Vector2.Zero();
  85438. this.volumetricLightPostProcess.onApply = function (effect) {
  85439. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  85440. var generator = _this.sourceLight.getShadowGenerator();
  85441. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  85442. effect.setTexture("positionSampler", geometry.textures[2]);
  85443. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  85444. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  85445. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  85446. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  85447. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  85448. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  85449. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  85450. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  85451. effect.setVector2("depthValues", depthValues);
  85452. }
  85453. };
  85454. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  85455. // Smooth
  85456. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  85457. // Merge
  85458. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  85459. this.volumetricLightMergePostProces.onApply = function (effect) {
  85460. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  85461. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  85462. };
  85463. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  85464. };
  85465. // Create luminance
  85466. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  85467. var _this = this;
  85468. // Create luminance
  85469. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  85470. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  85471. var offsets = [];
  85472. this.luminancePostProcess.onApply = function (effect) {
  85473. var sU = (1.0 / _this.luminancePostProcess.width);
  85474. var sV = (1.0 / _this.luminancePostProcess.height);
  85475. offsets[0] = -0.5 * sU;
  85476. offsets[1] = 0.5 * sV;
  85477. offsets[2] = 0.5 * sU;
  85478. offsets[3] = 0.5 * sV;
  85479. offsets[4] = -0.5 * sU;
  85480. offsets[5] = -0.5 * sV;
  85481. offsets[6] = 0.5 * sU;
  85482. offsets[7] = -0.5 * sV;
  85483. effect.setArray2("lumOffsets", offsets);
  85484. };
  85485. // Add to pipeline
  85486. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  85487. // Create down sample luminance
  85488. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  85489. var size = Math.pow(3, i);
  85490. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  85491. if (i === 0) {
  85492. defines += "#define FINAL_DOWN_SAMPLER";
  85493. }
  85494. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  85495. this.luminanceDownSamplePostProcesses.push(postProcess);
  85496. }
  85497. // Create callbacks and add effects
  85498. var lastLuminance = this.luminancePostProcess;
  85499. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  85500. var downSampleOffsets = new Array(18);
  85501. pp.onApply = function (effect) {
  85502. if (!lastLuminance) {
  85503. return;
  85504. }
  85505. var id = 0;
  85506. for (var x = -1; x < 2; x++) {
  85507. for (var y = -1; y < 2; y++) {
  85508. downSampleOffsets[id] = x / lastLuminance.width;
  85509. downSampleOffsets[id + 1] = y / lastLuminance.height;
  85510. id += 2;
  85511. }
  85512. }
  85513. effect.setArray2("dsOffsets", downSampleOffsets);
  85514. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  85515. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85516. lastLuminance = _this.luminancePostProcess;
  85517. }
  85518. else {
  85519. lastLuminance = pp;
  85520. }
  85521. };
  85522. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85523. pp.onAfterRender = function (effect) {
  85524. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  85525. 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);
  85526. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  85527. };
  85528. }
  85529. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  85530. });
  85531. };
  85532. // Create HDR post-process
  85533. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  85534. var _this = this;
  85535. 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);
  85536. var outputLiminance = 1;
  85537. var time = 0;
  85538. var lastTime = 0;
  85539. this.hdrPostProcess.onApply = function (effect) {
  85540. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  85541. time += scene.getEngine().getDeltaTime();
  85542. if (outputLiminance < 0) {
  85543. outputLiminance = _this._hdrCurrentLuminance;
  85544. }
  85545. else {
  85546. var dt = (lastTime - time) / 1000.0;
  85547. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  85548. outputLiminance += _this.hdrDecreaseRate * dt;
  85549. }
  85550. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  85551. outputLiminance -= _this.hdrIncreaseRate * dt;
  85552. }
  85553. else {
  85554. outputLiminance = _this._hdrCurrentLuminance;
  85555. }
  85556. }
  85557. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  85558. effect.setFloat("averageLuminance", outputLiminance);
  85559. lastTime = time;
  85560. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  85561. };
  85562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  85563. };
  85564. // Create lens flare post-process
  85565. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  85566. var _this = this;
  85567. 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);
  85568. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  85569. this._createBlurPostProcesses(scene, ratio / 4, 2);
  85570. 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);
  85571. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  85572. var resolution = new BABYLON.Vector2(0, 0);
  85573. // Lens flare
  85574. this.lensFlarePostProcess.onApply = function (effect) {
  85575. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  85576. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  85577. effect.setFloat("strength", _this.lensFlareStrength);
  85578. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  85579. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  85580. // Shift
  85581. resolution.x = _this.lensFlarePostProcess.width;
  85582. resolution.y = _this.lensFlarePostProcess.height;
  85583. effect.setVector2("resolution", resolution);
  85584. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  85585. };
  85586. // Compose
  85587. 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);
  85588. 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);
  85589. this.lensFlareComposePostProcess.onApply = function (effect) {
  85590. if (!_this._scene.activeCamera) {
  85591. return;
  85592. }
  85593. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85594. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  85595. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  85596. // Lens start rotation matrix
  85597. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  85598. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  85599. 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));
  85600. camRot *= 4.0;
  85601. 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);
  85602. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  85603. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  85604. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  85605. };
  85606. };
  85607. // Create depth-of-field post-process
  85608. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  85609. var _this = this;
  85610. 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);
  85611. this.depthOfFieldPostProcess.onApply = function (effect) {
  85612. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85613. effect.setTexture("depthSampler", _this._getDepthTexture());
  85614. effect.setFloat("distance", _this.depthOfFieldDistance);
  85615. };
  85616. // Add to pipeline
  85617. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  85618. };
  85619. // Create motion blur post-process
  85620. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  85621. var _this = this;
  85622. 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);
  85623. var motionScale = 0;
  85624. var prevViewProjection = BABYLON.Matrix.Identity();
  85625. var invViewProjection = BABYLON.Matrix.Identity();
  85626. var viewProjection = BABYLON.Matrix.Identity();
  85627. var screenSize = BABYLON.Vector2.Zero();
  85628. this.motionBlurPostProcess.onApply = function (effect) {
  85629. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  85630. viewProjection.invertToRef(invViewProjection);
  85631. effect.setMatrix("inverseViewProjection", invViewProjection);
  85632. effect.setMatrix("prevViewProjection", prevViewProjection);
  85633. prevViewProjection = viewProjection;
  85634. screenSize.x = _this.motionBlurPostProcess.width;
  85635. screenSize.y = _this.motionBlurPostProcess.height;
  85636. effect.setVector2("screenSize", screenSize);
  85637. motionScale = scene.getEngine().getFps() / 60.0;
  85638. effect.setFloat("motionScale", motionScale);
  85639. effect.setFloat("motionStrength", _this.motionStrength);
  85640. effect.setTexture("depthSampler", _this._getDepthTexture());
  85641. };
  85642. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  85643. };
  85644. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  85645. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  85646. var renderer = this._scene.enableGeometryBufferRenderer();
  85647. return renderer.getGBuffer().textures[0];
  85648. }
  85649. return this._scene.enableDepthRenderer().getDepthMap();
  85650. };
  85651. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  85652. for (var i = 0; i < this._cameras.length; i++) {
  85653. var camera = this._cameras[i];
  85654. if (this.originalPostProcess) {
  85655. this.originalPostProcess.dispose(camera);
  85656. }
  85657. if (this.downSampleX4PostProcess) {
  85658. this.downSampleX4PostProcess.dispose(camera);
  85659. }
  85660. if (this.brightPassPostProcess) {
  85661. this.brightPassPostProcess.dispose(camera);
  85662. }
  85663. if (this.textureAdderPostProcess) {
  85664. this.textureAdderPostProcess.dispose(camera);
  85665. }
  85666. if (this.textureAdderFinalPostProcess) {
  85667. this.textureAdderFinalPostProcess.dispose(camera);
  85668. }
  85669. if (this.volumetricLightPostProcess) {
  85670. this.volumetricLightPostProcess.dispose(camera);
  85671. }
  85672. if (this.volumetricLightSmoothXPostProcess) {
  85673. this.volumetricLightSmoothXPostProcess.dispose(camera);
  85674. }
  85675. if (this.volumetricLightSmoothYPostProcess) {
  85676. this.volumetricLightSmoothYPostProcess.dispose(camera);
  85677. }
  85678. if (this.volumetricLightMergePostProces) {
  85679. this.volumetricLightMergePostProces.dispose(camera);
  85680. }
  85681. if (this.volumetricLightFinalPostProcess) {
  85682. this.volumetricLightFinalPostProcess.dispose(camera);
  85683. }
  85684. if (this.lensFlarePostProcess) {
  85685. this.lensFlarePostProcess.dispose(camera);
  85686. }
  85687. if (this.lensFlareComposePostProcess) {
  85688. this.lensFlareComposePostProcess.dispose(camera);
  85689. }
  85690. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  85691. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  85692. }
  85693. if (this.luminancePostProcess) {
  85694. this.luminancePostProcess.dispose(camera);
  85695. }
  85696. if (this.hdrPostProcess) {
  85697. this.hdrPostProcess.dispose(camera);
  85698. }
  85699. if (this.hdrFinalPostProcess) {
  85700. this.hdrFinalPostProcess.dispose(camera);
  85701. }
  85702. if (this.depthOfFieldPostProcess) {
  85703. this.depthOfFieldPostProcess.dispose(camera);
  85704. }
  85705. if (this.motionBlurPostProcess) {
  85706. this.motionBlurPostProcess.dispose(camera);
  85707. }
  85708. if (this.fxaaPostProcess) {
  85709. this.fxaaPostProcess.dispose(camera);
  85710. }
  85711. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  85712. this.blurHPostProcesses[j].dispose(camera);
  85713. }
  85714. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  85715. this.blurVPostProcesses[j].dispose(camera);
  85716. }
  85717. }
  85718. this.originalPostProcess = null;
  85719. this.downSampleX4PostProcess = null;
  85720. this.brightPassPostProcess = null;
  85721. this.textureAdderPostProcess = null;
  85722. this.textureAdderFinalPostProcess = null;
  85723. this.volumetricLightPostProcess = null;
  85724. this.volumetricLightSmoothXPostProcess = null;
  85725. this.volumetricLightSmoothYPostProcess = null;
  85726. this.volumetricLightMergePostProces = null;
  85727. this.volumetricLightFinalPostProcess = null;
  85728. this.lensFlarePostProcess = null;
  85729. this.lensFlareComposePostProcess = null;
  85730. this.luminancePostProcess = null;
  85731. this.hdrPostProcess = null;
  85732. this.hdrFinalPostProcess = null;
  85733. this.depthOfFieldPostProcess = null;
  85734. this.motionBlurPostProcess = null;
  85735. this.fxaaPostProcess = null;
  85736. this.luminanceDownSamplePostProcesses = [];
  85737. this.blurHPostProcesses = [];
  85738. this.blurVPostProcesses = [];
  85739. };
  85740. /**
  85741. * Dispose of the pipeline and stop all post processes
  85742. */
  85743. StandardRenderingPipeline.prototype.dispose = function () {
  85744. this._disposePostProcesses();
  85745. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85746. _super.prototype.dispose.call(this);
  85747. };
  85748. /**
  85749. * Serialize the rendering pipeline (Used when exporting)
  85750. * @returns the serialized object
  85751. */
  85752. StandardRenderingPipeline.prototype.serialize = function () {
  85753. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85754. if (this.sourceLight) {
  85755. serializationObject.sourceLightId = this.sourceLight.id;
  85756. }
  85757. serializationObject.customType = "StandardRenderingPipeline";
  85758. return serializationObject;
  85759. };
  85760. /**
  85761. * Parse the serialized pipeline
  85762. * @param source Source pipeline.
  85763. * @param scene The scene to load the pipeline to.
  85764. * @param rootUrl The URL of the serialized pipeline.
  85765. * @returns An instantiated pipeline from the serialized object.
  85766. */
  85767. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85768. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85769. if (source.sourceLightId) {
  85770. p.sourceLight = scene.getLightByID(source.sourceLightId);
  85771. }
  85772. return p;
  85773. };
  85774. /**
  85775. * Luminance steps
  85776. */
  85777. StandardRenderingPipeline.LuminanceSteps = 6;
  85778. __decorate([
  85779. BABYLON.serialize()
  85780. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  85781. __decorate([
  85782. BABYLON.serialize()
  85783. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  85784. __decorate([
  85785. BABYLON.serialize()
  85786. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  85787. __decorate([
  85788. BABYLON.serialize()
  85789. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  85790. __decorate([
  85791. BABYLON.serializeAsTexture("lensTexture")
  85792. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  85793. __decorate([
  85794. BABYLON.serialize()
  85795. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  85796. __decorate([
  85797. BABYLON.serialize()
  85798. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  85799. __decorate([
  85800. BABYLON.serialize()
  85801. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  85802. __decorate([
  85803. BABYLON.serialize()
  85804. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  85805. __decorate([
  85806. BABYLON.serialize()
  85807. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  85808. __decorate([
  85809. BABYLON.serialize()
  85810. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  85811. __decorate([
  85812. BABYLON.serializeAsTexture("lensColorTexture")
  85813. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  85814. __decorate([
  85815. BABYLON.serialize()
  85816. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  85817. __decorate([
  85818. BABYLON.serialize()
  85819. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  85820. __decorate([
  85821. BABYLON.serialize()
  85822. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  85823. __decorate([
  85824. BABYLON.serialize()
  85825. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  85826. __decorate([
  85827. BABYLON.serializeAsTexture("lensStarTexture")
  85828. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  85829. __decorate([
  85830. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  85831. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  85832. __decorate([
  85833. BABYLON.serialize()
  85834. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  85835. __decorate([
  85836. BABYLON.serialize()
  85837. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  85838. __decorate([
  85839. BABYLON.serialize()
  85840. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  85841. __decorate([
  85842. BABYLON.serialize()
  85843. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  85844. __decorate([
  85845. BABYLON.serialize()
  85846. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  85847. __decorate([
  85848. BABYLON.serialize()
  85849. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  85850. __decorate([
  85851. BABYLON.serialize()
  85852. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  85853. __decorate([
  85854. BABYLON.serialize()
  85855. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  85856. __decorate([
  85857. BABYLON.serialize()
  85858. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  85859. __decorate([
  85860. BABYLON.serialize()
  85861. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  85862. __decorate([
  85863. BABYLON.serialize()
  85864. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  85865. __decorate([
  85866. BABYLON.serialize()
  85867. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  85868. __decorate([
  85869. BABYLON.serialize()
  85870. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  85871. __decorate([
  85872. BABYLON.serialize()
  85873. ], StandardRenderingPipeline.prototype, "samples", null);
  85874. return StandardRenderingPipeline;
  85875. }(BABYLON.PostProcessRenderPipeline));
  85876. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  85877. })(BABYLON || (BABYLON = {}));
  85878. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  85879. var BABYLON;
  85880. (function (BABYLON) {
  85881. /**
  85882. * Fxaa post process
  85883. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  85884. */
  85885. var FxaaPostProcess = /** @class */ (function (_super) {
  85886. __extends(FxaaPostProcess, _super);
  85887. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85888. if (camera === void 0) { camera = null; }
  85889. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85890. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  85891. var defines = _this._getDefines();
  85892. _this.updateEffect(defines);
  85893. _this.onApplyObservable.add(function (effect) {
  85894. var texelSize = _this.texelSize;
  85895. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  85896. });
  85897. return _this;
  85898. }
  85899. FxaaPostProcess.prototype._getDefines = function () {
  85900. var engine = this.getEngine();
  85901. if (!engine) {
  85902. return null;
  85903. }
  85904. var glInfo = engine.getGlInfo();
  85905. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  85906. return "#define MALI 1\n";
  85907. }
  85908. return null;
  85909. };
  85910. return FxaaPostProcess;
  85911. }(BABYLON.PostProcess));
  85912. BABYLON.FxaaPostProcess = FxaaPostProcess;
  85913. })(BABYLON || (BABYLON = {}));
  85914. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  85915. var BABYLON;
  85916. (function (BABYLON) {
  85917. /**
  85918. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  85919. */
  85920. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  85921. __extends(ChromaticAberrationPostProcess, _super);
  85922. /**
  85923. * Creates a new instance ChromaticAberrationPostProcess
  85924. * @param name The name of the effect.
  85925. * @param screenWidth The width of the screen to apply the effect on.
  85926. * @param screenHeight The height of the screen to apply the effect on.
  85927. * @param options The required width/height ratio to downsize to before computing the render pass.
  85928. * @param camera The camera to apply the render pass to.
  85929. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85930. * @param engine The engine which the post process will be applied. (default: current engine)
  85931. * @param reusable If the post process can be reused on the same frame. (default: false)
  85932. * @param textureType Type of textures used when performing the post process. (default: 0)
  85933. * @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)
  85934. */
  85935. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85936. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85937. if (blockCompilation === void 0) { blockCompilation = false; }
  85938. 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;
  85939. /**
  85940. * The amount of seperation of rgb channels (default: 30)
  85941. */
  85942. _this.aberrationAmount = 30;
  85943. /**
  85944. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  85945. */
  85946. _this.radialIntensity = 0;
  85947. /**
  85948. * 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))
  85949. */
  85950. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  85951. /**
  85952. * 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))
  85953. */
  85954. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  85955. _this.onApplyObservable.add(function (effect) {
  85956. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  85957. effect.setFloat('screen_width', screenWidth);
  85958. effect.setFloat('screen_height', screenHeight);
  85959. effect.setFloat('radialIntensity', _this.radialIntensity);
  85960. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  85961. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  85962. });
  85963. return _this;
  85964. }
  85965. return ChromaticAberrationPostProcess;
  85966. }(BABYLON.PostProcess));
  85967. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  85968. })(BABYLON || (BABYLON = {}));
  85969. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  85970. var BABYLON;
  85971. (function (BABYLON) {
  85972. /**
  85973. * The GrainPostProcess adds noise to the image at mid luminance levels
  85974. */
  85975. var GrainPostProcess = /** @class */ (function (_super) {
  85976. __extends(GrainPostProcess, _super);
  85977. /**
  85978. * Creates a new instance of @see GrainPostProcess
  85979. * @param name The name of the effect.
  85980. * @param options The required width/height ratio to downsize to before computing the render pass.
  85981. * @param camera The camera to apply the render pass to.
  85982. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85983. * @param engine The engine which the post process will be applied. (default: current engine)
  85984. * @param reusable If the post process can be reused on the same frame. (default: false)
  85985. * @param textureType Type of textures used when performing the post process. (default: 0)
  85986. * @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)
  85987. */
  85988. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85989. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85990. if (blockCompilation === void 0) { blockCompilation = false; }
  85991. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85992. /**
  85993. * The intensity of the grain added (default: 30)
  85994. */
  85995. _this.intensity = 30;
  85996. /**
  85997. * If the grain should be randomized on every frame
  85998. */
  85999. _this.animated = false;
  86000. _this.onApplyObservable.add(function (effect) {
  86001. effect.setFloat('intensity', _this.intensity);
  86002. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  86003. });
  86004. return _this;
  86005. }
  86006. return GrainPostProcess;
  86007. }(BABYLON.PostProcess));
  86008. BABYLON.GrainPostProcess = GrainPostProcess;
  86009. })(BABYLON || (BABYLON = {}));
  86010. //# sourceMappingURL=babylon.grainPostProcess.js.map
  86011. var BABYLON;
  86012. (function (BABYLON) {
  86013. /**
  86014. * The SharpenPostProcess applies a sharpen kernel to every pixel
  86015. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  86016. */
  86017. var SharpenPostProcess = /** @class */ (function (_super) {
  86018. __extends(SharpenPostProcess, _super);
  86019. /**
  86020. * Creates a new instance ConvolutionPostProcess
  86021. * @param name The name of the effect.
  86022. * @param options The required width/height ratio to downsize to before computing the render pass.
  86023. * @param camera The camera to apply the render pass to.
  86024. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86025. * @param engine The engine which the post process will be applied. (default: current engine)
  86026. * @param reusable If the post process can be reused on the same frame. (default: false)
  86027. * @param textureType Type of textures used when performing the post process. (default: 0)
  86028. * @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)
  86029. */
  86030. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86031. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86032. if (blockCompilation === void 0) { blockCompilation = false; }
  86033. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86034. /**
  86035. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  86036. */
  86037. _this.colorAmount = 1.0;
  86038. /**
  86039. * How much sharpness should be applied (default: 0.3)
  86040. */
  86041. _this.edgeAmount = 0.3;
  86042. _this.onApply = function (effect) {
  86043. effect.setFloat2("screenSize", _this.width, _this.height);
  86044. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  86045. };
  86046. return _this;
  86047. }
  86048. return SharpenPostProcess;
  86049. }(BABYLON.PostProcess));
  86050. BABYLON.SharpenPostProcess = SharpenPostProcess;
  86051. })(BABYLON || (BABYLON = {}));
  86052. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  86053. var BABYLON;
  86054. (function (BABYLON) {
  86055. /**
  86056. * The Blur Post Process which blurs an image based on a kernel and direction.
  86057. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  86058. */
  86059. var BlurPostProcess = /** @class */ (function (_super) {
  86060. __extends(BlurPostProcess, _super);
  86061. /**
  86062. * Creates a new instance BlurPostProcess
  86063. * @param name The name of the effect.
  86064. * @param direction The direction in which to blur the image.
  86065. * @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.
  86066. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  86067. * @param camera The camera to apply the render pass to.
  86068. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86069. * @param engine The engine which the post process will be applied. (default: current engine)
  86070. * @param reusable If the post process can be reused on the same frame. (default: false)
  86071. * @param textureType Type of textures used when performing the post process. (default: 0)
  86072. * @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)
  86073. */
  86074. function BlurPostProcess(name,
  86075. /** The direction in which to blur the image. */
  86076. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  86077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86078. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86079. if (defines === void 0) { defines = ""; }
  86080. if (blockCompilation === void 0) { blockCompilation = false; }
  86081. 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;
  86082. _this.direction = direction;
  86083. _this.blockCompilation = blockCompilation;
  86084. _this._packedFloat = false;
  86085. _this._staticDefines = "";
  86086. _this._staticDefines = defines;
  86087. _this.onApplyObservable.add(function (effect) {
  86088. if (_this._outputTexture) {
  86089. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  86090. }
  86091. else {
  86092. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  86093. }
  86094. });
  86095. _this.kernel = kernel;
  86096. return _this;
  86097. }
  86098. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  86099. /**
  86100. * Gets the length in pixels of the blur sample region
  86101. */
  86102. get: function () {
  86103. return this._idealKernel;
  86104. },
  86105. /**
  86106. * Sets the length in pixels of the blur sample region
  86107. */
  86108. set: function (v) {
  86109. if (this._idealKernel === v) {
  86110. return;
  86111. }
  86112. v = Math.max(v, 1);
  86113. this._idealKernel = v;
  86114. this._kernel = this._nearestBestKernel(v);
  86115. if (!this.blockCompilation) {
  86116. this._updateParameters();
  86117. }
  86118. },
  86119. enumerable: true,
  86120. configurable: true
  86121. });
  86122. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  86123. /**
  86124. * Gets wether or not the blur is unpacking/repacking floats
  86125. */
  86126. get: function () {
  86127. return this._packedFloat;
  86128. },
  86129. /**
  86130. * Sets wether or not the blur needs to unpack/repack floats
  86131. */
  86132. set: function (v) {
  86133. if (this._packedFloat === v) {
  86134. return;
  86135. }
  86136. this._packedFloat = v;
  86137. if (!this.blockCompilation) {
  86138. this._updateParameters();
  86139. }
  86140. },
  86141. enumerable: true,
  86142. configurable: true
  86143. });
  86144. /**
  86145. * Updates the effect with the current post process compile time values and recompiles the shader.
  86146. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86147. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86148. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86149. * @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
  86150. * @param onCompiled Called when the shader has been compiled.
  86151. * @param onError Called if there is an error when compiling a shader.
  86152. */
  86153. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86154. if (defines === void 0) { defines = null; }
  86155. if (uniforms === void 0) { uniforms = null; }
  86156. if (samplers === void 0) { samplers = null; }
  86157. this._updateParameters(onCompiled, onError);
  86158. };
  86159. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  86160. // Generate sampling offsets and weights
  86161. var N = this._kernel;
  86162. var centerIndex = (N - 1) / 2;
  86163. // Generate Gaussian sampling weights over kernel
  86164. var offsets = [];
  86165. var weights = [];
  86166. var totalWeight = 0;
  86167. for (var i = 0; i < N; i++) {
  86168. var u = i / (N - 1);
  86169. var w = this._gaussianWeight(u * 2.0 - 1);
  86170. offsets[i] = (i - centerIndex);
  86171. weights[i] = w;
  86172. totalWeight += w;
  86173. }
  86174. // Normalize weights
  86175. for (var i = 0; i < weights.length; i++) {
  86176. weights[i] /= totalWeight;
  86177. }
  86178. // Optimize: combine samples to take advantage of hardware linear sampling
  86179. // Walk from left to center, combining pairs (symmetrically)
  86180. var linearSamplingWeights = [];
  86181. var linearSamplingOffsets = [];
  86182. var linearSamplingMap = [];
  86183. for (var i = 0; i <= centerIndex; i += 2) {
  86184. var j = Math.min(i + 1, Math.floor(centerIndex));
  86185. var singleCenterSample = i === j;
  86186. if (singleCenterSample) {
  86187. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  86188. }
  86189. else {
  86190. var sharedCell = j === centerIndex;
  86191. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  86192. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  86193. if (offsetLinear === 0) {
  86194. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  86195. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  86196. }
  86197. else {
  86198. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  86199. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  86200. }
  86201. }
  86202. }
  86203. for (var i = 0; i < linearSamplingMap.length; i++) {
  86204. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  86205. linearSamplingWeights[i] = linearSamplingMap[i].w;
  86206. }
  86207. // Replace with optimized
  86208. offsets = linearSamplingOffsets;
  86209. weights = linearSamplingWeights;
  86210. // Generate shaders
  86211. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  86212. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  86213. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  86214. var defines = "";
  86215. defines += this._staticDefines;
  86216. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  86217. if (this._staticDefines.indexOf("DOF") != -1) {
  86218. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  86219. varyingCount--;
  86220. }
  86221. for (var i = 0; i < varyingCount; i++) {
  86222. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  86223. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  86224. }
  86225. var depCount = 0;
  86226. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  86227. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  86228. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  86229. depCount++;
  86230. }
  86231. if (this.packedFloat) {
  86232. defines += "#define PACKEDFLOAT 1";
  86233. }
  86234. this.blockCompilation = false;
  86235. _super.prototype.updateEffect.call(this, defines, null, null, {
  86236. varyingCount: varyingCount,
  86237. depCount: depCount
  86238. }, onCompiled, onError);
  86239. };
  86240. /**
  86241. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  86242. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  86243. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  86244. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  86245. * The gaps between physical kernels are compensated for in the weighting of the samples
  86246. * @param idealKernel Ideal blur kernel.
  86247. * @return Nearest best kernel.
  86248. */
  86249. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  86250. var v = Math.round(idealKernel);
  86251. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  86252. var k = _a[_i];
  86253. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  86254. return Math.max(k, 3);
  86255. }
  86256. }
  86257. return Math.max(v, 3);
  86258. };
  86259. /**
  86260. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  86261. * @param x The point on the Gaussian distribution to sample.
  86262. * @return the value of the Gaussian function at x.
  86263. */
  86264. BlurPostProcess.prototype._gaussianWeight = function (x) {
  86265. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  86266. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  86267. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  86268. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  86269. // truncated at around 1.3% of peak strength.
  86270. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  86271. var sigma = (1 / 3);
  86272. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  86273. var exponent = -((x * x) / (2.0 * sigma * sigma));
  86274. var weight = (1.0 / denominator) * Math.exp(exponent);
  86275. return weight;
  86276. };
  86277. /**
  86278. * Generates a string that can be used as a floating point number in GLSL.
  86279. * @param x Value to print.
  86280. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  86281. * @return GLSL float string.
  86282. */
  86283. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  86284. if (decimalFigures === void 0) { decimalFigures = 8; }
  86285. return x.toFixed(decimalFigures).replace(/0+$/, '');
  86286. };
  86287. return BlurPostProcess;
  86288. }(BABYLON.PostProcess));
  86289. BABYLON.BlurPostProcess = BlurPostProcess;
  86290. })(BABYLON || (BABYLON = {}));
  86291. //# sourceMappingURL=babylon.blurPostProcess.js.map
  86292. var BABYLON;
  86293. (function (BABYLON) {
  86294. /**
  86295. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  86296. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  86297. * based on samples that have a large difference in distance than the center pixel.
  86298. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86299. */
  86300. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  86301. __extends(DepthOfFieldBlurPostProcess, _super);
  86302. /**
  86303. * Creates a new instance CircleOfConfusionPostProcess
  86304. * @param name The name of the effect.
  86305. * @param scene The scene the effect belongs to.
  86306. * @param direction The direction the blur should be applied.
  86307. * @param kernel The size of the kernel used to blur.
  86308. * @param options The required width/height ratio to downsize to before computing the render pass.
  86309. * @param camera The camera to apply the render pass to.
  86310. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  86311. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  86312. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86313. * @param engine The engine which the post process will be applied. (default: current engine)
  86314. * @param reusable If the post process can be reused on the same frame. (default: false)
  86315. * @param textureType Type of textures used when performing the post process. (default: 0)
  86316. * @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)
  86317. */
  86318. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  86319. if (imageToBlur === void 0) { imageToBlur = null; }
  86320. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86321. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86322. if (blockCompilation === void 0) { blockCompilation = false; }
  86323. 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;
  86324. _this.direction = direction;
  86325. _this.onApplyObservable.add(function (effect) {
  86326. if (imageToBlur != null) {
  86327. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  86328. }
  86329. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86330. if (scene.activeCamera) {
  86331. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86332. }
  86333. });
  86334. return _this;
  86335. }
  86336. return DepthOfFieldBlurPostProcess;
  86337. }(BABYLON.BlurPostProcess));
  86338. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  86339. })(BABYLON || (BABYLON = {}));
  86340. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  86341. var BABYLON;
  86342. (function (BABYLON) {
  86343. /**
  86344. * Options to be set when merging outputs from the default pipeline.
  86345. */
  86346. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  86347. function DepthOfFieldMergePostProcessOptions() {
  86348. }
  86349. return DepthOfFieldMergePostProcessOptions;
  86350. }());
  86351. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  86352. /**
  86353. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86354. */
  86355. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  86356. __extends(DepthOfFieldMergePostProcess, _super);
  86357. /**
  86358. * Creates a new instance of DepthOfFieldMergePostProcess
  86359. * @param name The name of the effect.
  86360. * @param originalFromInput Post process which's input will be used for the merge.
  86361. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  86362. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  86363. * @param options The required width/height ratio to downsize to before computing the render pass.
  86364. * @param camera The camera to apply the render pass to.
  86365. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86366. * @param engine The engine which the post process will be applied. (default: current engine)
  86367. * @param reusable If the post process can be reused on the same frame. (default: false)
  86368. * @param textureType Type of textures used when performing the post process. (default: 0)
  86369. * @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)
  86370. */
  86371. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86372. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86373. if (blockCompilation === void 0) { blockCompilation = false; }
  86374. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86375. _this.blurSteps = blurSteps;
  86376. _this.onApplyObservable.add(function (effect) {
  86377. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86378. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86379. blurSteps.forEach(function (step, index) {
  86380. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  86381. });
  86382. });
  86383. if (!blockCompilation) {
  86384. _this.updateEffect();
  86385. }
  86386. return _this;
  86387. }
  86388. /**
  86389. * Updates the effect with the current post process compile time values and recompiles the shader.
  86390. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86391. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86392. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86393. * @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
  86394. * @param onCompiled Called when the shader has been compiled.
  86395. * @param onError Called if there is an error when compiling a shader.
  86396. */
  86397. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86398. if (defines === void 0) { defines = null; }
  86399. if (uniforms === void 0) { uniforms = null; }
  86400. if (samplers === void 0) { samplers = null; }
  86401. if (!defines) {
  86402. defines = "";
  86403. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  86404. }
  86405. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  86406. };
  86407. return DepthOfFieldMergePostProcess;
  86408. }(BABYLON.PostProcess));
  86409. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  86410. })(BABYLON || (BABYLON = {}));
  86411. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  86412. var BABYLON;
  86413. (function (BABYLON) {
  86414. /**
  86415. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  86416. */
  86417. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  86418. __extends(CircleOfConfusionPostProcess, _super);
  86419. /**
  86420. * Creates a new instance CircleOfConfusionPostProcess
  86421. * @param name The name of the effect.
  86422. * @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.
  86423. * @param options The required width/height ratio to downsize to before computing the render pass.
  86424. * @param camera The camera to apply the render pass to.
  86425. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86426. * @param engine The engine which the post process will be applied. (default: current engine)
  86427. * @param reusable If the post process can be reused on the same frame. (default: false)
  86428. * @param textureType Type of textures used when performing the post process. (default: 0)
  86429. * @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)
  86430. */
  86431. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86432. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86433. if (blockCompilation === void 0) { blockCompilation = false; }
  86434. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86435. /**
  86436. * 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.
  86437. */
  86438. _this.lensSize = 50;
  86439. /**
  86440. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86441. */
  86442. _this.fStop = 1.4;
  86443. /**
  86444. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86445. */
  86446. _this.focusDistance = 2000;
  86447. /**
  86448. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  86449. */
  86450. _this.focalLength = 50;
  86451. _this._depthTexture = null;
  86452. _this._depthTexture = depthTexture;
  86453. _this.onApplyObservable.add(function (effect) {
  86454. if (!_this._depthTexture) {
  86455. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  86456. return;
  86457. }
  86458. effect.setTexture("depthSampler", _this._depthTexture);
  86459. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  86460. var aperture = _this.lensSize / _this.fStop;
  86461. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  86462. effect.setFloat('focusDistance', _this.focusDistance);
  86463. effect.setFloat('cocPrecalculation', cocPrecalculation);
  86464. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  86465. });
  86466. return _this;
  86467. }
  86468. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  86469. /**
  86470. * 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.
  86471. */
  86472. set: function (value) {
  86473. this._depthTexture = value;
  86474. },
  86475. enumerable: true,
  86476. configurable: true
  86477. });
  86478. return CircleOfConfusionPostProcess;
  86479. }(BABYLON.PostProcess));
  86480. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  86481. })(BABYLON || (BABYLON = {}));
  86482. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  86483. var BABYLON;
  86484. (function (BABYLON) {
  86485. /**
  86486. * Specifies the level of max blur that should be applied when using the depth of field effect
  86487. */
  86488. var DepthOfFieldEffectBlurLevel;
  86489. (function (DepthOfFieldEffectBlurLevel) {
  86490. /**
  86491. * Subtle blur
  86492. */
  86493. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  86494. /**
  86495. * Medium blur
  86496. */
  86497. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  86498. /**
  86499. * Large blur
  86500. */
  86501. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  86502. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  86503. /**
  86504. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  86505. */
  86506. var DepthOfFieldEffect = /** @class */ (function (_super) {
  86507. __extends(DepthOfFieldEffect, _super);
  86508. /**
  86509. * Creates a new instance DepthOfFieldEffect
  86510. * @param scene The scene the effect belongs to.
  86511. * @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.
  86512. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86513. * @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)
  86514. */
  86515. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  86516. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  86517. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86518. if (blockCompilation === void 0) { blockCompilation = false; }
  86519. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  86520. return _this._effects;
  86521. }, true) || this;
  86522. /**
  86523. * @hidden Internal post processes in depth of field effect
  86524. */
  86525. _this._effects = [];
  86526. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  86527. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86528. // 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)
  86529. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  86530. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86531. _this._depthOfFieldBlurY = [];
  86532. _this._depthOfFieldBlurX = [];
  86533. var blurCount = 1;
  86534. var kernelSize = 15;
  86535. switch (blurLevel) {
  86536. case DepthOfFieldEffectBlurLevel.High: {
  86537. blurCount = 3;
  86538. kernelSize = 51;
  86539. break;
  86540. }
  86541. case DepthOfFieldEffectBlurLevel.Medium: {
  86542. blurCount = 2;
  86543. kernelSize = 31;
  86544. break;
  86545. }
  86546. default: {
  86547. kernelSize = 15;
  86548. blurCount = 1;
  86549. break;
  86550. }
  86551. }
  86552. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  86553. var ratio = 1.0;
  86554. for (var i = 0; i < blurCount; i++) {
  86555. 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);
  86556. blurY.autoClear = false;
  86557. ratio = 0.75 / Math.pow(2, i);
  86558. 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);
  86559. blurX.autoClear = false;
  86560. _this._depthOfFieldBlurY.push(blurY);
  86561. _this._depthOfFieldBlurX.push(blurX);
  86562. }
  86563. // Set all post processes on the effect.
  86564. _this._effects = [_this._circleOfConfusion];
  86565. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  86566. _this._effects.push(_this._depthOfFieldBlurY[i]);
  86567. _this._effects.push(_this._depthOfFieldBlurX[i]);
  86568. }
  86569. // Merge blurred images with original image based on circleOfConfusion
  86570. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86571. _this._dofMerge.autoClear = false;
  86572. _this._effects.push(_this._dofMerge);
  86573. return _this;
  86574. }
  86575. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  86576. get: function () {
  86577. return this._circleOfConfusion.focalLength;
  86578. },
  86579. /**
  86580. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  86581. */
  86582. set: function (value) {
  86583. this._circleOfConfusion.focalLength = value;
  86584. },
  86585. enumerable: true,
  86586. configurable: true
  86587. });
  86588. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  86589. get: function () {
  86590. return this._circleOfConfusion.fStop;
  86591. },
  86592. /**
  86593. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86594. */
  86595. set: function (value) {
  86596. this._circleOfConfusion.fStop = value;
  86597. },
  86598. enumerable: true,
  86599. configurable: true
  86600. });
  86601. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  86602. get: function () {
  86603. return this._circleOfConfusion.focusDistance;
  86604. },
  86605. /**
  86606. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86607. */
  86608. set: function (value) {
  86609. this._circleOfConfusion.focusDistance = value;
  86610. },
  86611. enumerable: true,
  86612. configurable: true
  86613. });
  86614. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  86615. get: function () {
  86616. return this._circleOfConfusion.lensSize;
  86617. },
  86618. /**
  86619. * 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.
  86620. */
  86621. set: function (value) {
  86622. this._circleOfConfusion.lensSize = value;
  86623. },
  86624. enumerable: true,
  86625. configurable: true
  86626. });
  86627. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  86628. /**
  86629. * 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.
  86630. */
  86631. set: function (value) {
  86632. this._circleOfConfusion.depthTexture = value;
  86633. },
  86634. enumerable: true,
  86635. configurable: true
  86636. });
  86637. /**
  86638. * Disposes each of the internal effects for a given camera.
  86639. * @param camera The camera to dispose the effect on.
  86640. */
  86641. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  86642. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86643. this._effects[effectIndex].dispose(camera);
  86644. }
  86645. };
  86646. /**
  86647. * @hidden Internal
  86648. */
  86649. DepthOfFieldEffect.prototype._updateEffects = function () {
  86650. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86651. this._effects[effectIndex].updateEffect();
  86652. }
  86653. };
  86654. /**
  86655. * Internal
  86656. * @returns if all the contained post processes are ready.
  86657. * @hidden
  86658. */
  86659. DepthOfFieldEffect.prototype._isReady = function () {
  86660. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86661. if (!this._effects[effectIndex].isReady()) {
  86662. return false;
  86663. }
  86664. }
  86665. return true;
  86666. };
  86667. return DepthOfFieldEffect;
  86668. }(BABYLON.PostProcessRenderEffect));
  86669. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  86670. })(BABYLON || (BABYLON = {}));
  86671. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  86672. var BABYLON;
  86673. (function (BABYLON) {
  86674. /**
  86675. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86676. */
  86677. var BloomMergePostProcess = /** @class */ (function (_super) {
  86678. __extends(BloomMergePostProcess, _super);
  86679. /**
  86680. * Creates a new instance of @see BloomMergePostProcess
  86681. * @param name The name of the effect.
  86682. * @param originalFromInput Post process which's input will be used for the merge.
  86683. * @param blurred Blurred highlights post process which's output will be used.
  86684. * @param weight Weight of the bloom to be added to the original input.
  86685. * @param options The required width/height ratio to downsize to before computing the render pass.
  86686. * @param camera The camera to apply the render pass to.
  86687. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86688. * @param engine The engine which the post process will be applied. (default: current engine)
  86689. * @param reusable If the post process can be reused on the same frame. (default: false)
  86690. * @param textureType Type of textures used when performing the post process. (default: 0)
  86691. * @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)
  86692. */
  86693. function BloomMergePostProcess(name, originalFromInput, blurred,
  86694. /** Weight of the bloom to be added to the original input. */
  86695. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86696. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86697. if (blockCompilation === void 0) { blockCompilation = false; }
  86698. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86699. _this.weight = weight;
  86700. _this.onApplyObservable.add(function (effect) {
  86701. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86702. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  86703. effect.setFloat("bloomWeight", _this.weight);
  86704. });
  86705. if (!blockCompilation) {
  86706. _this.updateEffect();
  86707. }
  86708. return _this;
  86709. }
  86710. return BloomMergePostProcess;
  86711. }(BABYLON.PostProcess));
  86712. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  86713. })(BABYLON || (BABYLON = {}));
  86714. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  86715. var BABYLON;
  86716. (function (BABYLON) {
  86717. /**
  86718. * 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.
  86719. */
  86720. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  86721. __extends(ExtractHighlightsPostProcess, _super);
  86722. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86723. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86724. if (blockCompilation === void 0) { blockCompilation = false; }
  86725. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86726. /**
  86727. * The luminance threshold, pixels below this value will be set to black.
  86728. */
  86729. _this.threshold = 0.9;
  86730. /** @hidden */
  86731. _this._exposure = 1;
  86732. /**
  86733. * Post process which has the input texture to be used when performing highlight extraction
  86734. * @hidden
  86735. */
  86736. _this._inputPostProcess = null;
  86737. _this.onApplyObservable.add(function (effect) {
  86738. if (_this._inputPostProcess) {
  86739. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  86740. }
  86741. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  86742. effect.setFloat('exposure', _this._exposure);
  86743. });
  86744. return _this;
  86745. }
  86746. return ExtractHighlightsPostProcess;
  86747. }(BABYLON.PostProcess));
  86748. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  86749. })(BABYLON || (BABYLON = {}));
  86750. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  86751. var BABYLON;
  86752. (function (BABYLON) {
  86753. /**
  86754. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  86755. */
  86756. var BloomEffect = /** @class */ (function (_super) {
  86757. __extends(BloomEffect, _super);
  86758. /**
  86759. * Creates a new instance of @see BloomEffect
  86760. * @param scene The scene the effect belongs to.
  86761. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  86762. * @param bloomKernel The size of the kernel to be used when applying the blur.
  86763. * @param bloomWeight The the strength of bloom.
  86764. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86765. * @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)
  86766. */
  86767. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  86768. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86769. if (blockCompilation === void 0) { blockCompilation = false; }
  86770. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  86771. return _this._effects;
  86772. }, true) || this;
  86773. _this.bloomScale = bloomScale;
  86774. /**
  86775. * @hidden Internal
  86776. */
  86777. _this._effects = [];
  86778. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86779. _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);
  86780. _this._blurX.alwaysForcePOT = true;
  86781. _this._blurX.autoClear = false;
  86782. _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);
  86783. _this._blurY.alwaysForcePOT = true;
  86784. _this._blurY.autoClear = false;
  86785. _this.kernel = bloomKernel;
  86786. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  86787. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86788. _this._merge.autoClear = false;
  86789. _this._effects.push(_this._merge);
  86790. return _this;
  86791. }
  86792. Object.defineProperty(BloomEffect.prototype, "threshold", {
  86793. /**
  86794. * The luminance threshold to find bright areas of the image to bloom.
  86795. */
  86796. get: function () {
  86797. return this._downscale.threshold;
  86798. },
  86799. set: function (value) {
  86800. this._downscale.threshold = value;
  86801. },
  86802. enumerable: true,
  86803. configurable: true
  86804. });
  86805. Object.defineProperty(BloomEffect.prototype, "weight", {
  86806. /**
  86807. * The strength of the bloom.
  86808. */
  86809. get: function () {
  86810. return this._merge.weight;
  86811. },
  86812. set: function (value) {
  86813. this._merge.weight = value;
  86814. },
  86815. enumerable: true,
  86816. configurable: true
  86817. });
  86818. Object.defineProperty(BloomEffect.prototype, "kernel", {
  86819. /**
  86820. * Specifies the size of the bloom blur kernel, relative to the final output size
  86821. */
  86822. get: function () {
  86823. return this._blurX.kernel / this.bloomScale;
  86824. },
  86825. set: function (value) {
  86826. this._blurX.kernel = value * this.bloomScale;
  86827. this._blurY.kernel = value * this.bloomScale;
  86828. },
  86829. enumerable: true,
  86830. configurable: true
  86831. });
  86832. /**
  86833. * Disposes each of the internal effects for a given camera.
  86834. * @param camera The camera to dispose the effect on.
  86835. */
  86836. BloomEffect.prototype.disposeEffects = function (camera) {
  86837. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86838. this._effects[effectIndex].dispose(camera);
  86839. }
  86840. };
  86841. /**
  86842. * @hidden Internal
  86843. */
  86844. BloomEffect.prototype._updateEffects = function () {
  86845. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86846. this._effects[effectIndex].updateEffect();
  86847. }
  86848. };
  86849. /**
  86850. * Internal
  86851. * @returns if all the contained post processes are ready.
  86852. * @hidden
  86853. */
  86854. BloomEffect.prototype._isReady = function () {
  86855. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86856. if (!this._effects[effectIndex].isReady()) {
  86857. return false;
  86858. }
  86859. }
  86860. return true;
  86861. };
  86862. return BloomEffect;
  86863. }(BABYLON.PostProcessRenderEffect));
  86864. BABYLON.BloomEffect = BloomEffect;
  86865. })(BABYLON || (BABYLON = {}));
  86866. //# sourceMappingURL=babylon.bloomEffect.js.map
  86867. var BABYLON;
  86868. (function (BABYLON) {
  86869. /**
  86870. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  86871. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  86872. */
  86873. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  86874. __extends(DefaultRenderingPipeline, _super);
  86875. /**
  86876. * @constructor
  86877. * @param name - The rendering pipeline name (default: "")
  86878. * @param hdr - If high dynamic range textures should be used (default: true)
  86879. * @param scene - The scene linked to this pipeline (default: the last created scene)
  86880. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  86881. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  86882. */
  86883. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  86884. if (name === void 0) { name = ""; }
  86885. if (hdr === void 0) { hdr = true; }
  86886. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  86887. if (automaticBuild === void 0) { automaticBuild = true; }
  86888. var _this = _super.call(this, scene.getEngine(), name) || this;
  86889. _this._camerasToBeAttached = [];
  86890. /**
  86891. * ID of the sharpen post process,
  86892. */
  86893. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  86894. /**
  86895. * @ignore
  86896. * ID of the image processing post process;
  86897. */
  86898. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  86899. /**
  86900. * @ignore
  86901. * ID of the Fast Approximate Anti-Aliasing post process;
  86902. */
  86903. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  86904. /**
  86905. * ID of the chromatic aberration post process,
  86906. */
  86907. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  86908. /**
  86909. * ID of the grain post process
  86910. */
  86911. _this.GrainPostProcessId = "GrainPostProcessEffect";
  86912. /**
  86913. * Glow post process which adds a glow to emmisive areas of the image
  86914. */
  86915. _this._glowLayer = null;
  86916. /**
  86917. * Animations which can be used to tweak settings over a period of time
  86918. */
  86919. _this.animations = [];
  86920. _this._imageProcessingConfigurationObserver = null;
  86921. // Values
  86922. _this._sharpenEnabled = false;
  86923. _this._bloomEnabled = false;
  86924. _this._depthOfFieldEnabled = false;
  86925. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  86926. _this._fxaaEnabled = false;
  86927. _this._imageProcessingEnabled = true;
  86928. _this._bloomScale = 0.5;
  86929. _this._chromaticAberrationEnabled = false;
  86930. _this._grainEnabled = false;
  86931. _this._buildAllowed = true;
  86932. _this._resizeObserver = null;
  86933. _this._hardwareScaleLevel = 1.0;
  86934. _this._bloomKernel = 64;
  86935. /**
  86936. * Specifies the weight of the bloom in the final rendering
  86937. */
  86938. _this._bloomWeight = 0.15;
  86939. /**
  86940. * Specifies the luma threshold for the area that will be blurred by the bloom
  86941. */
  86942. _this._bloomThreshold = 0.9;
  86943. _this._samples = 1;
  86944. _this._hasCleared = false;
  86945. _this._prevPostProcess = null;
  86946. _this._prevPrevPostProcess = null;
  86947. _this._depthOfFieldSceneObserver = null;
  86948. _this._cameras = cameras || scene.cameras;
  86949. _this._cameras = _this._cameras.slice();
  86950. _this._camerasToBeAttached = _this._cameras.slice();
  86951. _this._buildAllowed = automaticBuild;
  86952. // Initialize
  86953. _this._scene = scene;
  86954. var caps = _this._scene.getEngine().getCaps();
  86955. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  86956. // Misc
  86957. if (_this._hdr) {
  86958. if (caps.textureHalfFloatRender) {
  86959. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86960. }
  86961. else if (caps.textureFloatRender) {
  86962. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86963. }
  86964. }
  86965. else {
  86966. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86967. }
  86968. // Attach
  86969. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86970. var engine = _this._scene.getEngine();
  86971. // Create post processes before hand so they can be modified before enabled.
  86972. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  86973. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86974. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  86975. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  86976. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  86977. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86978. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  86979. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86980. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  86981. _this._resizeObserver = engine.onResizeObservable.add(function () {
  86982. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  86983. _this.bloomKernel = _this.bloomKernel;
  86984. });
  86985. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  86986. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  86987. });
  86988. _this._buildPipeline();
  86989. return _this;
  86990. }
  86991. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  86992. get: function () {
  86993. return this._sharpenEnabled;
  86994. },
  86995. /**
  86996. * Enable or disable the sharpen process from the pipeline
  86997. */
  86998. set: function (enabled) {
  86999. if (this._sharpenEnabled === enabled) {
  87000. return;
  87001. }
  87002. this._sharpenEnabled = enabled;
  87003. this._buildPipeline();
  87004. },
  87005. enumerable: true,
  87006. configurable: true
  87007. });
  87008. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  87009. /**
  87010. * Specifies the size of the bloom blur kernel, relative to the final output size
  87011. */
  87012. get: function () {
  87013. return this._bloomKernel;
  87014. },
  87015. set: function (value) {
  87016. this._bloomKernel = value;
  87017. this.bloom.kernel = value / this._hardwareScaleLevel;
  87018. },
  87019. enumerable: true,
  87020. configurable: true
  87021. });
  87022. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  87023. get: function () {
  87024. return this._bloomWeight;
  87025. },
  87026. /**
  87027. * The strength of the bloom.
  87028. */
  87029. set: function (value) {
  87030. if (this._bloomWeight === value) {
  87031. return;
  87032. }
  87033. this.bloom.weight = value;
  87034. this._bloomWeight = value;
  87035. },
  87036. enumerable: true,
  87037. configurable: true
  87038. });
  87039. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  87040. get: function () {
  87041. return this._bloomThreshold;
  87042. },
  87043. /**
  87044. * The strength of the bloom.
  87045. */
  87046. set: function (value) {
  87047. if (this._bloomThreshold === value) {
  87048. return;
  87049. }
  87050. this.bloom.threshold = value;
  87051. this._bloomThreshold = value;
  87052. },
  87053. enumerable: true,
  87054. configurable: true
  87055. });
  87056. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  87057. get: function () {
  87058. return this._bloomScale;
  87059. },
  87060. /**
  87061. * The scale of the bloom, lower value will provide better performance.
  87062. */
  87063. set: function (value) {
  87064. if (this._bloomScale === value) {
  87065. return;
  87066. }
  87067. this._bloomScale = value;
  87068. // recreate bloom and dispose old as this setting is not dynamic
  87069. this._rebuildBloom();
  87070. this._buildPipeline();
  87071. },
  87072. enumerable: true,
  87073. configurable: true
  87074. });
  87075. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  87076. get: function () {
  87077. return this._bloomEnabled;
  87078. },
  87079. /**
  87080. * Enable or disable the bloom from the pipeline
  87081. */
  87082. set: function (enabled) {
  87083. if (this._bloomEnabled === enabled) {
  87084. return;
  87085. }
  87086. this._bloomEnabled = enabled;
  87087. this._buildPipeline();
  87088. },
  87089. enumerable: true,
  87090. configurable: true
  87091. });
  87092. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  87093. // recreate bloom and dispose old as this setting is not dynamic
  87094. var oldBloom = this.bloom;
  87095. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  87096. this.bloom.threshold = oldBloom.threshold;
  87097. for (var i = 0; i < this._cameras.length; i++) {
  87098. oldBloom.disposeEffects(this._cameras[i]);
  87099. }
  87100. };
  87101. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  87102. /**
  87103. * If the depth of field is enabled.
  87104. */
  87105. get: function () {
  87106. return this._depthOfFieldEnabled;
  87107. },
  87108. set: function (enabled) {
  87109. if (this._depthOfFieldEnabled === enabled) {
  87110. return;
  87111. }
  87112. this._depthOfFieldEnabled = enabled;
  87113. this._buildPipeline();
  87114. },
  87115. enumerable: true,
  87116. configurable: true
  87117. });
  87118. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  87119. /**
  87120. * Blur level of the depth of field effect. (Higher blur will effect performance)
  87121. */
  87122. get: function () {
  87123. return this._depthOfFieldBlurLevel;
  87124. },
  87125. set: function (value) {
  87126. if (this._depthOfFieldBlurLevel === value) {
  87127. return;
  87128. }
  87129. this._depthOfFieldBlurLevel = value;
  87130. // recreate dof and dispose old as this setting is not dynamic
  87131. var oldDof = this.depthOfField;
  87132. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  87133. this.depthOfField.focalLength = oldDof.focalLength;
  87134. this.depthOfField.focusDistance = oldDof.focusDistance;
  87135. this.depthOfField.fStop = oldDof.fStop;
  87136. this.depthOfField.lensSize = oldDof.lensSize;
  87137. for (var i = 0; i < this._cameras.length; i++) {
  87138. oldDof.disposeEffects(this._cameras[i]);
  87139. }
  87140. this._buildPipeline();
  87141. },
  87142. enumerable: true,
  87143. configurable: true
  87144. });
  87145. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  87146. get: function () {
  87147. return this._fxaaEnabled;
  87148. },
  87149. /**
  87150. * If the anti aliasing is enabled.
  87151. */
  87152. set: function (enabled) {
  87153. if (this._fxaaEnabled === enabled) {
  87154. return;
  87155. }
  87156. this._fxaaEnabled = enabled;
  87157. this._buildPipeline();
  87158. },
  87159. enumerable: true,
  87160. configurable: true
  87161. });
  87162. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  87163. get: function () {
  87164. return this._samples;
  87165. },
  87166. /**
  87167. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  87168. */
  87169. set: function (sampleCount) {
  87170. if (this._samples === sampleCount) {
  87171. return;
  87172. }
  87173. this._samples = sampleCount;
  87174. this._buildPipeline();
  87175. },
  87176. enumerable: true,
  87177. configurable: true
  87178. });
  87179. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  87180. get: function () {
  87181. return this._imageProcessingEnabled;
  87182. },
  87183. /**
  87184. * If image processing is enabled.
  87185. */
  87186. set: function (enabled) {
  87187. if (this._imageProcessingEnabled === enabled) {
  87188. return;
  87189. }
  87190. this._imageProcessingEnabled = enabled;
  87191. this._buildPipeline();
  87192. },
  87193. enumerable: true,
  87194. configurable: true
  87195. });
  87196. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  87197. get: function () {
  87198. return this._glowLayer == null;
  87199. },
  87200. /**
  87201. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  87202. */
  87203. set: function (enabled) {
  87204. if (enabled && !this._glowLayer) {
  87205. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  87206. }
  87207. else if (!enabled && this._glowLayer) {
  87208. this._glowLayer.dispose();
  87209. this._glowLayer = null;
  87210. }
  87211. },
  87212. enumerable: true,
  87213. configurable: true
  87214. });
  87215. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  87216. get: function () {
  87217. return this._chromaticAberrationEnabled;
  87218. },
  87219. /**
  87220. * Enable or disable the chromaticAberration process from the pipeline
  87221. */
  87222. set: function (enabled) {
  87223. if (this._chromaticAberrationEnabled === enabled) {
  87224. return;
  87225. }
  87226. this._chromaticAberrationEnabled = enabled;
  87227. this._buildPipeline();
  87228. },
  87229. enumerable: true,
  87230. configurable: true
  87231. });
  87232. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  87233. get: function () {
  87234. return this._grainEnabled;
  87235. },
  87236. /**
  87237. * Enable or disable the grain process from the pipeline
  87238. */
  87239. set: function (enabled) {
  87240. if (this._grainEnabled === enabled) {
  87241. return;
  87242. }
  87243. this._grainEnabled = enabled;
  87244. this._buildPipeline();
  87245. },
  87246. enumerable: true,
  87247. configurable: true
  87248. });
  87249. /**
  87250. * Force the compilation of the entire pipeline.
  87251. */
  87252. DefaultRenderingPipeline.prototype.prepare = function () {
  87253. var previousState = this._buildAllowed;
  87254. this._buildAllowed = true;
  87255. this._buildPipeline();
  87256. this._buildAllowed = previousState;
  87257. };
  87258. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  87259. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  87260. if (this._hasCleared) {
  87261. postProcess.autoClear = false;
  87262. }
  87263. else {
  87264. postProcess.autoClear = true;
  87265. this._scene.autoClear = false;
  87266. this._hasCleared = true;
  87267. }
  87268. if (!skipTextureSharing) {
  87269. if (this._prevPrevPostProcess) {
  87270. postProcess.shareOutputWith(this._prevPrevPostProcess);
  87271. }
  87272. else {
  87273. postProcess.useOwnOutput();
  87274. }
  87275. if (this._prevPostProcess) {
  87276. this._prevPrevPostProcess = this._prevPostProcess;
  87277. }
  87278. this._prevPostProcess = postProcess;
  87279. }
  87280. };
  87281. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  87282. var _this = this;
  87283. if (!this._buildAllowed) {
  87284. return;
  87285. }
  87286. this._scene.autoClear = true;
  87287. var engine = this._scene.getEngine();
  87288. this._disposePostProcesses();
  87289. if (this._cameras !== null) {
  87290. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87291. // get back cameras to be used to reattach pipeline
  87292. this._cameras = this._camerasToBeAttached.slice();
  87293. }
  87294. this._reset();
  87295. this._prevPostProcess = null;
  87296. this._prevPrevPostProcess = null;
  87297. this._hasCleared = false;
  87298. if (this.depthOfFieldEnabled) {
  87299. // Multi camera suport
  87300. if (this._cameras.length > 1) {
  87301. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  87302. var camera = _a[_i];
  87303. var depthRenderer = this._scene.enableDepthRenderer(camera);
  87304. depthRenderer.useOnlyInActiveCamera = true;
  87305. }
  87306. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  87307. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  87308. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  87309. }
  87310. });
  87311. }
  87312. else {
  87313. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87314. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  87315. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  87316. }
  87317. if (!this.depthOfField._isReady()) {
  87318. this.depthOfField._updateEffects();
  87319. }
  87320. this.addEffect(this.depthOfField);
  87321. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  87322. }
  87323. else {
  87324. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87325. }
  87326. if (this.bloomEnabled) {
  87327. if (!this.bloom._isReady()) {
  87328. this.bloom._updateEffects();
  87329. }
  87330. this.addEffect(this.bloom);
  87331. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  87332. }
  87333. if (this._imageProcessingEnabled) {
  87334. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87335. if (this._hdr) {
  87336. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  87337. this._setAutoClearAndTextureSharing(this.imageProcessing);
  87338. }
  87339. else {
  87340. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  87341. }
  87342. }
  87343. if (this.sharpenEnabled) {
  87344. if (!this.sharpen.isReady()) {
  87345. this.sharpen.updateEffect();
  87346. }
  87347. this.addEffect(this._sharpenEffect);
  87348. this._setAutoClearAndTextureSharing(this.sharpen);
  87349. }
  87350. if (this.grainEnabled) {
  87351. if (!this.grain.isReady()) {
  87352. this.grain.updateEffect();
  87353. }
  87354. this.addEffect(this._grainEffect);
  87355. this._setAutoClearAndTextureSharing(this.grain);
  87356. }
  87357. if (this.chromaticAberrationEnabled) {
  87358. if (!this.chromaticAberration.isReady()) {
  87359. this.chromaticAberration.updateEffect();
  87360. }
  87361. this.addEffect(this._chromaticAberrationEffect);
  87362. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  87363. }
  87364. if (this.fxaaEnabled) {
  87365. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87366. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  87367. this._setAutoClearAndTextureSharing(this.fxaa, true);
  87368. }
  87369. if (this._cameras !== null) {
  87370. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87371. }
  87372. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  87373. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87374. }
  87375. };
  87376. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  87377. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  87378. for (var i = 0; i < this._cameras.length; i++) {
  87379. var camera = this._cameras[i];
  87380. if (this.imageProcessing) {
  87381. this.imageProcessing.dispose(camera);
  87382. }
  87383. if (this.fxaa) {
  87384. this.fxaa.dispose(camera);
  87385. }
  87386. // These are created in the constructor and should not be disposed on every pipeline change
  87387. if (disposeNonRecreated) {
  87388. if (this.sharpen) {
  87389. this.sharpen.dispose(camera);
  87390. }
  87391. if (this.depthOfField) {
  87392. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87393. this.depthOfField.disposeEffects(camera);
  87394. }
  87395. if (this.bloom) {
  87396. this.bloom.disposeEffects(camera);
  87397. }
  87398. if (this.chromaticAberration) {
  87399. this.chromaticAberration.dispose(camera);
  87400. }
  87401. if (this.grain) {
  87402. this.grain.dispose(camera);
  87403. }
  87404. if (this._glowLayer) {
  87405. this._glowLayer.dispose();
  87406. }
  87407. }
  87408. }
  87409. this.imageProcessing = null;
  87410. this.fxaa = null;
  87411. if (disposeNonRecreated) {
  87412. this.sharpen = null;
  87413. this._sharpenEffect = null;
  87414. this.depthOfField = null;
  87415. this.bloom = null;
  87416. this.chromaticAberration = null;
  87417. this._chromaticAberrationEffect = null;
  87418. this.grain = null;
  87419. this._grainEffect = null;
  87420. this._glowLayer = null;
  87421. }
  87422. };
  87423. /**
  87424. * Adds a camera to the pipeline
  87425. * @param camera the camera to be added
  87426. */
  87427. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  87428. this._camerasToBeAttached.push(camera);
  87429. this._buildPipeline();
  87430. };
  87431. /**
  87432. * Removes a camera from the pipeline
  87433. * @param camera the camera to remove
  87434. */
  87435. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  87436. var index = this._camerasToBeAttached.indexOf(camera);
  87437. this._camerasToBeAttached.splice(index, 1);
  87438. this._buildPipeline();
  87439. };
  87440. /**
  87441. * Dispose of the pipeline and stop all post processes
  87442. */
  87443. DefaultRenderingPipeline.prototype.dispose = function () {
  87444. this._disposePostProcesses(true);
  87445. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87446. this._scene.autoClear = true;
  87447. if (this._resizeObserver) {
  87448. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  87449. this._resizeObserver = null;
  87450. }
  87451. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  87452. _super.prototype.dispose.call(this);
  87453. };
  87454. /**
  87455. * Serialize the rendering pipeline (Used when exporting)
  87456. * @returns the serialized object
  87457. */
  87458. DefaultRenderingPipeline.prototype.serialize = function () {
  87459. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87460. serializationObject.customType = "DefaultRenderingPipeline";
  87461. return serializationObject;
  87462. };
  87463. /**
  87464. * Parse the serialized pipeline
  87465. * @param source Source pipeline.
  87466. * @param scene The scene to load the pipeline to.
  87467. * @param rootUrl The URL of the serialized pipeline.
  87468. * @returns An instantiated pipeline from the serialized object.
  87469. */
  87470. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87471. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  87472. };
  87473. __decorate([
  87474. BABYLON.serialize()
  87475. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  87476. __decorate([
  87477. BABYLON.serialize()
  87478. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  87479. __decorate([
  87480. BABYLON.serialize()
  87481. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  87482. __decorate([
  87483. BABYLON.serialize()
  87484. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  87485. __decorate([
  87486. BABYLON.serialize()
  87487. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  87488. __decorate([
  87489. BABYLON.serialize()
  87490. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  87491. __decorate([
  87492. BABYLON.serialize()
  87493. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  87494. __decorate([
  87495. BABYLON.serialize()
  87496. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  87497. __decorate([
  87498. BABYLON.serialize()
  87499. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  87500. __decorate([
  87501. BABYLON.serialize()
  87502. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  87503. __decorate([
  87504. BABYLON.serialize()
  87505. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  87506. __decorate([
  87507. BABYLON.serialize()
  87508. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  87509. __decorate([
  87510. BABYLON.serialize()
  87511. ], DefaultRenderingPipeline.prototype, "samples", null);
  87512. __decorate([
  87513. BABYLON.serialize()
  87514. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  87515. __decorate([
  87516. BABYLON.serialize()
  87517. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  87518. __decorate([
  87519. BABYLON.serialize()
  87520. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  87521. __decorate([
  87522. BABYLON.serialize()
  87523. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  87524. return DefaultRenderingPipeline;
  87525. }(BABYLON.PostProcessRenderPipeline));
  87526. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  87527. })(BABYLON || (BABYLON = {}));
  87528. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  87529. var BABYLON;
  87530. (function (BABYLON) {
  87531. /**
  87532. * @hidden
  87533. */
  87534. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  87535. __extends(ImageProcessingConfigurationDefines, _super);
  87536. function ImageProcessingConfigurationDefines() {
  87537. var _this = _super.call(this) || this;
  87538. _this.IMAGEPROCESSING = false;
  87539. _this.VIGNETTE = false;
  87540. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87541. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87542. _this.TONEMAPPING = false;
  87543. _this.TONEMAPPING_ACES = false;
  87544. _this.CONTRAST = false;
  87545. _this.COLORCURVES = false;
  87546. _this.COLORGRADING = false;
  87547. _this.COLORGRADING3D = false;
  87548. _this.SAMPLER3DGREENDEPTH = false;
  87549. _this.SAMPLER3DBGRMAP = false;
  87550. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87551. _this.EXPOSURE = false;
  87552. _this.rebuild();
  87553. return _this;
  87554. }
  87555. return ImageProcessingConfigurationDefines;
  87556. }(BABYLON.MaterialDefines));
  87557. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  87558. /**
  87559. * This groups together the common properties used for image processing either in direct forward pass
  87560. * or through post processing effect depending on the use of the image processing pipeline in your scene
  87561. * or not.
  87562. */
  87563. var ImageProcessingConfiguration = /** @class */ (function () {
  87564. function ImageProcessingConfiguration() {
  87565. /**
  87566. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  87567. */
  87568. this.colorCurves = new BABYLON.ColorCurves();
  87569. this._colorCurvesEnabled = false;
  87570. this._colorGradingEnabled = false;
  87571. this._colorGradingWithGreenDepth = true;
  87572. this._colorGradingBGR = true;
  87573. /** @hidden */
  87574. this._exposure = 1.0;
  87575. this._toneMappingEnabled = false;
  87576. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  87577. this._contrast = 1.0;
  87578. /**
  87579. * Vignette stretch size.
  87580. */
  87581. this.vignetteStretch = 0;
  87582. /**
  87583. * Vignette centre X Offset.
  87584. */
  87585. this.vignetteCentreX = 0;
  87586. /**
  87587. * Vignette centre Y Offset.
  87588. */
  87589. this.vignetteCentreY = 0;
  87590. /**
  87591. * Vignette weight or intensity of the vignette effect.
  87592. */
  87593. this.vignetteWeight = 1.5;
  87594. /**
  87595. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87596. * if vignetteEnabled is set to true.
  87597. */
  87598. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87599. /**
  87600. * Camera field of view used by the Vignette effect.
  87601. */
  87602. this.vignetteCameraFov = 0.5;
  87603. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  87604. this._vignetteEnabled = false;
  87605. this._applyByPostProcess = false;
  87606. this._isEnabled = true;
  87607. /**
  87608. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  87609. */
  87610. this.onUpdateParameters = new BABYLON.Observable();
  87611. }
  87612. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  87613. /**
  87614. * Gets wether the color curves effect is enabled.
  87615. */
  87616. get: function () {
  87617. return this._colorCurvesEnabled;
  87618. },
  87619. /**
  87620. * Sets wether the color curves effect is enabled.
  87621. */
  87622. set: function (value) {
  87623. if (this._colorCurvesEnabled === value) {
  87624. return;
  87625. }
  87626. this._colorCurvesEnabled = value;
  87627. this._updateParameters();
  87628. },
  87629. enumerable: true,
  87630. configurable: true
  87631. });
  87632. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  87633. /**
  87634. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87635. */
  87636. get: function () {
  87637. return this._colorGradingTexture;
  87638. },
  87639. /**
  87640. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87641. */
  87642. set: function (value) {
  87643. if (this._colorGradingTexture === value) {
  87644. return;
  87645. }
  87646. this._colorGradingTexture = value;
  87647. this._updateParameters();
  87648. },
  87649. enumerable: true,
  87650. configurable: true
  87651. });
  87652. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  87653. /**
  87654. * Gets wether the color grading effect is enabled.
  87655. */
  87656. get: function () {
  87657. return this._colorGradingEnabled;
  87658. },
  87659. /**
  87660. * Sets wether the color grading effect is enabled.
  87661. */
  87662. set: function (value) {
  87663. if (this._colorGradingEnabled === value) {
  87664. return;
  87665. }
  87666. this._colorGradingEnabled = value;
  87667. this._updateParameters();
  87668. },
  87669. enumerable: true,
  87670. configurable: true
  87671. });
  87672. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  87673. /**
  87674. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  87675. */
  87676. get: function () {
  87677. return this._colorGradingWithGreenDepth;
  87678. },
  87679. /**
  87680. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  87681. */
  87682. set: function (value) {
  87683. if (this._colorGradingWithGreenDepth === value) {
  87684. return;
  87685. }
  87686. this._colorGradingWithGreenDepth = value;
  87687. this._updateParameters();
  87688. },
  87689. enumerable: true,
  87690. configurable: true
  87691. });
  87692. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  87693. /**
  87694. * Gets wether the color grading texture contains BGR values.
  87695. */
  87696. get: function () {
  87697. return this._colorGradingBGR;
  87698. },
  87699. /**
  87700. * Sets wether the color grading texture contains BGR values.
  87701. */
  87702. set: function (value) {
  87703. if (this._colorGradingBGR === value) {
  87704. return;
  87705. }
  87706. this._colorGradingBGR = value;
  87707. this._updateParameters();
  87708. },
  87709. enumerable: true,
  87710. configurable: true
  87711. });
  87712. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  87713. /**
  87714. * Gets the Exposure used in the effect.
  87715. */
  87716. get: function () {
  87717. return this._exposure;
  87718. },
  87719. /**
  87720. * Sets the Exposure used in the effect.
  87721. */
  87722. set: function (value) {
  87723. if (this._exposure === value) {
  87724. return;
  87725. }
  87726. this._exposure = value;
  87727. this._updateParameters();
  87728. },
  87729. enumerable: true,
  87730. configurable: true
  87731. });
  87732. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  87733. /**
  87734. * Gets wether the tone mapping effect is enabled.
  87735. */
  87736. get: function () {
  87737. return this._toneMappingEnabled;
  87738. },
  87739. /**
  87740. * Sets wether the tone mapping effect is enabled.
  87741. */
  87742. set: function (value) {
  87743. if (this._toneMappingEnabled === value) {
  87744. return;
  87745. }
  87746. this._toneMappingEnabled = value;
  87747. this._updateParameters();
  87748. },
  87749. enumerable: true,
  87750. configurable: true
  87751. });
  87752. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  87753. /**
  87754. * Gets the type of tone mapping effect.
  87755. */
  87756. get: function () {
  87757. return this._toneMappingType;
  87758. },
  87759. /**
  87760. * Sets the type of tone mapping effect used in BabylonJS.
  87761. */
  87762. set: function (value) {
  87763. if (this._toneMappingType === value) {
  87764. return;
  87765. }
  87766. this._toneMappingType = value;
  87767. this._updateParameters();
  87768. },
  87769. enumerable: true,
  87770. configurable: true
  87771. });
  87772. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  87773. /**
  87774. * Gets the contrast used in the effect.
  87775. */
  87776. get: function () {
  87777. return this._contrast;
  87778. },
  87779. /**
  87780. * Sets the contrast used in the effect.
  87781. */
  87782. set: function (value) {
  87783. if (this._contrast === value) {
  87784. return;
  87785. }
  87786. this._contrast = value;
  87787. this._updateParameters();
  87788. },
  87789. enumerable: true,
  87790. configurable: true
  87791. });
  87792. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  87793. /**
  87794. * Gets the vignette blend mode allowing different kind of effect.
  87795. */
  87796. get: function () {
  87797. return this._vignetteBlendMode;
  87798. },
  87799. /**
  87800. * Sets the vignette blend mode allowing different kind of effect.
  87801. */
  87802. set: function (value) {
  87803. if (this._vignetteBlendMode === value) {
  87804. return;
  87805. }
  87806. this._vignetteBlendMode = value;
  87807. this._updateParameters();
  87808. },
  87809. enumerable: true,
  87810. configurable: true
  87811. });
  87812. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  87813. /**
  87814. * Gets wether the vignette effect is enabled.
  87815. */
  87816. get: function () {
  87817. return this._vignetteEnabled;
  87818. },
  87819. /**
  87820. * Sets wether the vignette effect is enabled.
  87821. */
  87822. set: function (value) {
  87823. if (this._vignetteEnabled === value) {
  87824. return;
  87825. }
  87826. this._vignetteEnabled = value;
  87827. this._updateParameters();
  87828. },
  87829. enumerable: true,
  87830. configurable: true
  87831. });
  87832. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  87833. /**
  87834. * Gets wether the image processing is applied through a post process or not.
  87835. */
  87836. get: function () {
  87837. return this._applyByPostProcess;
  87838. },
  87839. /**
  87840. * Sets wether the image processing is applied through a post process or not.
  87841. */
  87842. set: function (value) {
  87843. if (this._applyByPostProcess === value) {
  87844. return;
  87845. }
  87846. this._applyByPostProcess = value;
  87847. this._updateParameters();
  87848. },
  87849. enumerable: true,
  87850. configurable: true
  87851. });
  87852. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  87853. /**
  87854. * Gets wether the image processing is enabled or not.
  87855. */
  87856. get: function () {
  87857. return this._isEnabled;
  87858. },
  87859. /**
  87860. * Sets wether the image processing is enabled or not.
  87861. */
  87862. set: function (value) {
  87863. if (this._isEnabled === value) {
  87864. return;
  87865. }
  87866. this._isEnabled = value;
  87867. this._updateParameters();
  87868. },
  87869. enumerable: true,
  87870. configurable: true
  87871. });
  87872. /**
  87873. * Method called each time the image processing information changes requires to recompile the effect.
  87874. */
  87875. ImageProcessingConfiguration.prototype._updateParameters = function () {
  87876. this.onUpdateParameters.notifyObservers(this);
  87877. };
  87878. /**
  87879. * Gets the current class name.
  87880. * @return "ImageProcessingConfiguration"
  87881. */
  87882. ImageProcessingConfiguration.prototype.getClassName = function () {
  87883. return "ImageProcessingConfiguration";
  87884. };
  87885. /**
  87886. * Prepare the list of uniforms associated with the Image Processing effects.
  87887. * @param uniforms The list of uniforms used in the effect
  87888. * @param defines the list of defines currently in use
  87889. */
  87890. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  87891. if (defines.EXPOSURE) {
  87892. uniforms.push("exposureLinear");
  87893. }
  87894. if (defines.CONTRAST) {
  87895. uniforms.push("contrast");
  87896. }
  87897. if (defines.COLORGRADING) {
  87898. uniforms.push("colorTransformSettings");
  87899. }
  87900. if (defines.VIGNETTE) {
  87901. uniforms.push("vInverseScreenSize");
  87902. uniforms.push("vignetteSettings1");
  87903. uniforms.push("vignetteSettings2");
  87904. }
  87905. if (defines.COLORCURVES) {
  87906. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  87907. }
  87908. };
  87909. /**
  87910. * Prepare the list of samplers associated with the Image Processing effects.
  87911. * @param samplersList The list of uniforms used in the effect
  87912. * @param defines the list of defines currently in use
  87913. */
  87914. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  87915. if (defines.COLORGRADING) {
  87916. samplersList.push("txColorTransform");
  87917. }
  87918. };
  87919. /**
  87920. * Prepare the list of defines associated to the shader.
  87921. * @param defines the list of defines to complete
  87922. * @param forPostProcess Define if we are currently in post process mode or not
  87923. */
  87924. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  87925. if (forPostProcess === void 0) { forPostProcess = false; }
  87926. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  87927. defines.VIGNETTE = false;
  87928. defines.TONEMAPPING = false;
  87929. defines.TONEMAPPING_ACES = false;
  87930. defines.CONTRAST = false;
  87931. defines.EXPOSURE = false;
  87932. defines.COLORCURVES = false;
  87933. defines.COLORGRADING = false;
  87934. defines.COLORGRADING3D = false;
  87935. defines.IMAGEPROCESSING = false;
  87936. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  87937. return;
  87938. }
  87939. defines.VIGNETTE = this.vignetteEnabled;
  87940. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  87941. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  87942. defines.TONEMAPPING = this.toneMappingEnabled;
  87943. switch (this._toneMappingType) {
  87944. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  87945. defines.TONEMAPPING_ACES = true;
  87946. break;
  87947. }
  87948. defines.CONTRAST = (this.contrast !== 1.0);
  87949. defines.EXPOSURE = (this.exposure !== 1.0);
  87950. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  87951. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  87952. if (defines.COLORGRADING) {
  87953. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  87954. }
  87955. else {
  87956. defines.COLORGRADING3D = false;
  87957. }
  87958. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  87959. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  87960. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  87961. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  87962. };
  87963. /**
  87964. * Returns true if all the image processing information are ready.
  87965. * @returns True if ready, otherwise, false
  87966. */
  87967. ImageProcessingConfiguration.prototype.isReady = function () {
  87968. // Color Grading texure can not be none blocking.
  87969. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  87970. };
  87971. /**
  87972. * Binds the image processing to the shader.
  87973. * @param effect The effect to bind to
  87974. * @param aspectRatio Define the current aspect ratio of the effect
  87975. */
  87976. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  87977. if (aspectRatio === void 0) { aspectRatio = 1; }
  87978. // Color Curves
  87979. if (this._colorCurvesEnabled && this.colorCurves) {
  87980. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  87981. }
  87982. // Vignette
  87983. if (this._vignetteEnabled) {
  87984. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  87985. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  87986. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  87987. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  87988. var vignetteScaleX = vignetteScaleY * aspectRatio;
  87989. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  87990. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  87991. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  87992. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  87993. var vignettePower = -2.0 * this.vignetteWeight;
  87994. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  87995. }
  87996. // Exposure
  87997. effect.setFloat("exposureLinear", this.exposure);
  87998. // Contrast
  87999. effect.setFloat("contrast", this.contrast);
  88000. // Color transform settings
  88001. if (this.colorGradingTexture) {
  88002. effect.setTexture("txColorTransform", this.colorGradingTexture);
  88003. var textureSize = this.colorGradingTexture.getSize().height;
  88004. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  88005. 0.5 / textureSize, // textureOffset
  88006. textureSize, // textureSize
  88007. this.colorGradingTexture.level // weight
  88008. );
  88009. }
  88010. };
  88011. /**
  88012. * Clones the current image processing instance.
  88013. * @return The cloned image processing
  88014. */
  88015. ImageProcessingConfiguration.prototype.clone = function () {
  88016. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  88017. };
  88018. /**
  88019. * Serializes the current image processing instance to a json representation.
  88020. * @return a JSON representation
  88021. */
  88022. ImageProcessingConfiguration.prototype.serialize = function () {
  88023. return BABYLON.SerializationHelper.Serialize(this);
  88024. };
  88025. /**
  88026. * Parses the image processing from a json representation.
  88027. * @param source the JSON source to parse
  88028. * @return The parsed image processing
  88029. */
  88030. ImageProcessingConfiguration.Parse = function (source) {
  88031. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  88032. };
  88033. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  88034. /**
  88035. * Used to apply the vignette as a mix with the pixel color.
  88036. */
  88037. get: function () {
  88038. return this._VIGNETTEMODE_MULTIPLY;
  88039. },
  88040. enumerable: true,
  88041. configurable: true
  88042. });
  88043. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  88044. /**
  88045. * Used to apply the vignette as a replacement of the pixel color.
  88046. */
  88047. get: function () {
  88048. return this._VIGNETTEMODE_OPAQUE;
  88049. },
  88050. enumerable: true,
  88051. configurable: true
  88052. });
  88053. /**
  88054. * Default tone mapping applied in BabylonJS.
  88055. */
  88056. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  88057. /**
  88058. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  88059. * to other engines rendering to increase portability.
  88060. */
  88061. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  88062. // Static constants associated to the image processing.
  88063. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  88064. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  88065. __decorate([
  88066. BABYLON.serializeAsColorCurves()
  88067. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  88068. __decorate([
  88069. BABYLON.serialize()
  88070. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  88071. __decorate([
  88072. BABYLON.serializeAsTexture("colorGradingTexture")
  88073. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  88074. __decorate([
  88075. BABYLON.serialize()
  88076. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  88077. __decorate([
  88078. BABYLON.serialize()
  88079. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  88080. __decorate([
  88081. BABYLON.serialize()
  88082. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  88083. __decorate([
  88084. BABYLON.serialize()
  88085. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  88086. __decorate([
  88087. BABYLON.serialize()
  88088. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  88089. __decorate([
  88090. BABYLON.serialize()
  88091. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  88092. __decorate([
  88093. BABYLON.serialize()
  88094. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  88095. __decorate([
  88096. BABYLON.serialize()
  88097. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  88098. __decorate([
  88099. BABYLON.serialize()
  88100. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  88101. __decorate([
  88102. BABYLON.serialize()
  88103. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  88104. __decorate([
  88105. BABYLON.serialize()
  88106. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  88107. __decorate([
  88108. BABYLON.serializeAsColor4()
  88109. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  88110. __decorate([
  88111. BABYLON.serialize()
  88112. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  88113. __decorate([
  88114. BABYLON.serialize()
  88115. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  88116. __decorate([
  88117. BABYLON.serialize()
  88118. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  88119. __decorate([
  88120. BABYLON.serialize()
  88121. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  88122. __decorate([
  88123. BABYLON.serialize()
  88124. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  88125. return ImageProcessingConfiguration;
  88126. }());
  88127. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  88128. })(BABYLON || (BABYLON = {}));
  88129. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  88130. var BABYLON;
  88131. (function (BABYLON) {
  88132. /**
  88133. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  88134. * It can help converting any input color in a desired output one. This can then be used to create effects
  88135. * from sepia, black and white to sixties or futuristic rendering...
  88136. *
  88137. * The only supported format is currently 3dl.
  88138. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  88139. */
  88140. var ColorGradingTexture = /** @class */ (function (_super) {
  88141. __extends(ColorGradingTexture, _super);
  88142. /**
  88143. * Instantiates a ColorGradingTexture from the following parameters.
  88144. *
  88145. * @param url The location of the color gradind data (currently only supporting 3dl)
  88146. * @param scene The scene the texture will be used in
  88147. */
  88148. function ColorGradingTexture(url, scene) {
  88149. var _this = _super.call(this, scene) || this;
  88150. if (!url) {
  88151. return _this;
  88152. }
  88153. _this._engine = scene.getEngine();
  88154. _this._textureMatrix = BABYLON.Matrix.Identity();
  88155. _this.name = url;
  88156. _this.url = url;
  88157. _this.hasAlpha = false;
  88158. _this.isCube = false;
  88159. _this.is3D = _this._engine.webGLVersion > 1;
  88160. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88161. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88162. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88163. _this.anisotropicFilteringLevel = 1;
  88164. _this._texture = _this._getFromCache(url, true);
  88165. if (!_this._texture) {
  88166. if (!scene.useDelayedTextureLoading) {
  88167. _this.loadTexture();
  88168. }
  88169. else {
  88170. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  88171. }
  88172. }
  88173. return _this;
  88174. }
  88175. /**
  88176. * Returns the texture matrix used in most of the material.
  88177. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  88178. */
  88179. ColorGradingTexture.prototype.getTextureMatrix = function () {
  88180. return this._textureMatrix;
  88181. };
  88182. /**
  88183. * Occurs when the file being loaded is a .3dl LUT file.
  88184. */
  88185. ColorGradingTexture.prototype.load3dlTexture = function () {
  88186. var engine = this._engine;
  88187. var texture;
  88188. if (engine.webGLVersion === 1) {
  88189. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88190. }
  88191. else {
  88192. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88193. }
  88194. this._texture = texture;
  88195. var callback = function (text) {
  88196. if (typeof text !== "string") {
  88197. return;
  88198. }
  88199. var data = null;
  88200. var tempData = null;
  88201. var line;
  88202. var lines = text.split('\n');
  88203. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  88204. var maxColor = 0;
  88205. for (var i = 0; i < lines.length; i++) {
  88206. line = lines[i];
  88207. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  88208. continue;
  88209. }
  88210. if (line.indexOf('#') === 0) {
  88211. continue;
  88212. }
  88213. var words = line.split(" ");
  88214. if (size === 0) {
  88215. // Number of space + one
  88216. size = words.length;
  88217. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  88218. tempData = new Float32Array(size * size * size * 4);
  88219. continue;
  88220. }
  88221. if (size != 0) {
  88222. var r = Math.max(parseInt(words[0]), 0);
  88223. var g = Math.max(parseInt(words[1]), 0);
  88224. var b = Math.max(parseInt(words[2]), 0);
  88225. maxColor = Math.max(r, maxColor);
  88226. maxColor = Math.max(g, maxColor);
  88227. maxColor = Math.max(b, maxColor);
  88228. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  88229. if (tempData) {
  88230. tempData[pixelStorageIndex + 0] = r;
  88231. tempData[pixelStorageIndex + 1] = g;
  88232. tempData[pixelStorageIndex + 2] = b;
  88233. }
  88234. // Keep for reference in case of back compat problems.
  88235. // pixelIndexSlice++;
  88236. // if (pixelIndexSlice % size == 0) {
  88237. // pixelIndexH++;
  88238. // pixelIndexSlice = 0;
  88239. // if (pixelIndexH % size == 0) {
  88240. // pixelIndexW++;
  88241. // pixelIndexH = 0;
  88242. // }
  88243. // }
  88244. pixelIndexH++;
  88245. if (pixelIndexH % size == 0) {
  88246. pixelIndexSlice++;
  88247. pixelIndexH = 0;
  88248. if (pixelIndexSlice % size == 0) {
  88249. pixelIndexW++;
  88250. pixelIndexSlice = 0;
  88251. }
  88252. }
  88253. }
  88254. }
  88255. if (tempData && data) {
  88256. for (var i = 0; i < tempData.length; i++) {
  88257. if (i > 0 && (i + 1) % 4 === 0) {
  88258. data[i] = 255;
  88259. }
  88260. else {
  88261. var value = tempData[i];
  88262. data[i] = (value / maxColor * 255);
  88263. }
  88264. }
  88265. }
  88266. if (texture.is3D) {
  88267. texture.updateSize(size, size, size);
  88268. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88269. }
  88270. else {
  88271. texture.updateSize(size * size, size);
  88272. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88273. }
  88274. };
  88275. var scene = this.getScene();
  88276. if (scene) {
  88277. scene._loadFile(this.url, callback);
  88278. }
  88279. else {
  88280. this._engine._loadFile(this.url, callback);
  88281. }
  88282. return this._texture;
  88283. };
  88284. /**
  88285. * Starts the loading process of the texture.
  88286. */
  88287. ColorGradingTexture.prototype.loadTexture = function () {
  88288. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  88289. this.load3dlTexture();
  88290. }
  88291. };
  88292. /**
  88293. * Clones the color gradind texture.
  88294. */
  88295. ColorGradingTexture.prototype.clone = function () {
  88296. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  88297. // Base texture
  88298. newTexture.level = this.level;
  88299. return newTexture;
  88300. };
  88301. /**
  88302. * Called during delayed load for textures.
  88303. */
  88304. ColorGradingTexture.prototype.delayLoad = function () {
  88305. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88306. return;
  88307. }
  88308. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88309. this._texture = this._getFromCache(this.url, true);
  88310. if (!this._texture) {
  88311. this.loadTexture();
  88312. }
  88313. };
  88314. /**
  88315. * Parses a color grading texture serialized by Babylon.
  88316. * @param parsedTexture The texture information being parsedTexture
  88317. * @param scene The scene to load the texture in
  88318. * @param rootUrl The root url of the data assets to load
  88319. * @return A color gradind texture
  88320. */
  88321. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88322. var texture = null;
  88323. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88324. texture = new ColorGradingTexture(parsedTexture.name, scene);
  88325. texture.name = parsedTexture.name;
  88326. texture.level = parsedTexture.level;
  88327. }
  88328. return texture;
  88329. };
  88330. /**
  88331. * Serializes the LUT texture to json format.
  88332. */
  88333. ColorGradingTexture.prototype.serialize = function () {
  88334. if (!this.name) {
  88335. return null;
  88336. }
  88337. var serializationObject = {};
  88338. serializationObject.name = this.name;
  88339. serializationObject.level = this.level;
  88340. serializationObject.customType = "BABYLON.ColorGradingTexture";
  88341. return serializationObject;
  88342. };
  88343. /**
  88344. * Empty line regex stored for GC.
  88345. */
  88346. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  88347. return ColorGradingTexture;
  88348. }(BABYLON.BaseTexture));
  88349. BABYLON.ColorGradingTexture = ColorGradingTexture;
  88350. })(BABYLON || (BABYLON = {}));
  88351. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  88352. var BABYLON;
  88353. (function (BABYLON) {
  88354. /**
  88355. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88356. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88357. * 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;
  88358. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88359. */
  88360. var ColorCurves = /** @class */ (function () {
  88361. function ColorCurves() {
  88362. this._dirty = true;
  88363. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  88364. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  88365. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88366. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  88367. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88368. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  88369. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  88370. this._globalHue = 30;
  88371. this._globalDensity = 0;
  88372. this._globalSaturation = 0;
  88373. this._globalExposure = 0;
  88374. this._highlightsHue = 30;
  88375. this._highlightsDensity = 0;
  88376. this._highlightsSaturation = 0;
  88377. this._highlightsExposure = 0;
  88378. this._midtonesHue = 30;
  88379. this._midtonesDensity = 0;
  88380. this._midtonesSaturation = 0;
  88381. this._midtonesExposure = 0;
  88382. this._shadowsHue = 30;
  88383. this._shadowsDensity = 0;
  88384. this._shadowsSaturation = 0;
  88385. this._shadowsExposure = 0;
  88386. }
  88387. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  88388. /**
  88389. * Gets the global Hue value.
  88390. * 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).
  88391. */
  88392. get: function () {
  88393. return this._globalHue;
  88394. },
  88395. /**
  88396. * Sets the global Hue value.
  88397. * 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).
  88398. */
  88399. set: function (value) {
  88400. this._globalHue = value;
  88401. this._dirty = true;
  88402. },
  88403. enumerable: true,
  88404. configurable: true
  88405. });
  88406. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  88407. /**
  88408. * Gets the global Density value.
  88409. * 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.
  88410. * Values less than zero provide a filter of opposite hue.
  88411. */
  88412. get: function () {
  88413. return this._globalDensity;
  88414. },
  88415. /**
  88416. * Sets the global Density value.
  88417. * 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.
  88418. * Values less than zero provide a filter of opposite hue.
  88419. */
  88420. set: function (value) {
  88421. this._globalDensity = value;
  88422. this._dirty = true;
  88423. },
  88424. enumerable: true,
  88425. configurable: true
  88426. });
  88427. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  88428. /**
  88429. * Gets the global Saturation value.
  88430. * 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.
  88431. */
  88432. get: function () {
  88433. return this._globalSaturation;
  88434. },
  88435. /**
  88436. * Sets the global Saturation value.
  88437. * 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.
  88438. */
  88439. set: function (value) {
  88440. this._globalSaturation = value;
  88441. this._dirty = true;
  88442. },
  88443. enumerable: true,
  88444. configurable: true
  88445. });
  88446. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  88447. /**
  88448. * Gets the global Exposure value.
  88449. * 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.
  88450. */
  88451. get: function () {
  88452. return this._globalExposure;
  88453. },
  88454. /**
  88455. * Sets the global Exposure value.
  88456. * 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.
  88457. */
  88458. set: function (value) {
  88459. this._globalExposure = value;
  88460. this._dirty = true;
  88461. },
  88462. enumerable: true,
  88463. configurable: true
  88464. });
  88465. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  88466. /**
  88467. * Gets the highlights Hue value.
  88468. * 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).
  88469. */
  88470. get: function () {
  88471. return this._highlightsHue;
  88472. },
  88473. /**
  88474. * Sets the highlights Hue value.
  88475. * 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).
  88476. */
  88477. set: function (value) {
  88478. this._highlightsHue = value;
  88479. this._dirty = true;
  88480. },
  88481. enumerable: true,
  88482. configurable: true
  88483. });
  88484. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  88485. /**
  88486. * Gets the highlights Density value.
  88487. * 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.
  88488. * Values less than zero provide a filter of opposite hue.
  88489. */
  88490. get: function () {
  88491. return this._highlightsDensity;
  88492. },
  88493. /**
  88494. * Sets the highlights Density value.
  88495. * 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.
  88496. * Values less than zero provide a filter of opposite hue.
  88497. */
  88498. set: function (value) {
  88499. this._highlightsDensity = value;
  88500. this._dirty = true;
  88501. },
  88502. enumerable: true,
  88503. configurable: true
  88504. });
  88505. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  88506. /**
  88507. * Gets the highlights Saturation value.
  88508. * 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.
  88509. */
  88510. get: function () {
  88511. return this._highlightsSaturation;
  88512. },
  88513. /**
  88514. * Sets the highlights Saturation value.
  88515. * 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.
  88516. */
  88517. set: function (value) {
  88518. this._highlightsSaturation = value;
  88519. this._dirty = true;
  88520. },
  88521. enumerable: true,
  88522. configurable: true
  88523. });
  88524. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  88525. /**
  88526. * Gets the highlights Exposure value.
  88527. * 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.
  88528. */
  88529. get: function () {
  88530. return this._highlightsExposure;
  88531. },
  88532. /**
  88533. * Sets the highlights Exposure value.
  88534. * 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.
  88535. */
  88536. set: function (value) {
  88537. this._highlightsExposure = value;
  88538. this._dirty = true;
  88539. },
  88540. enumerable: true,
  88541. configurable: true
  88542. });
  88543. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  88544. /**
  88545. * Gets the midtones Hue value.
  88546. * 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).
  88547. */
  88548. get: function () {
  88549. return this._midtonesHue;
  88550. },
  88551. /**
  88552. * Sets the midtones Hue value.
  88553. * 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).
  88554. */
  88555. set: function (value) {
  88556. this._midtonesHue = value;
  88557. this._dirty = true;
  88558. },
  88559. enumerable: true,
  88560. configurable: true
  88561. });
  88562. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  88563. /**
  88564. * Gets the midtones Density value.
  88565. * 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.
  88566. * Values less than zero provide a filter of opposite hue.
  88567. */
  88568. get: function () {
  88569. return this._midtonesDensity;
  88570. },
  88571. /**
  88572. * Sets the midtones Density value.
  88573. * 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.
  88574. * Values less than zero provide a filter of opposite hue.
  88575. */
  88576. set: function (value) {
  88577. this._midtonesDensity = value;
  88578. this._dirty = true;
  88579. },
  88580. enumerable: true,
  88581. configurable: true
  88582. });
  88583. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  88584. /**
  88585. * Gets the midtones Saturation value.
  88586. * 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.
  88587. */
  88588. get: function () {
  88589. return this._midtonesSaturation;
  88590. },
  88591. /**
  88592. * Sets the midtones Saturation value.
  88593. * 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.
  88594. */
  88595. set: function (value) {
  88596. this._midtonesSaturation = value;
  88597. this._dirty = true;
  88598. },
  88599. enumerable: true,
  88600. configurable: true
  88601. });
  88602. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  88603. /**
  88604. * Gets the midtones Exposure value.
  88605. * 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.
  88606. */
  88607. get: function () {
  88608. return this._midtonesExposure;
  88609. },
  88610. /**
  88611. * Sets the midtones Exposure value.
  88612. * 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.
  88613. */
  88614. set: function (value) {
  88615. this._midtonesExposure = value;
  88616. this._dirty = true;
  88617. },
  88618. enumerable: true,
  88619. configurable: true
  88620. });
  88621. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  88622. /**
  88623. * Gets the shadows Hue value.
  88624. * 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).
  88625. */
  88626. get: function () {
  88627. return this._shadowsHue;
  88628. },
  88629. /**
  88630. * Sets the shadows Hue value.
  88631. * 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).
  88632. */
  88633. set: function (value) {
  88634. this._shadowsHue = value;
  88635. this._dirty = true;
  88636. },
  88637. enumerable: true,
  88638. configurable: true
  88639. });
  88640. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  88641. /**
  88642. * Gets the shadows Density value.
  88643. * 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.
  88644. * Values less than zero provide a filter of opposite hue.
  88645. */
  88646. get: function () {
  88647. return this._shadowsDensity;
  88648. },
  88649. /**
  88650. * Sets the shadows Density value.
  88651. * 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.
  88652. * Values less than zero provide a filter of opposite hue.
  88653. */
  88654. set: function (value) {
  88655. this._shadowsDensity = value;
  88656. this._dirty = true;
  88657. },
  88658. enumerable: true,
  88659. configurable: true
  88660. });
  88661. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  88662. /**
  88663. * Gets the shadows Saturation value.
  88664. * 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.
  88665. */
  88666. get: function () {
  88667. return this._shadowsSaturation;
  88668. },
  88669. /**
  88670. * Sets the shadows Saturation value.
  88671. * 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.
  88672. */
  88673. set: function (value) {
  88674. this._shadowsSaturation = value;
  88675. this._dirty = true;
  88676. },
  88677. enumerable: true,
  88678. configurable: true
  88679. });
  88680. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  88681. /**
  88682. * Gets the shadows Exposure value.
  88683. * 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.
  88684. */
  88685. get: function () {
  88686. return this._shadowsExposure;
  88687. },
  88688. /**
  88689. * Sets the shadows Exposure value.
  88690. * 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.
  88691. */
  88692. set: function (value) {
  88693. this._shadowsExposure = value;
  88694. this._dirty = true;
  88695. },
  88696. enumerable: true,
  88697. configurable: true
  88698. });
  88699. /**
  88700. * Returns the class name
  88701. * @returns The class name
  88702. */
  88703. ColorCurves.prototype.getClassName = function () {
  88704. return "ColorCurves";
  88705. };
  88706. /**
  88707. * Binds the color curves to the shader.
  88708. * @param colorCurves The color curve to bind
  88709. * @param effect The effect to bind to
  88710. * @param positiveUniform The positive uniform shader parameter
  88711. * @param neutralUniform The neutral uniform shader parameter
  88712. * @param negativeUniform The negative uniform shader parameter
  88713. */
  88714. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  88715. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  88716. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  88717. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  88718. if (colorCurves._dirty) {
  88719. colorCurves._dirty = false;
  88720. // Fill in global info.
  88721. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  88722. // Compute highlights info.
  88723. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  88724. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  88725. // Compute midtones info.
  88726. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  88727. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  88728. // Compute shadows info.
  88729. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  88730. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  88731. // Compute deltas (neutral is midtones).
  88732. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  88733. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  88734. }
  88735. if (effect) {
  88736. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  88737. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  88738. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  88739. }
  88740. };
  88741. /**
  88742. * Prepare the list of uniforms associated with the ColorCurves effects.
  88743. * @param uniformsList The list of uniforms used in the effect
  88744. */
  88745. ColorCurves.PrepareUniforms = function (uniformsList) {
  88746. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  88747. };
  88748. /**
  88749. * Returns color grading data based on a hue, density, saturation and exposure value.
  88750. * @param filterHue The hue of the color filter.
  88751. * @param filterDensity The density of the color filter.
  88752. * @param saturation The saturation.
  88753. * @param exposure The exposure.
  88754. * @param result The result data container.
  88755. */
  88756. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  88757. if (hue == null) {
  88758. return;
  88759. }
  88760. hue = ColorCurves.clamp(hue, 0, 360);
  88761. density = ColorCurves.clamp(density, -100, 100);
  88762. saturation = ColorCurves.clamp(saturation, -100, 100);
  88763. exposure = ColorCurves.clamp(exposure, -100, 100);
  88764. // Remap the slider/config filter density with non-linear mapping and also scale by half
  88765. // so that the maximum filter density is only 50% control. This provides fine control
  88766. // for small values and reasonable range.
  88767. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  88768. density *= 0.5;
  88769. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  88770. if (density < 0) {
  88771. density *= -1;
  88772. hue = (hue + 180) % 360;
  88773. }
  88774. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  88775. result.scaleToRef(2, result);
  88776. result.a = 1 + 0.01 * saturation;
  88777. };
  88778. /**
  88779. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  88780. * @param value The input slider value in range [-100,100].
  88781. * @returns Adjusted value.
  88782. */
  88783. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  88784. value /= 100;
  88785. var x = Math.abs(value);
  88786. x = Math.pow(x, 2);
  88787. if (value < 0) {
  88788. x *= -1;
  88789. }
  88790. x *= 100;
  88791. return x;
  88792. };
  88793. /**
  88794. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  88795. * @param hue The hue (H) input.
  88796. * @param saturation The saturation (S) input.
  88797. * @param brightness The brightness (B) input.
  88798. * @result An RGBA color represented as Vector4.
  88799. */
  88800. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  88801. var h = ColorCurves.clamp(hue, 0, 360);
  88802. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  88803. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  88804. if (s === 0) {
  88805. result.r = v;
  88806. result.g = v;
  88807. result.b = v;
  88808. }
  88809. else {
  88810. // sector 0 to 5
  88811. h /= 60;
  88812. var i = Math.floor(h);
  88813. // fractional part of h
  88814. var f = h - i;
  88815. var p = v * (1 - s);
  88816. var q = v * (1 - s * f);
  88817. var t = v * (1 - s * (1 - f));
  88818. switch (i) {
  88819. case 0:
  88820. result.r = v;
  88821. result.g = t;
  88822. result.b = p;
  88823. break;
  88824. case 1:
  88825. result.r = q;
  88826. result.g = v;
  88827. result.b = p;
  88828. break;
  88829. case 2:
  88830. result.r = p;
  88831. result.g = v;
  88832. result.b = t;
  88833. break;
  88834. case 3:
  88835. result.r = p;
  88836. result.g = q;
  88837. result.b = v;
  88838. break;
  88839. case 4:
  88840. result.r = t;
  88841. result.g = p;
  88842. result.b = v;
  88843. break;
  88844. default: // case 5:
  88845. result.r = v;
  88846. result.g = p;
  88847. result.b = q;
  88848. break;
  88849. }
  88850. }
  88851. result.a = 1;
  88852. };
  88853. /**
  88854. * Returns a value clamped between min and max
  88855. * @param value The value to clamp
  88856. * @param min The minimum of value
  88857. * @param max The maximum of value
  88858. * @returns The clamped value.
  88859. */
  88860. ColorCurves.clamp = function (value, min, max) {
  88861. return Math.min(Math.max(value, min), max);
  88862. };
  88863. /**
  88864. * Clones the current color curve instance.
  88865. * @return The cloned curves
  88866. */
  88867. ColorCurves.prototype.clone = function () {
  88868. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  88869. };
  88870. /**
  88871. * Serializes the current color curve instance to a json representation.
  88872. * @return a JSON representation
  88873. */
  88874. ColorCurves.prototype.serialize = function () {
  88875. return BABYLON.SerializationHelper.Serialize(this);
  88876. };
  88877. /**
  88878. * Parses the color curve from a json representation.
  88879. * @param source the JSON source to parse
  88880. * @return The parsed curves
  88881. */
  88882. ColorCurves.Parse = function (source) {
  88883. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  88884. };
  88885. __decorate([
  88886. BABYLON.serialize()
  88887. ], ColorCurves.prototype, "_globalHue", void 0);
  88888. __decorate([
  88889. BABYLON.serialize()
  88890. ], ColorCurves.prototype, "_globalDensity", void 0);
  88891. __decorate([
  88892. BABYLON.serialize()
  88893. ], ColorCurves.prototype, "_globalSaturation", void 0);
  88894. __decorate([
  88895. BABYLON.serialize()
  88896. ], ColorCurves.prototype, "_globalExposure", void 0);
  88897. __decorate([
  88898. BABYLON.serialize()
  88899. ], ColorCurves.prototype, "_highlightsHue", void 0);
  88900. __decorate([
  88901. BABYLON.serialize()
  88902. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  88903. __decorate([
  88904. BABYLON.serialize()
  88905. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  88906. __decorate([
  88907. BABYLON.serialize()
  88908. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  88909. __decorate([
  88910. BABYLON.serialize()
  88911. ], ColorCurves.prototype, "_midtonesHue", void 0);
  88912. __decorate([
  88913. BABYLON.serialize()
  88914. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  88915. __decorate([
  88916. BABYLON.serialize()
  88917. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  88918. __decorate([
  88919. BABYLON.serialize()
  88920. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  88921. return ColorCurves;
  88922. }());
  88923. BABYLON.ColorCurves = ColorCurves;
  88924. })(BABYLON || (BABYLON = {}));
  88925. //# sourceMappingURL=babylon.colorCurves.js.map
  88926. var BABYLON;
  88927. (function (BABYLON) {
  88928. /**
  88929. * Post process which applies a refractin texture
  88930. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88931. */
  88932. var RefractionPostProcess = /** @class */ (function (_super) {
  88933. __extends(RefractionPostProcess, _super);
  88934. /**
  88935. * Initializes the RefractionPostProcess
  88936. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88937. * @param name The name of the effect.
  88938. * @param refractionTextureUrl Url of the refraction texture to use
  88939. * @param color the base color of the refraction (used to taint the rendering)
  88940. * @param depth simulated refraction depth
  88941. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  88942. * @param camera The camera to apply the render pass to.
  88943. * @param options The required width/height ratio to downsize to before computing the render pass.
  88944. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88945. * @param engine The engine which the post process will be applied. (default: current engine)
  88946. * @param reusable If the post process can be reused on the same frame. (default: false)
  88947. */
  88948. function RefractionPostProcess(name, refractionTextureUrl,
  88949. /** the base color of the refraction (used to taint the rendering) */
  88950. color,
  88951. /** simulated refraction depth */
  88952. depth,
  88953. /** the coefficient of the base color (0 to remove base color tainting) */
  88954. colorLevel, options, camera, samplingMode, engine, reusable) {
  88955. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  88956. _this.color = color;
  88957. _this.depth = depth;
  88958. _this.colorLevel = colorLevel;
  88959. _this._ownRefractionTexture = true;
  88960. _this.onActivateObservable.add(function (cam) {
  88961. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  88962. });
  88963. _this.onApplyObservable.add(function (effect) {
  88964. effect.setColor3("baseColor", _this.color);
  88965. effect.setFloat("depth", _this.depth);
  88966. effect.setFloat("colorLevel", _this.colorLevel);
  88967. effect.setTexture("refractionSampler", _this._refTexture);
  88968. });
  88969. return _this;
  88970. }
  88971. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  88972. /**
  88973. * Gets or sets the refraction texture
  88974. * Please note that you are responsible for disposing the texture if you set it manually
  88975. */
  88976. get: function () {
  88977. return this._refTexture;
  88978. },
  88979. set: function (value) {
  88980. if (this._refTexture && this._ownRefractionTexture) {
  88981. this._refTexture.dispose();
  88982. }
  88983. this._refTexture = value;
  88984. this._ownRefractionTexture = false;
  88985. },
  88986. enumerable: true,
  88987. configurable: true
  88988. });
  88989. // Methods
  88990. /**
  88991. * Disposes of the post process
  88992. * @param camera Camera to dispose post process on
  88993. */
  88994. RefractionPostProcess.prototype.dispose = function (camera) {
  88995. if (this._refTexture && this._ownRefractionTexture) {
  88996. this._refTexture.dispose();
  88997. this._refTexture = null;
  88998. }
  88999. _super.prototype.dispose.call(this, camera);
  89000. };
  89001. return RefractionPostProcess;
  89002. }(BABYLON.PostProcess));
  89003. BABYLON.RefractionPostProcess = RefractionPostProcess;
  89004. })(BABYLON || (BABYLON = {}));
  89005. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  89006. var BABYLON;
  89007. (function (BABYLON) {
  89008. /**
  89009. * Post process used to render in black and white
  89010. */
  89011. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  89012. __extends(BlackAndWhitePostProcess, _super);
  89013. /**
  89014. * Creates a black and white post process
  89015. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  89016. * @param name The name of the effect.
  89017. * @param options The required width/height ratio to downsize to before computing the render pass.
  89018. * @param camera The camera to apply the render pass to.
  89019. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89020. * @param engine The engine which the post process will be applied. (default: current engine)
  89021. * @param reusable If the post process can be reused on the same frame. (default: false)
  89022. */
  89023. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  89024. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  89025. /**
  89026. * Linear about to convert he result to black and white (default: 1)
  89027. */
  89028. _this.degree = 1;
  89029. _this.onApplyObservable.add(function (effect) {
  89030. effect.setFloat("degree", _this.degree);
  89031. });
  89032. return _this;
  89033. }
  89034. return BlackAndWhitePostProcess;
  89035. }(BABYLON.PostProcess));
  89036. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  89037. })(BABYLON || (BABYLON = {}));
  89038. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  89039. var BABYLON;
  89040. (function (BABYLON) {
  89041. /**
  89042. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  89043. * input texture to perform effects such as edge detection or sharpening
  89044. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  89045. */
  89046. var ConvolutionPostProcess = /** @class */ (function (_super) {
  89047. __extends(ConvolutionPostProcess, _super);
  89048. /**
  89049. * Creates a new instance ConvolutionPostProcess
  89050. * @param name The name of the effect.
  89051. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  89052. * @param options The required width/height ratio to downsize to before computing the render pass.
  89053. * @param camera The camera to apply the render pass to.
  89054. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89055. * @param engine The engine which the post process will be applied. (default: current engine)
  89056. * @param reusable If the post process can be reused on the same frame. (default: false)
  89057. * @param textureType Type of textures used when performing the post process. (default: 0)
  89058. */
  89059. function ConvolutionPostProcess(name,
  89060. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  89061. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  89062. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89063. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89064. _this.kernel = kernel;
  89065. _this.onApply = function (effect) {
  89066. effect.setFloat2("screenSize", _this.width, _this.height);
  89067. effect.setArray("kernel", _this.kernel);
  89068. };
  89069. return _this;
  89070. }
  89071. // Statics
  89072. /**
  89073. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89074. */
  89075. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  89076. /**
  89077. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89078. */
  89079. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  89080. /**
  89081. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89082. */
  89083. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  89084. /**
  89085. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89086. */
  89087. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  89088. /**
  89089. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89090. */
  89091. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  89092. /**
  89093. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  89094. */
  89095. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  89096. return ConvolutionPostProcess;
  89097. }(BABYLON.PostProcess));
  89098. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  89099. })(BABYLON || (BABYLON = {}));
  89100. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  89101. var BABYLON;
  89102. (function (BABYLON) {
  89103. /**
  89104. * Applies a kernel filter to the image
  89105. */
  89106. var FilterPostProcess = /** @class */ (function (_super) {
  89107. __extends(FilterPostProcess, _super);
  89108. /**
  89109. *
  89110. * @param name The name of the effect.
  89111. * @param kernelMatrix The matrix to be applied to the image
  89112. * @param options The required width/height ratio to downsize to before computing the render pass.
  89113. * @param camera The camera to apply the render pass to.
  89114. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89115. * @param engine The engine which the post process will be applied. (default: current engine)
  89116. * @param reusable If the post process can be reused on the same frame. (default: false)
  89117. */
  89118. function FilterPostProcess(name,
  89119. /** The matrix to be applied to the image */
  89120. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  89121. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  89122. _this.kernelMatrix = kernelMatrix;
  89123. _this.onApply = function (effect) {
  89124. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  89125. };
  89126. return _this;
  89127. }
  89128. return FilterPostProcess;
  89129. }(BABYLON.PostProcess));
  89130. BABYLON.FilterPostProcess = FilterPostProcess;
  89131. })(BABYLON || (BABYLON = {}));
  89132. //# sourceMappingURL=babylon.filterPostProcess.js.map
  89133. var BABYLON;
  89134. (function (BABYLON) {
  89135. /**
  89136. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  89137. */
  89138. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  89139. __extends(VolumetricLightScatteringPostProcess, _super);
  89140. /**
  89141. * @constructor
  89142. * @param name The post-process name
  89143. * @param 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)
  89144. * @param camera The camera that the post-process will be attached to
  89145. * @param mesh The mesh used to create the light scattering
  89146. * @param samples The post-process quality, default 100
  89147. * @param samplingModeThe post-process filtering mode
  89148. * @param engine The babylon engine
  89149. * @param reusable If the post-process is reusable
  89150. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  89151. */
  89152. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  89153. if (samples === void 0) { samples = 100; }
  89154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89155. 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;
  89156. _this._screenCoordinates = BABYLON.Vector2.Zero();
  89157. /**
  89158. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  89159. */
  89160. _this.customMeshPosition = BABYLON.Vector3.Zero();
  89161. /**
  89162. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  89163. */
  89164. _this.useCustomMeshPosition = false;
  89165. /**
  89166. * If the post-process should inverse the light scattering direction
  89167. */
  89168. _this.invert = true;
  89169. /**
  89170. * Array containing the excluded meshes not rendered in the internal pass
  89171. */
  89172. _this.excludedMeshes = new Array();
  89173. /**
  89174. * Controls the overall intensity of the post-process
  89175. */
  89176. _this.exposure = 0.3;
  89177. /**
  89178. * Dissipates each sample's contribution in range [0, 1]
  89179. */
  89180. _this.decay = 0.96815;
  89181. /**
  89182. * Controls the overall intensity of each sample
  89183. */
  89184. _this.weight = 0.58767;
  89185. /**
  89186. * Controls the density of each sample
  89187. */
  89188. _this.density = 0.926;
  89189. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  89190. engine = scene.getEngine();
  89191. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  89192. // Configure mesh
  89193. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  89194. // Configure
  89195. _this._createPass(scene, ratio.passRatio || ratio);
  89196. _this.onActivate = function (camera) {
  89197. if (!_this.isSupported) {
  89198. _this.dispose(camera);
  89199. }
  89200. _this.onActivate = null;
  89201. };
  89202. _this.onApplyObservable.add(function (effect) {
  89203. _this._updateMeshScreenCoordinates(scene);
  89204. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  89205. effect.setFloat("exposure", _this.exposure);
  89206. effect.setFloat("decay", _this.decay);
  89207. effect.setFloat("weight", _this.weight);
  89208. effect.setFloat("density", _this.density);
  89209. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  89210. });
  89211. return _this;
  89212. }
  89213. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  89214. /**
  89215. * @hidden
  89216. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  89217. */
  89218. get: function () {
  89219. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  89220. return false;
  89221. },
  89222. set: function (useDiffuseColor) {
  89223. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  89224. },
  89225. enumerable: true,
  89226. configurable: true
  89227. });
  89228. /**
  89229. * Returns the string "VolumetricLightScatteringPostProcess"
  89230. * @returns "VolumetricLightScatteringPostProcess"
  89231. */
  89232. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  89233. return "VolumetricLightScatteringPostProcess";
  89234. };
  89235. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  89236. var mesh = subMesh.getMesh();
  89237. // Render this.mesh as default
  89238. if (mesh === this.mesh && mesh.material) {
  89239. return mesh.material.isReady(mesh);
  89240. }
  89241. var defines = [];
  89242. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89243. var material = subMesh.getMaterial();
  89244. // Alpha test
  89245. if (material) {
  89246. if (material.needAlphaTesting()) {
  89247. defines.push("#define ALPHATEST");
  89248. }
  89249. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89250. attribs.push(BABYLON.VertexBuffer.UVKind);
  89251. defines.push("#define UV1");
  89252. }
  89253. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  89254. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89255. defines.push("#define UV2");
  89256. }
  89257. }
  89258. // Bones
  89259. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89260. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89261. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89262. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89263. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89264. }
  89265. else {
  89266. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89267. }
  89268. // Instances
  89269. if (useInstances) {
  89270. defines.push("#define INSTANCES");
  89271. attribs.push("world0");
  89272. attribs.push("world1");
  89273. attribs.push("world2");
  89274. attribs.push("world3");
  89275. }
  89276. // Get correct effect
  89277. var join = defines.join("\n");
  89278. if (this._cachedDefines !== join) {
  89279. this._cachedDefines = join;
  89280. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  89281. }
  89282. return this._volumetricLightScatteringPass.isReady();
  89283. };
  89284. /**
  89285. * Sets the new light position for light scattering effect
  89286. * @param position The new custom light position
  89287. */
  89288. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  89289. this.customMeshPosition = position;
  89290. };
  89291. /**
  89292. * Returns the light position for light scattering effect
  89293. * @return Vector3 The custom light position
  89294. */
  89295. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  89296. return this.customMeshPosition;
  89297. };
  89298. /**
  89299. * Disposes the internal assets and detaches the post-process from the camera
  89300. */
  89301. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  89302. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  89303. if (rttIndex !== -1) {
  89304. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  89305. }
  89306. this._volumetricLightScatteringRTT.dispose();
  89307. _super.prototype.dispose.call(this, camera);
  89308. };
  89309. /**
  89310. * Returns the render target texture used by the post-process
  89311. * @return the render target texture used by the post-process
  89312. */
  89313. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  89314. return this._volumetricLightScatteringRTT;
  89315. };
  89316. // Private methods
  89317. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  89318. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  89319. return true;
  89320. }
  89321. return false;
  89322. };
  89323. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  89324. var _this = this;
  89325. var engine = scene.getEngine();
  89326. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89327. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89328. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89329. this._volumetricLightScatteringRTT.renderList = null;
  89330. this._volumetricLightScatteringRTT.renderParticles = false;
  89331. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  89332. var camera = this.getCamera();
  89333. if (camera) {
  89334. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89335. }
  89336. else {
  89337. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89338. }
  89339. // Custom render function for submeshes
  89340. var renderSubMesh = function (subMesh) {
  89341. var mesh = subMesh.getRenderingMesh();
  89342. if (_this._meshExcluded(mesh)) {
  89343. return;
  89344. }
  89345. var material = subMesh.getMaterial();
  89346. if (!material) {
  89347. return;
  89348. }
  89349. var scene = mesh.getScene();
  89350. var engine = scene.getEngine();
  89351. // Culling
  89352. engine.setState(material.backFaceCulling);
  89353. // Managing instances
  89354. var batch = mesh._getInstancesRenderList(subMesh._id);
  89355. if (batch.mustReturn) {
  89356. return;
  89357. }
  89358. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  89359. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  89360. var effect = _this._volumetricLightScatteringPass;
  89361. if (mesh === _this.mesh) {
  89362. if (subMesh.effect) {
  89363. effect = subMesh.effect;
  89364. }
  89365. else {
  89366. effect = material.getEffect();
  89367. }
  89368. }
  89369. engine.enableEffect(effect);
  89370. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  89371. if (mesh === _this.mesh) {
  89372. material.bind(mesh.getWorldMatrix(), mesh);
  89373. }
  89374. else {
  89375. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  89376. // Alpha test
  89377. if (material && material.needAlphaTesting()) {
  89378. var alphaTexture = material.getAlphaTestTexture();
  89379. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  89380. if (alphaTexture) {
  89381. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89382. }
  89383. }
  89384. // Bones
  89385. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89386. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89387. }
  89388. }
  89389. // Draw
  89390. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  89391. }
  89392. };
  89393. // Render target texture callbacks
  89394. var savedSceneClearColor;
  89395. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  89396. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  89397. savedSceneClearColor = scene.clearColor;
  89398. scene.clearColor = sceneClearColor;
  89399. });
  89400. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  89401. scene.clearColor = savedSceneClearColor;
  89402. });
  89403. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89404. var engine = scene.getEngine();
  89405. var index;
  89406. if (depthOnlySubMeshes.length) {
  89407. engine.setColorWrite(false);
  89408. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89409. renderSubMesh(depthOnlySubMeshes.data[index]);
  89410. }
  89411. engine.setColorWrite(true);
  89412. }
  89413. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89414. renderSubMesh(opaqueSubMeshes.data[index]);
  89415. }
  89416. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89417. renderSubMesh(alphaTestSubMeshes.data[index]);
  89418. }
  89419. if (transparentSubMeshes.length) {
  89420. // Sort sub meshes
  89421. for (index = 0; index < transparentSubMeshes.length; index++) {
  89422. var submesh = transparentSubMeshes.data[index];
  89423. var boundingInfo = submesh.getBoundingInfo();
  89424. if (boundingInfo && scene.activeCamera) {
  89425. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  89426. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  89427. }
  89428. }
  89429. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  89430. sortedArray.sort(function (a, b) {
  89431. // Alpha index first
  89432. if (a._alphaIndex > b._alphaIndex) {
  89433. return 1;
  89434. }
  89435. if (a._alphaIndex < b._alphaIndex) {
  89436. return -1;
  89437. }
  89438. // Then distance to camera
  89439. if (a._distanceToCamera < b._distanceToCamera) {
  89440. return 1;
  89441. }
  89442. if (a._distanceToCamera > b._distanceToCamera) {
  89443. return -1;
  89444. }
  89445. return 0;
  89446. });
  89447. // Render sub meshes
  89448. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  89449. for (index = 0; index < sortedArray.length; index++) {
  89450. renderSubMesh(sortedArray[index]);
  89451. }
  89452. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89453. }
  89454. };
  89455. };
  89456. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  89457. var transform = scene.getTransformMatrix();
  89458. var meshPosition;
  89459. if (this.useCustomMeshPosition) {
  89460. meshPosition = this.customMeshPosition;
  89461. }
  89462. else if (this.attachedNode) {
  89463. meshPosition = this.attachedNode.position;
  89464. }
  89465. else {
  89466. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  89467. }
  89468. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  89469. this._screenCoordinates.x = pos.x / this._viewPort.width;
  89470. this._screenCoordinates.y = pos.y / this._viewPort.height;
  89471. if (this.invert) {
  89472. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  89473. }
  89474. };
  89475. // Static methods
  89476. /**
  89477. * Creates a default mesh for the Volumeric Light Scattering post-process
  89478. * @param name The mesh name
  89479. * @param scene The scene where to create the mesh
  89480. * @return the default mesh
  89481. */
  89482. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  89483. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  89484. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  89485. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  89486. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  89487. mesh.material = material;
  89488. return mesh;
  89489. };
  89490. __decorate([
  89491. BABYLON.serializeAsVector3()
  89492. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  89493. __decorate([
  89494. BABYLON.serialize()
  89495. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  89496. __decorate([
  89497. BABYLON.serialize()
  89498. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  89499. __decorate([
  89500. BABYLON.serializeAsMeshReference()
  89501. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  89502. __decorate([
  89503. BABYLON.serialize()
  89504. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  89505. __decorate([
  89506. BABYLON.serialize()
  89507. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  89508. __decorate([
  89509. BABYLON.serialize()
  89510. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  89511. __decorate([
  89512. BABYLON.serialize()
  89513. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  89514. __decorate([
  89515. BABYLON.serialize()
  89516. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  89517. return VolumetricLightScatteringPostProcess;
  89518. }(BABYLON.PostProcess));
  89519. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  89520. })(BABYLON || (BABYLON = {}));
  89521. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  89522. var BABYLON;
  89523. (function (BABYLON) {
  89524. /**
  89525. *
  89526. * This post-process allows the modification of rendered colors by using
  89527. * a 'look-up table' (LUT). This effect is also called Color Grading.
  89528. *
  89529. * The object needs to be provided an url to a texture containing the color
  89530. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  89531. * Use an image editing software to tweak the LUT to match your needs.
  89532. *
  89533. * For an example of a color LUT, see here:
  89534. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  89535. * For explanations on color grading, see here:
  89536. * @see http://udn.epicgames.com/Three/ColorGrading.html
  89537. *
  89538. */
  89539. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  89540. __extends(ColorCorrectionPostProcess, _super);
  89541. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  89542. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  89543. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89544. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  89545. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89546. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89547. _this.onApply = function (effect) {
  89548. effect.setTexture("colorTable", _this._colorTableTexture);
  89549. };
  89550. return _this;
  89551. }
  89552. return ColorCorrectionPostProcess;
  89553. }(BABYLON.PostProcess));
  89554. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  89555. })(BABYLON || (BABYLON = {}));
  89556. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  89557. var BABYLON;
  89558. (function (BABYLON) {
  89559. /** Defines operator used for tonemapping */
  89560. var TonemappingOperator;
  89561. (function (TonemappingOperator) {
  89562. /** Hable */
  89563. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  89564. /** Reinhard */
  89565. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  89566. /** HejiDawson */
  89567. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  89568. /** Photographic */
  89569. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  89570. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  89571. /**
  89572. * Defines a post process to apply tone mapping
  89573. */
  89574. var TonemapPostProcess = /** @class */ (function (_super) {
  89575. __extends(TonemapPostProcess, _super);
  89576. /**
  89577. * Creates a new TonemapPostProcess
  89578. * @param name defines the name of the postprocess
  89579. * @param _operator defines the operator to use
  89580. * @param exposureAdjustment defines the required exposure adjustement
  89581. * @param camera defines the camera to use (can be null)
  89582. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  89583. * @param engine defines the hosting engine (can be ignore if camera is set)
  89584. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  89585. */
  89586. function TonemapPostProcess(name, _operator,
  89587. /** Defines the required exposure adjustement */
  89588. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  89589. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89590. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89591. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  89592. _this._operator = _operator;
  89593. _this.exposureAdjustment = exposureAdjustment;
  89594. var defines = "#define ";
  89595. if (_this._operator === TonemappingOperator.Hable) {
  89596. defines += "HABLE_TONEMAPPING";
  89597. }
  89598. else if (_this._operator === TonemappingOperator.Reinhard) {
  89599. defines += "REINHARD_TONEMAPPING";
  89600. }
  89601. else if (_this._operator === TonemappingOperator.HejiDawson) {
  89602. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  89603. }
  89604. else if (_this._operator === TonemappingOperator.Photographic) {
  89605. defines += "PHOTOGRAPHIC_TONEMAPPING";
  89606. }
  89607. //sadly a second call to create the effect.
  89608. _this.updateEffect(defines);
  89609. _this.onApply = function (effect) {
  89610. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  89611. };
  89612. return _this;
  89613. }
  89614. return TonemapPostProcess;
  89615. }(BABYLON.PostProcess));
  89616. BABYLON.TonemapPostProcess = TonemapPostProcess;
  89617. })(BABYLON || (BABYLON = {}));
  89618. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  89619. var BABYLON;
  89620. (function (BABYLON) {
  89621. /**
  89622. * DisplayPassPostProcess which produces an output the same as it's input
  89623. */
  89624. var DisplayPassPostProcess = /** @class */ (function (_super) {
  89625. __extends(DisplayPassPostProcess, _super);
  89626. /**
  89627. * Creates the DisplayPassPostProcess
  89628. * @param name The name of the effect.
  89629. * @param options The required width/height ratio to downsize to before computing the render pass.
  89630. * @param camera The camera to apply the render pass to.
  89631. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89632. * @param engine The engine which the post process will be applied. (default: current engine)
  89633. * @param reusable If the post process can be reused on the same frame. (default: false)
  89634. */
  89635. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  89636. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  89637. }
  89638. return DisplayPassPostProcess;
  89639. }(BABYLON.PostProcess));
  89640. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  89641. })(BABYLON || (BABYLON = {}));
  89642. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  89643. var BABYLON;
  89644. (function (BABYLON) {
  89645. /**
  89646. * Extracts highlights from the image
  89647. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89648. */
  89649. var HighlightsPostProcess = /** @class */ (function (_super) {
  89650. __extends(HighlightsPostProcess, _super);
  89651. /**
  89652. * Extracts highlights from the image
  89653. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89654. * @param name The name of the effect.
  89655. * @param options The required width/height ratio to downsize to before computing the render pass.
  89656. * @param camera The camera to apply the render pass to.
  89657. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89658. * @param engine The engine which the post process will be applied. (default: current engine)
  89659. * @param reusable If the post process can be reused on the same frame. (default: false)
  89660. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  89661. */
  89662. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  89663. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89664. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89665. }
  89666. return HighlightsPostProcess;
  89667. }(BABYLON.PostProcess));
  89668. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  89669. })(BABYLON || (BABYLON = {}));
  89670. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  89671. var BABYLON;
  89672. (function (BABYLON) {
  89673. /**
  89674. * ImageProcessingPostProcess
  89675. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  89676. */
  89677. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  89678. __extends(ImageProcessingPostProcess, _super);
  89679. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  89680. if (camera === void 0) { camera = null; }
  89681. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89682. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  89683. _this._fromLinearSpace = true;
  89684. /**
  89685. * Defines cache preventing GC.
  89686. */
  89687. _this._defines = {
  89688. IMAGEPROCESSING: false,
  89689. VIGNETTE: false,
  89690. VIGNETTEBLENDMODEMULTIPLY: false,
  89691. VIGNETTEBLENDMODEOPAQUE: false,
  89692. TONEMAPPING: false,
  89693. TONEMAPPING_ACES: false,
  89694. CONTRAST: false,
  89695. COLORCURVES: false,
  89696. COLORGRADING: false,
  89697. COLORGRADING3D: false,
  89698. FROMLINEARSPACE: false,
  89699. SAMPLER3DGREENDEPTH: false,
  89700. SAMPLER3DBGRMAP: false,
  89701. IMAGEPROCESSINGPOSTPROCESS: false,
  89702. EXPOSURE: false,
  89703. };
  89704. // Setup the configuration as forced by the constructor. This would then not force the
  89705. // scene materials output in linear space and let untouched the default forward pass.
  89706. if (imageProcessingConfiguration) {
  89707. imageProcessingConfiguration.applyByPostProcess = true;
  89708. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  89709. // This will cause the shader to be compiled
  89710. _this.fromLinearSpace = false;
  89711. }
  89712. // Setup the default processing configuration to the scene.
  89713. else {
  89714. _this._attachImageProcessingConfiguration(null, true);
  89715. _this.imageProcessingConfiguration.applyByPostProcess = true;
  89716. }
  89717. _this.onApply = function (effect) {
  89718. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  89719. };
  89720. return _this;
  89721. }
  89722. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  89723. /**
  89724. * Gets the image processing configuration used either in this material.
  89725. */
  89726. get: function () {
  89727. return this._imageProcessingConfiguration;
  89728. },
  89729. /**
  89730. * Sets the Default image processing configuration used either in the this material.
  89731. *
  89732. * If sets to null, the scene one is in use.
  89733. */
  89734. set: function (value) {
  89735. this._attachImageProcessingConfiguration(value);
  89736. },
  89737. enumerable: true,
  89738. configurable: true
  89739. });
  89740. /**
  89741. * Attaches a new image processing configuration to the PBR Material.
  89742. * @param configuration
  89743. */
  89744. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  89745. var _this = this;
  89746. if (doNotBuild === void 0) { doNotBuild = false; }
  89747. if (configuration === this._imageProcessingConfiguration) {
  89748. return;
  89749. }
  89750. // Detaches observer.
  89751. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89752. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89753. }
  89754. // Pick the scene configuration if needed.
  89755. if (!configuration) {
  89756. var scene = null;
  89757. var engine = this.getEngine();
  89758. var camera = this.getCamera();
  89759. if (camera) {
  89760. scene = camera.getScene();
  89761. }
  89762. else if (engine && engine.scenes) {
  89763. var scenes = engine.scenes;
  89764. scene = scenes[scenes.length - 1];
  89765. }
  89766. else {
  89767. scene = BABYLON.Engine.LastCreatedScene;
  89768. }
  89769. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  89770. }
  89771. else {
  89772. this._imageProcessingConfiguration = configuration;
  89773. }
  89774. // Attaches observer.
  89775. if (this._imageProcessingConfiguration) {
  89776. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89777. _this._updateParameters();
  89778. });
  89779. }
  89780. // Ensure the effect will be rebuilt.
  89781. if (!doNotBuild) {
  89782. this._updateParameters();
  89783. }
  89784. };
  89785. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  89786. /**
  89787. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89788. */
  89789. get: function () {
  89790. return this.imageProcessingConfiguration.colorCurves;
  89791. },
  89792. /**
  89793. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89794. */
  89795. set: function (value) {
  89796. this.imageProcessingConfiguration.colorCurves = value;
  89797. },
  89798. enumerable: true,
  89799. configurable: true
  89800. });
  89801. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  89802. /**
  89803. * Gets wether the color curves effect is enabled.
  89804. */
  89805. get: function () {
  89806. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89807. },
  89808. /**
  89809. * Sets wether the color curves effect is enabled.
  89810. */
  89811. set: function (value) {
  89812. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89813. },
  89814. enumerable: true,
  89815. configurable: true
  89816. });
  89817. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  89818. /**
  89819. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89820. */
  89821. get: function () {
  89822. return this.imageProcessingConfiguration.colorGradingTexture;
  89823. },
  89824. /**
  89825. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89826. */
  89827. set: function (value) {
  89828. this.imageProcessingConfiguration.colorGradingTexture = value;
  89829. },
  89830. enumerable: true,
  89831. configurable: true
  89832. });
  89833. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  89834. /**
  89835. * Gets wether the color grading effect is enabled.
  89836. */
  89837. get: function () {
  89838. return this.imageProcessingConfiguration.colorGradingEnabled;
  89839. },
  89840. /**
  89841. * Gets wether the color grading effect is enabled.
  89842. */
  89843. set: function (value) {
  89844. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89845. },
  89846. enumerable: true,
  89847. configurable: true
  89848. });
  89849. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  89850. /**
  89851. * Gets exposure used in the effect.
  89852. */
  89853. get: function () {
  89854. return this.imageProcessingConfiguration.exposure;
  89855. },
  89856. /**
  89857. * Sets exposure used in the effect.
  89858. */
  89859. set: function (value) {
  89860. this.imageProcessingConfiguration.exposure = value;
  89861. },
  89862. enumerable: true,
  89863. configurable: true
  89864. });
  89865. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  89866. /**
  89867. * Gets wether tonemapping is enabled or not.
  89868. */
  89869. get: function () {
  89870. return this._imageProcessingConfiguration.toneMappingEnabled;
  89871. },
  89872. /**
  89873. * Sets wether tonemapping is enabled or not
  89874. */
  89875. set: function (value) {
  89876. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89877. },
  89878. enumerable: true,
  89879. configurable: true
  89880. });
  89881. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  89882. /**
  89883. * Gets contrast used in the effect.
  89884. */
  89885. get: function () {
  89886. return this.imageProcessingConfiguration.contrast;
  89887. },
  89888. /**
  89889. * Sets contrast used in the effect.
  89890. */
  89891. set: function (value) {
  89892. this.imageProcessingConfiguration.contrast = value;
  89893. },
  89894. enumerable: true,
  89895. configurable: true
  89896. });
  89897. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  89898. /**
  89899. * Gets Vignette stretch size.
  89900. */
  89901. get: function () {
  89902. return this.imageProcessingConfiguration.vignetteStretch;
  89903. },
  89904. /**
  89905. * Sets Vignette stretch size.
  89906. */
  89907. set: function (value) {
  89908. this.imageProcessingConfiguration.vignetteStretch = value;
  89909. },
  89910. enumerable: true,
  89911. configurable: true
  89912. });
  89913. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  89914. /**
  89915. * Gets Vignette centre X Offset.
  89916. */
  89917. get: function () {
  89918. return this.imageProcessingConfiguration.vignetteCentreX;
  89919. },
  89920. /**
  89921. * Sets Vignette centre X Offset.
  89922. */
  89923. set: function (value) {
  89924. this.imageProcessingConfiguration.vignetteCentreX = value;
  89925. },
  89926. enumerable: true,
  89927. configurable: true
  89928. });
  89929. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  89930. /**
  89931. * Gets Vignette centre Y Offset.
  89932. */
  89933. get: function () {
  89934. return this.imageProcessingConfiguration.vignetteCentreY;
  89935. },
  89936. /**
  89937. * Sets Vignette centre Y Offset.
  89938. */
  89939. set: function (value) {
  89940. this.imageProcessingConfiguration.vignetteCentreY = value;
  89941. },
  89942. enumerable: true,
  89943. configurable: true
  89944. });
  89945. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  89946. /**
  89947. * Gets Vignette weight or intensity of the vignette effect.
  89948. */
  89949. get: function () {
  89950. return this.imageProcessingConfiguration.vignetteWeight;
  89951. },
  89952. /**
  89953. * Sets Vignette weight or intensity of the vignette effect.
  89954. */
  89955. set: function (value) {
  89956. this.imageProcessingConfiguration.vignetteWeight = value;
  89957. },
  89958. enumerable: true,
  89959. configurable: true
  89960. });
  89961. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  89962. /**
  89963. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89964. * if vignetteEnabled is set to true.
  89965. */
  89966. get: function () {
  89967. return this.imageProcessingConfiguration.vignetteColor;
  89968. },
  89969. /**
  89970. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89971. * if vignetteEnabled is set to true.
  89972. */
  89973. set: function (value) {
  89974. this.imageProcessingConfiguration.vignetteColor = value;
  89975. },
  89976. enumerable: true,
  89977. configurable: true
  89978. });
  89979. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  89980. /**
  89981. * Gets Camera field of view used by the Vignette effect.
  89982. */
  89983. get: function () {
  89984. return this.imageProcessingConfiguration.vignetteCameraFov;
  89985. },
  89986. /**
  89987. * Sets Camera field of view used by the Vignette effect.
  89988. */
  89989. set: function (value) {
  89990. this.imageProcessingConfiguration.vignetteCameraFov = value;
  89991. },
  89992. enumerable: true,
  89993. configurable: true
  89994. });
  89995. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  89996. /**
  89997. * Gets the vignette blend mode allowing different kind of effect.
  89998. */
  89999. get: function () {
  90000. return this.imageProcessingConfiguration.vignetteBlendMode;
  90001. },
  90002. /**
  90003. * Sets the vignette blend mode allowing different kind of effect.
  90004. */
  90005. set: function (value) {
  90006. this.imageProcessingConfiguration.vignetteBlendMode = value;
  90007. },
  90008. enumerable: true,
  90009. configurable: true
  90010. });
  90011. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  90012. /**
  90013. * Gets wether the vignette effect is enabled.
  90014. */
  90015. get: function () {
  90016. return this.imageProcessingConfiguration.vignetteEnabled;
  90017. },
  90018. /**
  90019. * Sets wether the vignette effect is enabled.
  90020. */
  90021. set: function (value) {
  90022. this.imageProcessingConfiguration.vignetteEnabled = value;
  90023. },
  90024. enumerable: true,
  90025. configurable: true
  90026. });
  90027. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  90028. /**
  90029. * Gets wether the input of the processing is in Gamma or Linear Space.
  90030. */
  90031. get: function () {
  90032. return this._fromLinearSpace;
  90033. },
  90034. /**
  90035. * Sets wether the input of the processing is in Gamma or Linear Space.
  90036. */
  90037. set: function (value) {
  90038. if (this._fromLinearSpace === value) {
  90039. return;
  90040. }
  90041. this._fromLinearSpace = value;
  90042. this._updateParameters();
  90043. },
  90044. enumerable: true,
  90045. configurable: true
  90046. });
  90047. /**
  90048. * "ImageProcessingPostProcess"
  90049. * @returns "ImageProcessingPostProcess"
  90050. */
  90051. ImageProcessingPostProcess.prototype.getClassName = function () {
  90052. return "ImageProcessingPostProcess";
  90053. };
  90054. ImageProcessingPostProcess.prototype._updateParameters = function () {
  90055. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  90056. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  90057. var defines = "";
  90058. for (var define in this._defines) {
  90059. if (this._defines[define]) {
  90060. defines += "#define " + define + ";\r\n";
  90061. }
  90062. }
  90063. var samplers = ["textureSampler"];
  90064. var uniforms = ["scale"];
  90065. if (BABYLON.ImageProcessingConfiguration) {
  90066. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  90067. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  90068. }
  90069. this.updateEffect(defines, uniforms, samplers);
  90070. };
  90071. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  90072. _super.prototype.dispose.call(this, camera);
  90073. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90074. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90075. }
  90076. if (this._imageProcessingConfiguration) {
  90077. this.imageProcessingConfiguration.applyByPostProcess = false;
  90078. }
  90079. };
  90080. __decorate([
  90081. BABYLON.serialize()
  90082. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  90083. return ImageProcessingPostProcess;
  90084. }(BABYLON.PostProcess));
  90085. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  90086. })(BABYLON || (BABYLON = {}));
  90087. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  90088. var BABYLON;
  90089. (function (BABYLON) {
  90090. /**
  90091. * Class used to store bone information
  90092. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  90093. */
  90094. var Bone = /** @class */ (function (_super) {
  90095. __extends(Bone, _super);
  90096. /**
  90097. * Create a new bone
  90098. * @param name defines the bone name
  90099. * @param skeleton defines the parent skeleton
  90100. * @param parentBone defines the parent (can be null if the bone is the root)
  90101. * @param localMatrix defines the local matrix
  90102. * @param restPose defines the rest pose matrix
  90103. * @param baseMatrix defines the base matrix
  90104. * @param index defines index of the bone in the hiearchy
  90105. */
  90106. function Bone(
  90107. /**
  90108. * defines the bone name
  90109. */
  90110. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  90111. if (parentBone === void 0) { parentBone = null; }
  90112. if (localMatrix === void 0) { localMatrix = null; }
  90113. if (restPose === void 0) { restPose = null; }
  90114. if (baseMatrix === void 0) { baseMatrix = null; }
  90115. if (index === void 0) { index = null; }
  90116. var _this = _super.call(this, name, skeleton.getScene()) || this;
  90117. _this.name = name;
  90118. /**
  90119. * Gets the list of child bones
  90120. */
  90121. _this.children = new Array();
  90122. /** Gets the animations associated with this bone */
  90123. _this.animations = new Array();
  90124. /**
  90125. * @hidden Internal only
  90126. * Set this value to map this bone to a different index in the transform matrices
  90127. * Set this value to -1 to exclude the bone from the transform matrices
  90128. */
  90129. _this._index = null;
  90130. _this._absoluteTransform = new BABYLON.Matrix();
  90131. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  90132. _this._scalingDeterminant = 1;
  90133. _this._worldTransform = new BABYLON.Matrix();
  90134. _this._needToDecompose = true;
  90135. _this._needToCompose = false;
  90136. _this._skeleton = skeleton;
  90137. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  90138. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  90139. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  90140. _this._index = index;
  90141. skeleton.bones.push(_this);
  90142. _this.setParent(parentBone, false);
  90143. if (baseMatrix || localMatrix) {
  90144. _this._updateDifferenceMatrix();
  90145. }
  90146. return _this;
  90147. }
  90148. Object.defineProperty(Bone.prototype, "_matrix", {
  90149. /** @hidden */
  90150. get: function () {
  90151. this._compose();
  90152. return this._localMatrix;
  90153. },
  90154. /** @hidden */
  90155. set: function (value) {
  90156. this._localMatrix.copyFrom(value);
  90157. this._needToDecompose = true;
  90158. },
  90159. enumerable: true,
  90160. configurable: true
  90161. });
  90162. // Members
  90163. /**
  90164. * Gets the parent skeleton
  90165. * @returns a skeleton
  90166. */
  90167. Bone.prototype.getSkeleton = function () {
  90168. return this._skeleton;
  90169. };
  90170. /**
  90171. * Gets parent bone
  90172. * @returns a bone or null if the bone is the root of the bone hierarchy
  90173. */
  90174. Bone.prototype.getParent = function () {
  90175. return this._parent;
  90176. };
  90177. /**
  90178. * Sets the parent bone
  90179. * @param parent defines the parent (can be null if the bone is the root)
  90180. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90181. */
  90182. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  90183. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90184. if (this._parent === parent) {
  90185. return;
  90186. }
  90187. if (this._parent) {
  90188. var index = this._parent.children.indexOf(this);
  90189. if (index !== -1) {
  90190. this._parent.children.splice(index, 1);
  90191. }
  90192. }
  90193. this._parent = parent;
  90194. if (this._parent) {
  90195. this._parent.children.push(this);
  90196. }
  90197. if (updateDifferenceMatrix) {
  90198. this._updateDifferenceMatrix();
  90199. }
  90200. this.markAsDirty();
  90201. };
  90202. /**
  90203. * Gets the local matrix
  90204. * @returns a matrix
  90205. */
  90206. Bone.prototype.getLocalMatrix = function () {
  90207. this._compose();
  90208. return this._localMatrix;
  90209. };
  90210. /**
  90211. * Gets the base matrix (initial matrix which remains unchanged)
  90212. * @returns a matrix
  90213. */
  90214. Bone.prototype.getBaseMatrix = function () {
  90215. return this._baseMatrix;
  90216. };
  90217. /**
  90218. * Gets the rest pose matrix
  90219. * @returns a matrix
  90220. */
  90221. Bone.prototype.getRestPose = function () {
  90222. return this._restPose;
  90223. };
  90224. /**
  90225. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  90226. */
  90227. Bone.prototype.getWorldMatrix = function () {
  90228. return this._worldTransform;
  90229. };
  90230. /**
  90231. * Sets the local matrix to rest pose matrix
  90232. */
  90233. Bone.prototype.returnToRest = function () {
  90234. this.updateMatrix(this._restPose.clone());
  90235. };
  90236. /**
  90237. * Gets the inverse of the absolute transform matrix.
  90238. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  90239. * @returns a matrix
  90240. */
  90241. Bone.prototype.getInvertedAbsoluteTransform = function () {
  90242. return this._invertedAbsoluteTransform;
  90243. };
  90244. /**
  90245. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  90246. * @returns a matrix
  90247. */
  90248. Bone.prototype.getAbsoluteTransform = function () {
  90249. return this._absoluteTransform;
  90250. };
  90251. Object.defineProperty(Bone.prototype, "position", {
  90252. // Properties (matches AbstractMesh properties)
  90253. /** Gets or sets current position (in local space) */
  90254. get: function () {
  90255. this._decompose();
  90256. return this._localPosition;
  90257. },
  90258. set: function (newPosition) {
  90259. this._decompose();
  90260. this._localPosition.copyFrom(newPosition);
  90261. this._markAsDirtyAndCompose();
  90262. },
  90263. enumerable: true,
  90264. configurable: true
  90265. });
  90266. Object.defineProperty(Bone.prototype, "rotation", {
  90267. /** Gets or sets current rotation (in local space) */
  90268. get: function () {
  90269. return this.getRotation();
  90270. },
  90271. set: function (newRotation) {
  90272. this.setRotation(newRotation);
  90273. },
  90274. enumerable: true,
  90275. configurable: true
  90276. });
  90277. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  90278. /** Gets or sets current rotation quaternion (in local space) */
  90279. get: function () {
  90280. this._decompose();
  90281. return this._localRotation;
  90282. },
  90283. set: function (newRotation) {
  90284. this.setRotationQuaternion(newRotation);
  90285. },
  90286. enumerable: true,
  90287. configurable: true
  90288. });
  90289. Object.defineProperty(Bone.prototype, "scaling", {
  90290. /** Gets or sets current scaling (in local space) */
  90291. get: function () {
  90292. return this.getScale();
  90293. },
  90294. set: function (newScaling) {
  90295. this.setScale(newScaling);
  90296. },
  90297. enumerable: true,
  90298. configurable: true
  90299. });
  90300. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  90301. /**
  90302. * Gets the animation properties override
  90303. */
  90304. get: function () {
  90305. return this._skeleton.animationPropertiesOverride;
  90306. },
  90307. enumerable: true,
  90308. configurable: true
  90309. });
  90310. // Methods
  90311. Bone.prototype._decompose = function () {
  90312. if (!this._needToDecompose) {
  90313. return;
  90314. }
  90315. this._needToDecompose = false;
  90316. if (!this._localScaling) {
  90317. this._localScaling = BABYLON.Vector3.Zero();
  90318. this._localRotation = BABYLON.Quaternion.Zero();
  90319. this._localPosition = BABYLON.Vector3.Zero();
  90320. }
  90321. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  90322. };
  90323. Bone.prototype._compose = function () {
  90324. if (!this._needToCompose) {
  90325. return;
  90326. }
  90327. this._needToCompose = false;
  90328. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  90329. };
  90330. /**
  90331. * Update the base and local matrices
  90332. * @param matrix defines the new base or local matrix
  90333. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90334. * @param updateLocalMatrix defines if the local matrix should be updated
  90335. */
  90336. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  90337. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90338. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  90339. this._baseMatrix.copyFrom(matrix);
  90340. if (updateDifferenceMatrix) {
  90341. this._updateDifferenceMatrix();
  90342. }
  90343. if (updateLocalMatrix) {
  90344. this._localMatrix.copyFrom(matrix);
  90345. this._markAsDirtyAndDecompose();
  90346. }
  90347. else {
  90348. this.markAsDirty();
  90349. }
  90350. };
  90351. /** @hidden */
  90352. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  90353. if (updateChildren === void 0) { updateChildren = true; }
  90354. if (!rootMatrix) {
  90355. rootMatrix = this._baseMatrix;
  90356. }
  90357. if (this._parent) {
  90358. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90359. }
  90360. else {
  90361. this._absoluteTransform.copyFrom(rootMatrix);
  90362. }
  90363. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  90364. if (updateChildren) {
  90365. for (var index = 0; index < this.children.length; index++) {
  90366. this.children[index]._updateDifferenceMatrix();
  90367. }
  90368. }
  90369. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  90370. };
  90371. /**
  90372. * Flag the bone as dirty (Forcing it to update everything)
  90373. */
  90374. Bone.prototype.markAsDirty = function () {
  90375. this._currentRenderId++;
  90376. this._childRenderId++;
  90377. this._skeleton._markAsDirty();
  90378. };
  90379. Bone.prototype._markAsDirtyAndCompose = function () {
  90380. this.markAsDirty();
  90381. this._needToCompose = true;
  90382. };
  90383. Bone.prototype._markAsDirtyAndDecompose = function () {
  90384. this.markAsDirty();
  90385. this._needToDecompose = true;
  90386. };
  90387. /**
  90388. * Copy an animation range from another bone
  90389. * @param source defines the source bone
  90390. * @param rangeName defines the range name to copy
  90391. * @param frameOffset defines the frame offset
  90392. * @param rescaleAsRequired defines if rescaling must be applied if required
  90393. * @param skelDimensionsRatio defines the scaling ratio
  90394. * @returns true if operation was successful
  90395. */
  90396. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  90397. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90398. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  90399. // all animation may be coming from a library skeleton, so may need to create animation
  90400. if (this.animations.length === 0) {
  90401. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  90402. this.animations[0].setKeys([]);
  90403. }
  90404. // get animation info / verify there is such a range from the source bone
  90405. var sourceRange = source.animations[0].getRange(rangeName);
  90406. if (!sourceRange) {
  90407. return false;
  90408. }
  90409. var from = sourceRange.from;
  90410. var to = sourceRange.to;
  90411. var sourceKeys = source.animations[0].getKeys();
  90412. // rescaling prep
  90413. var sourceBoneLength = source.length;
  90414. var sourceParent = source.getParent();
  90415. var parent = this.getParent();
  90416. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  90417. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  90418. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  90419. var destKeys = this.animations[0].getKeys();
  90420. // loop vars declaration
  90421. var orig;
  90422. var origTranslation;
  90423. var mat;
  90424. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  90425. orig = sourceKeys[key];
  90426. if (orig.frame >= from && orig.frame <= to) {
  90427. if (rescaleAsRequired) {
  90428. mat = orig.value.clone();
  90429. // scale based on parent ratio, when bone has parent
  90430. if (parentScalingReqd) {
  90431. origTranslation = mat.getTranslation();
  90432. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  90433. // scale based on skeleton dimension ratio when root bone, and value is passed
  90434. }
  90435. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  90436. origTranslation = mat.getTranslation();
  90437. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  90438. // use original when root bone, and no data for skelDimensionsRatio
  90439. }
  90440. else {
  90441. mat = orig.value;
  90442. }
  90443. }
  90444. else {
  90445. mat = orig.value;
  90446. }
  90447. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  90448. }
  90449. }
  90450. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  90451. return true;
  90452. };
  90453. /**
  90454. * Translate the bone in local or world space
  90455. * @param vec The amount to translate the bone
  90456. * @param space The space that the translation is in
  90457. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90458. */
  90459. Bone.prototype.translate = function (vec, space, mesh) {
  90460. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90461. var lm = this.getLocalMatrix();
  90462. if (space == BABYLON.Space.LOCAL) {
  90463. lm.m[12] += vec.x;
  90464. lm.m[13] += vec.y;
  90465. lm.m[14] += vec.z;
  90466. }
  90467. else {
  90468. var wm = null;
  90469. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90470. if (mesh) {
  90471. wm = mesh.getWorldMatrix();
  90472. }
  90473. this._skeleton.computeAbsoluteTransforms();
  90474. var tmat = Bone._tmpMats[0];
  90475. var tvec = Bone._tmpVecs[0];
  90476. if (this._parent) {
  90477. if (mesh && wm) {
  90478. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90479. tmat.multiplyToRef(wm, tmat);
  90480. }
  90481. else {
  90482. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90483. }
  90484. }
  90485. tmat.m[12] = 0;
  90486. tmat.m[13] = 0;
  90487. tmat.m[14] = 0;
  90488. tmat.invert();
  90489. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  90490. lm.m[12] += tvec.x;
  90491. lm.m[13] += tvec.y;
  90492. lm.m[14] += tvec.z;
  90493. }
  90494. this._markAsDirtyAndDecompose();
  90495. };
  90496. /**
  90497. * Set the postion of the bone in local or world space
  90498. * @param position The position to set the bone
  90499. * @param space The space that the position is in
  90500. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90501. */
  90502. Bone.prototype.setPosition = function (position, space, mesh) {
  90503. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90504. var lm = this.getLocalMatrix();
  90505. if (space == BABYLON.Space.LOCAL) {
  90506. lm.m[12] = position.x;
  90507. lm.m[13] = position.y;
  90508. lm.m[14] = position.z;
  90509. }
  90510. else {
  90511. var wm = null;
  90512. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90513. if (mesh) {
  90514. wm = mesh.getWorldMatrix();
  90515. }
  90516. this._skeleton.computeAbsoluteTransforms();
  90517. var tmat = Bone._tmpMats[0];
  90518. var vec = Bone._tmpVecs[0];
  90519. if (this._parent) {
  90520. if (mesh && wm) {
  90521. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90522. tmat.multiplyToRef(wm, tmat);
  90523. }
  90524. else {
  90525. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90526. }
  90527. }
  90528. tmat.invert();
  90529. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  90530. lm.m[12] = vec.x;
  90531. lm.m[13] = vec.y;
  90532. lm.m[14] = vec.z;
  90533. }
  90534. this._markAsDirtyAndDecompose();
  90535. };
  90536. /**
  90537. * Set the absolute position of the bone (world space)
  90538. * @param position The position to set the bone
  90539. * @param mesh The mesh that this bone is attached to
  90540. */
  90541. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  90542. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  90543. };
  90544. /**
  90545. * Scale the bone on the x, y and z axes (in local space)
  90546. * @param x The amount to scale the bone on the x axis
  90547. * @param y The amount to scale the bone on the y axis
  90548. * @param z The amount to scale the bone on the z axis
  90549. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  90550. */
  90551. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  90552. if (scaleChildren === void 0) { scaleChildren = false; }
  90553. var locMat = this.getLocalMatrix();
  90554. // Apply new scaling on top of current local matrix
  90555. var scaleMat = Bone._tmpMats[0];
  90556. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  90557. scaleMat.multiplyToRef(locMat, locMat);
  90558. // Invert scaling matrix and apply the inverse to all children
  90559. scaleMat.invert();
  90560. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  90561. var child = _a[_i];
  90562. var cm = child.getLocalMatrix();
  90563. cm.multiplyToRef(scaleMat, cm);
  90564. cm.m[12] *= x;
  90565. cm.m[13] *= y;
  90566. cm.m[14] *= z;
  90567. child._markAsDirtyAndDecompose();
  90568. }
  90569. this._markAsDirtyAndDecompose();
  90570. if (scaleChildren) {
  90571. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  90572. var child = _c[_b];
  90573. child.scale(x, y, z, scaleChildren);
  90574. }
  90575. }
  90576. };
  90577. /**
  90578. * Set the bone scaling in local space
  90579. * @param scale defines the scaling vector
  90580. */
  90581. Bone.prototype.setScale = function (scale) {
  90582. this._decompose();
  90583. this._localScaling.copyFrom(scale);
  90584. this._markAsDirtyAndCompose();
  90585. };
  90586. /**
  90587. * Gets the current scaling in local space
  90588. * @returns the current scaling vector
  90589. */
  90590. Bone.prototype.getScale = function () {
  90591. this._decompose();
  90592. return this._localScaling;
  90593. };
  90594. /**
  90595. * Gets the current scaling in local space and stores it in a target vector
  90596. * @param result defines the target vector
  90597. */
  90598. Bone.prototype.getScaleToRef = function (result) {
  90599. this._decompose();
  90600. result.copyFrom(this._localScaling);
  90601. };
  90602. /**
  90603. * Set the yaw, pitch, and roll of the bone in local or world space
  90604. * @param yaw The rotation of the bone on the y axis
  90605. * @param pitch The rotation of the bone on the x axis
  90606. * @param roll The rotation of the bone on the z axis
  90607. * @param space The space that the axes of rotation are in
  90608. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90609. */
  90610. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  90611. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90612. if (space === BABYLON.Space.LOCAL) {
  90613. var quat = Bone._tmpQuat;
  90614. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  90615. this.setRotationQuaternion(quat, space, mesh);
  90616. return;
  90617. }
  90618. var rotMatInv = Bone._tmpMats[0];
  90619. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90620. return;
  90621. }
  90622. var rotMat = Bone._tmpMats[1];
  90623. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  90624. rotMatInv.multiplyToRef(rotMat, rotMat);
  90625. this._rotateWithMatrix(rotMat, space, mesh);
  90626. };
  90627. /**
  90628. * Add a rotation to the bone on an axis in local or world space
  90629. * @param axis The axis to rotate the bone on
  90630. * @param amount The amount to rotate the bone
  90631. * @param space The space that the axis is in
  90632. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90633. */
  90634. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  90635. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90636. var rmat = Bone._tmpMats[0];
  90637. rmat.m[12] = 0;
  90638. rmat.m[13] = 0;
  90639. rmat.m[14] = 0;
  90640. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  90641. this._rotateWithMatrix(rmat, space, mesh);
  90642. };
  90643. /**
  90644. * Set the rotation of the bone to a particular axis angle in local or world space
  90645. * @param axis The axis to rotate the bone on
  90646. * @param angle The angle that the bone should be rotated to
  90647. * @param space The space that the axis is in
  90648. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90649. */
  90650. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  90651. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90652. if (space === BABYLON.Space.LOCAL) {
  90653. var quat = Bone._tmpQuat;
  90654. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  90655. this.setRotationQuaternion(quat, space, mesh);
  90656. return;
  90657. }
  90658. var rotMatInv = Bone._tmpMats[0];
  90659. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90660. return;
  90661. }
  90662. var rotMat = Bone._tmpMats[1];
  90663. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  90664. rotMatInv.multiplyToRef(rotMat, rotMat);
  90665. this._rotateWithMatrix(rotMat, space, mesh);
  90666. };
  90667. /**
  90668. * Set the euler rotation of the bone in local of world space
  90669. * @param rotation The euler rotation that the bone should be set to
  90670. * @param space The space that the rotation is in
  90671. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90672. */
  90673. Bone.prototype.setRotation = function (rotation, space, mesh) {
  90674. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90675. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  90676. };
  90677. /**
  90678. * Set the quaternion rotation of the bone in local of world space
  90679. * @param quat The quaternion rotation that the bone should be set to
  90680. * @param space The space that the rotation is in
  90681. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90682. */
  90683. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  90684. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90685. if (space === BABYLON.Space.LOCAL) {
  90686. this._decompose();
  90687. this._localRotation.copyFrom(quat);
  90688. this._markAsDirtyAndCompose();
  90689. return;
  90690. }
  90691. var rotMatInv = Bone._tmpMats[0];
  90692. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90693. return;
  90694. }
  90695. var rotMat = Bone._tmpMats[1];
  90696. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  90697. rotMatInv.multiplyToRef(rotMat, rotMat);
  90698. this._rotateWithMatrix(rotMat, space, mesh);
  90699. };
  90700. /**
  90701. * Set the rotation matrix of the bone in local of world space
  90702. * @param rotMat The rotation matrix that the bone should be set to
  90703. * @param space The space that the rotation is in
  90704. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90705. */
  90706. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  90707. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90708. if (space === BABYLON.Space.LOCAL) {
  90709. var quat = Bone._tmpQuat;
  90710. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  90711. this.setRotationQuaternion(quat, space, mesh);
  90712. return;
  90713. }
  90714. var rotMatInv = Bone._tmpMats[0];
  90715. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90716. return;
  90717. }
  90718. var rotMat2 = Bone._tmpMats[1];
  90719. rotMat2.copyFrom(rotMat);
  90720. rotMatInv.multiplyToRef(rotMat, rotMat2);
  90721. this._rotateWithMatrix(rotMat2, space, mesh);
  90722. };
  90723. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  90724. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90725. var lmat = this.getLocalMatrix();
  90726. var lx = lmat.m[12];
  90727. var ly = lmat.m[13];
  90728. var lz = lmat.m[14];
  90729. var parent = this.getParent();
  90730. var parentScale = Bone._tmpMats[3];
  90731. var parentScaleInv = Bone._tmpMats[4];
  90732. if (parent && space == BABYLON.Space.WORLD) {
  90733. if (mesh) {
  90734. parentScale.copyFrom(mesh.getWorldMatrix());
  90735. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  90736. }
  90737. else {
  90738. parentScale.copyFrom(parent.getAbsoluteTransform());
  90739. }
  90740. parentScaleInv.copyFrom(parentScale);
  90741. parentScaleInv.invert();
  90742. lmat.multiplyToRef(parentScale, lmat);
  90743. lmat.multiplyToRef(rmat, lmat);
  90744. lmat.multiplyToRef(parentScaleInv, lmat);
  90745. }
  90746. else {
  90747. if (space == BABYLON.Space.WORLD && mesh) {
  90748. parentScale.copyFrom(mesh.getWorldMatrix());
  90749. parentScaleInv.copyFrom(parentScale);
  90750. parentScaleInv.invert();
  90751. lmat.multiplyToRef(parentScale, lmat);
  90752. lmat.multiplyToRef(rmat, lmat);
  90753. lmat.multiplyToRef(parentScaleInv, lmat);
  90754. }
  90755. else {
  90756. lmat.multiplyToRef(rmat, lmat);
  90757. }
  90758. }
  90759. lmat.m[12] = lx;
  90760. lmat.m[13] = ly;
  90761. lmat.m[14] = lz;
  90762. this.computeAbsoluteTransforms();
  90763. this._markAsDirtyAndDecompose();
  90764. };
  90765. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  90766. var scaleMatrix = Bone._tmpMats[2];
  90767. rotMatInv.copyFrom(this.getAbsoluteTransform());
  90768. if (mesh) {
  90769. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  90770. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  90771. }
  90772. rotMatInv.invert();
  90773. if (isNaN(rotMatInv.m[0])) {
  90774. // Matrix failed to invert.
  90775. // This can happen if scale is zero for example.
  90776. return false;
  90777. }
  90778. scaleMatrix.m[0] *= this._scalingDeterminant;
  90779. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  90780. return true;
  90781. };
  90782. /**
  90783. * Get the position of the bone in local or world space
  90784. * @param space The space that the returned position is in
  90785. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90786. * @returns The position of the bone
  90787. */
  90788. Bone.prototype.getPosition = function (space, mesh) {
  90789. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90790. if (mesh === void 0) { mesh = null; }
  90791. var pos = BABYLON.Vector3.Zero();
  90792. this.getPositionToRef(space, mesh, pos);
  90793. return pos;
  90794. };
  90795. /**
  90796. * Copy the position of the bone to a vector3 in local or world space
  90797. * @param space The space that the returned position is in
  90798. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90799. * @param result The vector3 to copy the position to
  90800. */
  90801. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  90802. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90803. if (space == BABYLON.Space.LOCAL) {
  90804. var lm = this.getLocalMatrix();
  90805. result.x = lm.m[12];
  90806. result.y = lm.m[13];
  90807. result.z = lm.m[14];
  90808. }
  90809. else {
  90810. var wm = null;
  90811. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90812. if (mesh) {
  90813. wm = mesh.getWorldMatrix();
  90814. }
  90815. this._skeleton.computeAbsoluteTransforms();
  90816. var tmat = Bone._tmpMats[0];
  90817. if (mesh && wm) {
  90818. tmat.copyFrom(this.getAbsoluteTransform());
  90819. tmat.multiplyToRef(wm, tmat);
  90820. }
  90821. else {
  90822. tmat = this.getAbsoluteTransform();
  90823. }
  90824. result.x = tmat.m[12];
  90825. result.y = tmat.m[13];
  90826. result.z = tmat.m[14];
  90827. }
  90828. };
  90829. /**
  90830. * Get the absolute position of the bone (world space)
  90831. * @param mesh The mesh that this bone is attached to
  90832. * @returns The absolute position of the bone
  90833. */
  90834. Bone.prototype.getAbsolutePosition = function (mesh) {
  90835. if (mesh === void 0) { mesh = null; }
  90836. var pos = BABYLON.Vector3.Zero();
  90837. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  90838. return pos;
  90839. };
  90840. /**
  90841. * Copy the absolute position of the bone (world space) to the result param
  90842. * @param mesh The mesh that this bone is attached to
  90843. * @param result The vector3 to copy the absolute position to
  90844. */
  90845. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  90846. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  90847. };
  90848. /**
  90849. * Compute the absolute transforms of this bone and its children
  90850. */
  90851. Bone.prototype.computeAbsoluteTransforms = function () {
  90852. this._compose();
  90853. if (this._parent) {
  90854. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90855. }
  90856. else {
  90857. this._absoluteTransform.copyFrom(this._localMatrix);
  90858. var poseMatrix = this._skeleton.getPoseMatrix();
  90859. if (poseMatrix) {
  90860. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  90861. }
  90862. }
  90863. var children = this.children;
  90864. var len = children.length;
  90865. for (var i = 0; i < len; i++) {
  90866. children[i].computeAbsoluteTransforms();
  90867. }
  90868. };
  90869. /**
  90870. * Get the world direction from an axis that is in the local space of the bone
  90871. * @param localAxis The local direction that is used to compute the world direction
  90872. * @param mesh The mesh that this bone is attached to
  90873. * @returns The world direction
  90874. */
  90875. Bone.prototype.getDirection = function (localAxis, mesh) {
  90876. if (mesh === void 0) { mesh = null; }
  90877. var result = BABYLON.Vector3.Zero();
  90878. this.getDirectionToRef(localAxis, mesh, result);
  90879. return result;
  90880. };
  90881. /**
  90882. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  90883. * @param localAxis The local direction that is used to compute the world direction
  90884. * @param mesh The mesh that this bone is attached to
  90885. * @param result The vector3 that the world direction will be copied to
  90886. */
  90887. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  90888. if (mesh === void 0) { mesh = null; }
  90889. var wm = null;
  90890. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90891. if (mesh) {
  90892. wm = mesh.getWorldMatrix();
  90893. }
  90894. this._skeleton.computeAbsoluteTransforms();
  90895. var mat = Bone._tmpMats[0];
  90896. mat.copyFrom(this.getAbsoluteTransform());
  90897. if (mesh && wm) {
  90898. mat.multiplyToRef(wm, mat);
  90899. }
  90900. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  90901. result.normalize();
  90902. };
  90903. /**
  90904. * Get the euler rotation of the bone in local or world space
  90905. * @param space The space that the rotation should be in
  90906. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90907. * @returns The euler rotation
  90908. */
  90909. Bone.prototype.getRotation = function (space, mesh) {
  90910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90911. if (mesh === void 0) { mesh = null; }
  90912. var result = BABYLON.Vector3.Zero();
  90913. this.getRotationToRef(space, mesh, result);
  90914. return result;
  90915. };
  90916. /**
  90917. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  90918. * @param space The space that the rotation should be in
  90919. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90920. * @param result The vector3 that the rotation should be copied to
  90921. */
  90922. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  90923. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90924. if (mesh === void 0) { mesh = null; }
  90925. var quat = Bone._tmpQuat;
  90926. this.getRotationQuaternionToRef(space, mesh, quat);
  90927. quat.toEulerAnglesToRef(result);
  90928. };
  90929. /**
  90930. * Get the quaternion rotation of the bone in either local or world space
  90931. * @param space The space that the rotation should be in
  90932. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90933. * @returns The quaternion rotation
  90934. */
  90935. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  90936. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90937. if (mesh === void 0) { mesh = null; }
  90938. var result = BABYLON.Quaternion.Identity();
  90939. this.getRotationQuaternionToRef(space, mesh, result);
  90940. return result;
  90941. };
  90942. /**
  90943. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  90944. * @param space The space that the rotation should be in
  90945. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90946. * @param result The quaternion that the rotation should be copied to
  90947. */
  90948. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  90949. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90950. if (mesh === void 0) { mesh = null; }
  90951. if (space == BABYLON.Space.LOCAL) {
  90952. this._decompose();
  90953. result.copyFrom(this._localRotation);
  90954. }
  90955. else {
  90956. var mat = Bone._tmpMats[0];
  90957. var amat = this.getAbsoluteTransform();
  90958. if (mesh) {
  90959. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90960. }
  90961. else {
  90962. mat.copyFrom(amat);
  90963. }
  90964. mat.m[0] *= this._scalingDeterminant;
  90965. mat.m[1] *= this._scalingDeterminant;
  90966. mat.m[2] *= this._scalingDeterminant;
  90967. mat.decompose(undefined, result, undefined);
  90968. }
  90969. };
  90970. /**
  90971. * Get the rotation matrix of the bone in local or world space
  90972. * @param space The space that the rotation should be in
  90973. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90974. * @returns The rotation matrix
  90975. */
  90976. Bone.prototype.getRotationMatrix = function (space, mesh) {
  90977. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90978. var result = BABYLON.Matrix.Identity();
  90979. this.getRotationMatrixToRef(space, mesh, result);
  90980. return result;
  90981. };
  90982. /**
  90983. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  90984. * @param space The space that the rotation should be in
  90985. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90986. * @param result The quaternion that the rotation should be copied to
  90987. */
  90988. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  90989. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90990. if (space == BABYLON.Space.LOCAL) {
  90991. this.getLocalMatrix().getRotationMatrixToRef(result);
  90992. }
  90993. else {
  90994. var mat = Bone._tmpMats[0];
  90995. var amat = this.getAbsoluteTransform();
  90996. if (mesh) {
  90997. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90998. }
  90999. else {
  91000. mat.copyFrom(amat);
  91001. }
  91002. mat.m[0] *= this._scalingDeterminant;
  91003. mat.m[1] *= this._scalingDeterminant;
  91004. mat.m[2] *= this._scalingDeterminant;
  91005. mat.getRotationMatrixToRef(result);
  91006. }
  91007. };
  91008. /**
  91009. * Get the world position of a point that is in the local space of the bone
  91010. * @param position The local position
  91011. * @param mesh The mesh that this bone is attached to
  91012. * @returns The world position
  91013. */
  91014. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  91015. if (mesh === void 0) { mesh = null; }
  91016. var result = BABYLON.Vector3.Zero();
  91017. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  91018. return result;
  91019. };
  91020. /**
  91021. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  91022. * @param position The local position
  91023. * @param mesh The mesh that this bone is attached to
  91024. * @param result The vector3 that the world position should be copied to
  91025. */
  91026. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  91027. if (mesh === void 0) { mesh = null; }
  91028. var wm = null;
  91029. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91030. if (mesh) {
  91031. wm = mesh.getWorldMatrix();
  91032. }
  91033. this._skeleton.computeAbsoluteTransforms();
  91034. var tmat = Bone._tmpMats[0];
  91035. if (mesh && wm) {
  91036. tmat.copyFrom(this.getAbsoluteTransform());
  91037. tmat.multiplyToRef(wm, tmat);
  91038. }
  91039. else {
  91040. tmat = this.getAbsoluteTransform();
  91041. }
  91042. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  91043. };
  91044. /**
  91045. * Get the local position of a point that is in world space
  91046. * @param position The world position
  91047. * @param mesh The mesh that this bone is attached to
  91048. * @returns The local position
  91049. */
  91050. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  91051. if (mesh === void 0) { mesh = null; }
  91052. var result = BABYLON.Vector3.Zero();
  91053. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  91054. return result;
  91055. };
  91056. /**
  91057. * Get the local position of a point that is in world space and copy it to the result param
  91058. * @param position The world position
  91059. * @param mesh The mesh that this bone is attached to
  91060. * @param result The vector3 that the local position should be copied to
  91061. */
  91062. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  91063. if (mesh === void 0) { mesh = null; }
  91064. var wm = null;
  91065. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91066. if (mesh) {
  91067. wm = mesh.getWorldMatrix();
  91068. }
  91069. this._skeleton.computeAbsoluteTransforms();
  91070. var tmat = Bone._tmpMats[0];
  91071. tmat.copyFrom(this.getAbsoluteTransform());
  91072. if (mesh && wm) {
  91073. tmat.multiplyToRef(wm, tmat);
  91074. }
  91075. tmat.invert();
  91076. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  91077. };
  91078. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91079. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  91080. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91081. return Bone;
  91082. }(BABYLON.Node));
  91083. BABYLON.Bone = Bone;
  91084. })(BABYLON || (BABYLON = {}));
  91085. //# sourceMappingURL=babylon.bone.js.map
  91086. var BABYLON;
  91087. (function (BABYLON) {
  91088. /**
  91089. * Class used to apply inverse kinematics to bones
  91090. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  91091. */
  91092. var BoneIKController = /** @class */ (function () {
  91093. /**
  91094. * Creates a new BoneIKController
  91095. * @param mesh defines the mesh to control
  91096. * @param bone defines the bone to control
  91097. * @param options defines options to set up the controller
  91098. */
  91099. function BoneIKController(mesh, bone, options) {
  91100. /**
  91101. * Gets or sets the target position
  91102. */
  91103. this.targetPosition = BABYLON.Vector3.Zero();
  91104. /**
  91105. * Gets or sets the pole target position
  91106. */
  91107. this.poleTargetPosition = BABYLON.Vector3.Zero();
  91108. /**
  91109. * Gets or sets the pole target local offset
  91110. */
  91111. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  91112. /**
  91113. * Gets or sets the pole angle
  91114. */
  91115. this.poleAngle = 0;
  91116. /**
  91117. * 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)
  91118. */
  91119. this.slerpAmount = 1;
  91120. this._bone1Quat = BABYLON.Quaternion.Identity();
  91121. this._bone1Mat = BABYLON.Matrix.Identity();
  91122. this._bone2Ang = Math.PI;
  91123. this._maxAngle = Math.PI;
  91124. this._rightHandedSystem = false;
  91125. this._bendAxis = BABYLON.Vector3.Right();
  91126. this._slerping = false;
  91127. this._adjustRoll = 0;
  91128. this._bone2 = bone;
  91129. this._bone1 = bone.getParent();
  91130. if (!this._bone1) {
  91131. return;
  91132. }
  91133. this.mesh = mesh;
  91134. var bonePos = bone.getPosition();
  91135. if (bone.getAbsoluteTransform().determinant() > 0) {
  91136. this._rightHandedSystem = true;
  91137. this._bendAxis.x = 0;
  91138. this._bendAxis.y = 0;
  91139. this._bendAxis.z = -1;
  91140. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  91141. this._adjustRoll = Math.PI * .5;
  91142. this._bendAxis.z = 1;
  91143. }
  91144. }
  91145. if (this._bone1.length) {
  91146. var boneScale1 = this._bone1.getScale();
  91147. var boneScale2 = this._bone2.getScale();
  91148. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  91149. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  91150. }
  91151. else if (this._bone1.children[0]) {
  91152. mesh.computeWorldMatrix(true);
  91153. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  91154. var pos2 = this._bone2.getAbsolutePosition(mesh);
  91155. var pos3 = this._bone1.getAbsolutePosition(mesh);
  91156. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  91157. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  91158. }
  91159. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  91160. this.maxAngle = Math.PI;
  91161. if (options) {
  91162. if (options.targetMesh) {
  91163. this.targetMesh = options.targetMesh;
  91164. this.targetMesh.computeWorldMatrix(true);
  91165. }
  91166. if (options.poleTargetMesh) {
  91167. this.poleTargetMesh = options.poleTargetMesh;
  91168. this.poleTargetMesh.computeWorldMatrix(true);
  91169. }
  91170. else if (options.poleTargetBone) {
  91171. this.poleTargetBone = options.poleTargetBone;
  91172. }
  91173. else if (this._bone1.getParent()) {
  91174. this.poleTargetBone = this._bone1.getParent();
  91175. }
  91176. if (options.poleTargetLocalOffset) {
  91177. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  91178. }
  91179. if (options.poleAngle) {
  91180. this.poleAngle = options.poleAngle;
  91181. }
  91182. if (options.bendAxis) {
  91183. this._bendAxis.copyFrom(options.bendAxis);
  91184. }
  91185. if (options.maxAngle) {
  91186. this.maxAngle = options.maxAngle;
  91187. }
  91188. if (options.slerpAmount) {
  91189. this.slerpAmount = options.slerpAmount;
  91190. }
  91191. }
  91192. }
  91193. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  91194. /**
  91195. * Gets or sets maximum allowed angle
  91196. */
  91197. get: function () {
  91198. return this._maxAngle;
  91199. },
  91200. set: function (value) {
  91201. this._setMaxAngle(value);
  91202. },
  91203. enumerable: true,
  91204. configurable: true
  91205. });
  91206. BoneIKController.prototype._setMaxAngle = function (ang) {
  91207. if (ang < 0) {
  91208. ang = 0;
  91209. }
  91210. if (ang > Math.PI || ang == undefined) {
  91211. ang = Math.PI;
  91212. }
  91213. this._maxAngle = ang;
  91214. var a = this._bone1Length;
  91215. var b = this._bone2Length;
  91216. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  91217. };
  91218. /**
  91219. * Force the controller to update the bones
  91220. */
  91221. BoneIKController.prototype.update = function () {
  91222. var bone1 = this._bone1;
  91223. if (!bone1) {
  91224. return;
  91225. }
  91226. var target = this.targetPosition;
  91227. var poleTarget = this.poleTargetPosition;
  91228. var mat1 = BoneIKController._tmpMats[0];
  91229. var mat2 = BoneIKController._tmpMats[1];
  91230. if (this.targetMesh) {
  91231. target.copyFrom(this.targetMesh.getAbsolutePosition());
  91232. }
  91233. if (this.poleTargetBone) {
  91234. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  91235. }
  91236. else if (this.poleTargetMesh) {
  91237. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  91238. }
  91239. var bonePos = BoneIKController._tmpVecs[0];
  91240. var zaxis = BoneIKController._tmpVecs[1];
  91241. var xaxis = BoneIKController._tmpVecs[2];
  91242. var yaxis = BoneIKController._tmpVecs[3];
  91243. var upAxis = BoneIKController._tmpVecs[4];
  91244. var _tmpQuat = BoneIKController._tmpQuat;
  91245. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  91246. poleTarget.subtractToRef(bonePos, upAxis);
  91247. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  91248. upAxis.y = 1;
  91249. }
  91250. else {
  91251. upAxis.normalize();
  91252. }
  91253. target.subtractToRef(bonePos, yaxis);
  91254. yaxis.normalize();
  91255. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  91256. zaxis.normalize();
  91257. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  91258. xaxis.normalize();
  91259. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  91260. var a = this._bone1Length;
  91261. var b = this._bone2Length;
  91262. var c = BABYLON.Vector3.Distance(bonePos, target);
  91263. if (this._maxReach > 0) {
  91264. c = Math.min(this._maxReach, c);
  91265. }
  91266. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  91267. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  91268. if (acosa > 1) {
  91269. acosa = 1;
  91270. }
  91271. if (acosb > 1) {
  91272. acosb = 1;
  91273. }
  91274. if (acosa < -1) {
  91275. acosa = -1;
  91276. }
  91277. if (acosb < -1) {
  91278. acosb = -1;
  91279. }
  91280. var angA = Math.acos(acosa);
  91281. var angB = Math.acos(acosb);
  91282. var angC = -angA - angB;
  91283. if (this._rightHandedSystem) {
  91284. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  91285. mat2.multiplyToRef(mat1, mat1);
  91286. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  91287. mat2.multiplyToRef(mat1, mat1);
  91288. }
  91289. else {
  91290. var _tmpVec = BoneIKController._tmpVecs[5];
  91291. _tmpVec.copyFrom(this._bendAxis);
  91292. _tmpVec.x *= -1;
  91293. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  91294. mat2.multiplyToRef(mat1, mat1);
  91295. }
  91296. if (this.poleAngle) {
  91297. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  91298. mat1.multiplyToRef(mat2, mat1);
  91299. }
  91300. if (this._bone1) {
  91301. if (this.slerpAmount < 1) {
  91302. if (!this._slerping) {
  91303. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  91304. }
  91305. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  91306. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  91307. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  91308. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  91309. this._slerping = true;
  91310. }
  91311. else {
  91312. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  91313. this._bone1Mat.copyFrom(mat1);
  91314. this._slerping = false;
  91315. }
  91316. }
  91317. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  91318. this._bone2Ang = angC;
  91319. };
  91320. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91321. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  91322. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91323. return BoneIKController;
  91324. }());
  91325. BABYLON.BoneIKController = BoneIKController;
  91326. })(BABYLON || (BABYLON = {}));
  91327. //# sourceMappingURL=babylon.boneIKController.js.map
  91328. var BABYLON;
  91329. (function (BABYLON) {
  91330. /**
  91331. * Class used to make a bone look toward a point in space
  91332. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  91333. */
  91334. var BoneLookController = /** @class */ (function () {
  91335. /**
  91336. * Create a BoneLookController
  91337. * @param mesh the mesh that the bone belongs to
  91338. * @param bone the bone that will be looking to the target
  91339. * @param target the target Vector3 to look at
  91340. * @param settings optional settings:
  91341. * * maxYaw: the maximum angle the bone will yaw to
  91342. * * minYaw: the minimum angle the bone will yaw to
  91343. * * maxPitch: the maximum angle the bone will pitch to
  91344. * * minPitch: the minimum angle the bone will yaw to
  91345. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  91346. * * upAxis: the up axis of the coordinate system
  91347. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  91348. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  91349. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  91350. * * adjustYaw: used to make an adjustment to the yaw of the bone
  91351. * * adjustPitch: used to make an adjustment to the pitch of the bone
  91352. * * adjustRoll: used to make an adjustment to the roll of the bone
  91353. **/
  91354. function BoneLookController(mesh, bone, target, options) {
  91355. /**
  91356. * The up axis of the coordinate system that is used when the bone is rotated
  91357. */
  91358. this.upAxis = BABYLON.Vector3.Up();
  91359. /**
  91360. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  91361. */
  91362. this.upAxisSpace = BABYLON.Space.LOCAL;
  91363. /**
  91364. * Used to make an adjustment to the yaw of the bone
  91365. */
  91366. this.adjustYaw = 0;
  91367. /**
  91368. * Used to make an adjustment to the pitch of the bone
  91369. */
  91370. this.adjustPitch = 0;
  91371. /**
  91372. * Used to make an adjustment to the roll of the bone
  91373. */
  91374. this.adjustRoll = 0;
  91375. /**
  91376. * 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)
  91377. */
  91378. this.slerpAmount = 1;
  91379. this._boneQuat = BABYLON.Quaternion.Identity();
  91380. this._slerping = false;
  91381. this._firstFrameSkipped = false;
  91382. this._fowardAxis = BABYLON.Vector3.Forward();
  91383. this.mesh = mesh;
  91384. this.bone = bone;
  91385. this.target = target;
  91386. if (options) {
  91387. if (options.adjustYaw) {
  91388. this.adjustYaw = options.adjustYaw;
  91389. }
  91390. if (options.adjustPitch) {
  91391. this.adjustPitch = options.adjustPitch;
  91392. }
  91393. if (options.adjustRoll) {
  91394. this.adjustRoll = options.adjustRoll;
  91395. }
  91396. if (options.maxYaw != null) {
  91397. this.maxYaw = options.maxYaw;
  91398. }
  91399. else {
  91400. this.maxYaw = Math.PI;
  91401. }
  91402. if (options.minYaw != null) {
  91403. this.minYaw = options.minYaw;
  91404. }
  91405. else {
  91406. this.minYaw = -Math.PI;
  91407. }
  91408. if (options.maxPitch != null) {
  91409. this.maxPitch = options.maxPitch;
  91410. }
  91411. else {
  91412. this.maxPitch = Math.PI;
  91413. }
  91414. if (options.minPitch != null) {
  91415. this.minPitch = options.minPitch;
  91416. }
  91417. else {
  91418. this.minPitch = -Math.PI;
  91419. }
  91420. if (options.slerpAmount != null) {
  91421. this.slerpAmount = options.slerpAmount;
  91422. }
  91423. if (options.upAxis != null) {
  91424. this.upAxis = options.upAxis;
  91425. }
  91426. if (options.upAxisSpace != null) {
  91427. this.upAxisSpace = options.upAxisSpace;
  91428. }
  91429. if (options.yawAxis != null || options.pitchAxis != null) {
  91430. var newYawAxis = BABYLON.Axis.Y;
  91431. var newPitchAxis = BABYLON.Axis.X;
  91432. if (options.yawAxis != null) {
  91433. newYawAxis = options.yawAxis.clone();
  91434. newYawAxis.normalize();
  91435. }
  91436. if (options.pitchAxis != null) {
  91437. newPitchAxis = options.pitchAxis.clone();
  91438. newPitchAxis.normalize();
  91439. }
  91440. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  91441. this._transformYawPitch = BABYLON.Matrix.Identity();
  91442. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  91443. this._transformYawPitchInv = this._transformYawPitch.clone();
  91444. this._transformYawPitch.invert();
  91445. }
  91446. }
  91447. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  91448. this.upAxisSpace = BABYLON.Space.LOCAL;
  91449. }
  91450. }
  91451. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  91452. /**
  91453. * Gets or sets the minimum yaw angle that the bone can look to
  91454. */
  91455. get: function () {
  91456. return this._minYaw;
  91457. },
  91458. set: function (value) {
  91459. this._minYaw = value;
  91460. this._minYawSin = Math.sin(value);
  91461. this._minYawCos = Math.cos(value);
  91462. if (this._maxYaw != null) {
  91463. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91464. this._yawRange = this._maxYaw - this._minYaw;
  91465. }
  91466. },
  91467. enumerable: true,
  91468. configurable: true
  91469. });
  91470. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  91471. /**
  91472. * Gets or sets the maximum yaw angle that the bone can look to
  91473. */
  91474. get: function () {
  91475. return this._maxYaw;
  91476. },
  91477. set: function (value) {
  91478. this._maxYaw = value;
  91479. this._maxYawSin = Math.sin(value);
  91480. this._maxYawCos = Math.cos(value);
  91481. if (this._minYaw != null) {
  91482. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91483. this._yawRange = this._maxYaw - this._minYaw;
  91484. }
  91485. },
  91486. enumerable: true,
  91487. configurable: true
  91488. });
  91489. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  91490. /**
  91491. * Gets or sets the minimum pitch angle that the bone can look to
  91492. */
  91493. get: function () {
  91494. return this._minPitch;
  91495. },
  91496. set: function (value) {
  91497. this._minPitch = value;
  91498. this._minPitchTan = Math.tan(value);
  91499. },
  91500. enumerable: true,
  91501. configurable: true
  91502. });
  91503. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  91504. /**
  91505. * Gets or sets the maximum pitch angle that the bone can look to
  91506. */
  91507. get: function () {
  91508. return this._maxPitch;
  91509. },
  91510. set: function (value) {
  91511. this._maxPitch = value;
  91512. this._maxPitchTan = Math.tan(value);
  91513. },
  91514. enumerable: true,
  91515. configurable: true
  91516. });
  91517. /**
  91518. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  91519. */
  91520. BoneLookController.prototype.update = function () {
  91521. //skip the first frame when slerping so that the mesh rotation is correct
  91522. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  91523. this._firstFrameSkipped = true;
  91524. return;
  91525. }
  91526. var bone = this.bone;
  91527. var bonePos = BoneLookController._tmpVecs[0];
  91528. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  91529. var target = this.target;
  91530. var _tmpMat1 = BoneLookController._tmpMats[0];
  91531. var _tmpMat2 = BoneLookController._tmpMats[1];
  91532. var mesh = this.mesh;
  91533. var parentBone = bone.getParent();
  91534. var upAxis = BoneLookController._tmpVecs[1];
  91535. upAxis.copyFrom(this.upAxis);
  91536. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  91537. if (this._transformYawPitch) {
  91538. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  91539. }
  91540. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  91541. }
  91542. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  91543. mesh.getDirectionToRef(upAxis, upAxis);
  91544. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  91545. upAxis.normalize();
  91546. }
  91547. }
  91548. var checkYaw = false;
  91549. var checkPitch = false;
  91550. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  91551. checkYaw = true;
  91552. }
  91553. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  91554. checkPitch = true;
  91555. }
  91556. if (checkYaw || checkPitch) {
  91557. var spaceMat = BoneLookController._tmpMats[2];
  91558. var spaceMatInv = BoneLookController._tmpMats[3];
  91559. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  91560. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  91561. }
  91562. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  91563. spaceMat.copyFrom(mesh.getWorldMatrix());
  91564. }
  91565. else {
  91566. var forwardAxis = BoneLookController._tmpVecs[2];
  91567. forwardAxis.copyFrom(this._fowardAxis);
  91568. if (this._transformYawPitch) {
  91569. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  91570. }
  91571. if (parentBone) {
  91572. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  91573. }
  91574. else {
  91575. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  91576. }
  91577. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  91578. rightAxis.normalize();
  91579. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  91580. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  91581. }
  91582. spaceMat.invertToRef(spaceMatInv);
  91583. var xzlen = null;
  91584. if (checkPitch) {
  91585. var localTarget = BoneLookController._tmpVecs[3];
  91586. target.subtractToRef(bonePos, localTarget);
  91587. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91588. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91589. var pitch = Math.atan2(localTarget.y, xzlen);
  91590. var newPitch = pitch;
  91591. if (pitch > this._maxPitch) {
  91592. localTarget.y = this._maxPitchTan * xzlen;
  91593. newPitch = this._maxPitch;
  91594. }
  91595. else if (pitch < this._minPitch) {
  91596. localTarget.y = this._minPitchTan * xzlen;
  91597. newPitch = this._minPitch;
  91598. }
  91599. if (pitch != newPitch) {
  91600. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91601. localTarget.addInPlace(bonePos);
  91602. target = localTarget;
  91603. }
  91604. }
  91605. if (checkYaw) {
  91606. var localTarget = BoneLookController._tmpVecs[4];
  91607. target.subtractToRef(bonePos, localTarget);
  91608. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91609. var yaw = Math.atan2(localTarget.x, localTarget.z);
  91610. var newYaw = yaw;
  91611. if (yaw > this._maxYaw || yaw < this._minYaw) {
  91612. if (xzlen == null) {
  91613. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91614. }
  91615. if (this._yawRange > Math.PI) {
  91616. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  91617. localTarget.z = this._maxYawCos * xzlen;
  91618. localTarget.x = this._maxYawSin * xzlen;
  91619. newYaw = this._maxYaw;
  91620. }
  91621. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  91622. localTarget.z = this._minYawCos * xzlen;
  91623. localTarget.x = this._minYawSin * xzlen;
  91624. newYaw = this._minYaw;
  91625. }
  91626. }
  91627. else {
  91628. if (yaw > this._maxYaw) {
  91629. localTarget.z = this._maxYawCos * xzlen;
  91630. localTarget.x = this._maxYawSin * xzlen;
  91631. newYaw = this._maxYaw;
  91632. }
  91633. else if (yaw < this._minYaw) {
  91634. localTarget.z = this._minYawCos * xzlen;
  91635. localTarget.x = this._minYawSin * xzlen;
  91636. newYaw = this._minYaw;
  91637. }
  91638. }
  91639. }
  91640. if (this._slerping && this._yawRange > Math.PI) {
  91641. //are we going to be crossing into the min/max region?
  91642. var boneFwd = BoneLookController._tmpVecs[8];
  91643. boneFwd.copyFrom(BABYLON.Axis.Z);
  91644. if (this._transformYawPitch) {
  91645. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  91646. }
  91647. var boneRotMat = BoneLookController._tmpMats[4];
  91648. this._boneQuat.toRotationMatrix(boneRotMat);
  91649. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  91650. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  91651. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  91652. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  91653. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  91654. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  91655. if (angBtwTar > angBtwMidYaw) {
  91656. if (xzlen == null) {
  91657. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91658. }
  91659. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  91660. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  91661. if (angBtwMin < angBtwMax) {
  91662. newYaw = boneYaw + Math.PI * .75;
  91663. localTarget.z = Math.cos(newYaw) * xzlen;
  91664. localTarget.x = Math.sin(newYaw) * xzlen;
  91665. }
  91666. else {
  91667. newYaw = boneYaw - Math.PI * .75;
  91668. localTarget.z = Math.cos(newYaw) * xzlen;
  91669. localTarget.x = Math.sin(newYaw) * xzlen;
  91670. }
  91671. }
  91672. }
  91673. if (yaw != newYaw) {
  91674. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91675. localTarget.addInPlace(bonePos);
  91676. target = localTarget;
  91677. }
  91678. }
  91679. }
  91680. var zaxis = BoneLookController._tmpVecs[5];
  91681. var xaxis = BoneLookController._tmpVecs[6];
  91682. var yaxis = BoneLookController._tmpVecs[7];
  91683. var _tmpQuat = BoneLookController._tmpQuat;
  91684. target.subtractToRef(bonePos, zaxis);
  91685. zaxis.normalize();
  91686. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  91687. xaxis.normalize();
  91688. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  91689. yaxis.normalize();
  91690. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  91691. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  91692. return;
  91693. }
  91694. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  91695. return;
  91696. }
  91697. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  91698. return;
  91699. }
  91700. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  91701. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  91702. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  91703. }
  91704. if (this.slerpAmount < 1) {
  91705. if (!this._slerping) {
  91706. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  91707. }
  91708. if (this._transformYawPitch) {
  91709. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91710. }
  91711. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  91712. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  91713. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  91714. this._slerping = true;
  91715. }
  91716. else {
  91717. if (this._transformYawPitch) {
  91718. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91719. }
  91720. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  91721. this._slerping = false;
  91722. }
  91723. };
  91724. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  91725. var angDiff = ang2 - ang1;
  91726. angDiff %= Math.PI * 2;
  91727. if (angDiff > Math.PI) {
  91728. angDiff -= Math.PI * 2;
  91729. }
  91730. else if (angDiff < -Math.PI) {
  91731. angDiff += Math.PI * 2;
  91732. }
  91733. return angDiff;
  91734. };
  91735. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  91736. ang1 %= (2 * Math.PI);
  91737. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91738. ang2 %= (2 * Math.PI);
  91739. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91740. var ab = 0;
  91741. if (ang1 < ang2) {
  91742. ab = ang2 - ang1;
  91743. }
  91744. else {
  91745. ab = ang1 - ang2;
  91746. }
  91747. if (ab > Math.PI) {
  91748. ab = Math.PI * 2 - ab;
  91749. }
  91750. return ab;
  91751. };
  91752. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  91753. ang %= (2 * Math.PI);
  91754. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  91755. ang1 %= (2 * Math.PI);
  91756. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91757. ang2 %= (2 * Math.PI);
  91758. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91759. if (ang1 < ang2) {
  91760. if (ang > ang1 && ang < ang2) {
  91761. return true;
  91762. }
  91763. }
  91764. else {
  91765. if (ang > ang2 && ang < ang1) {
  91766. return true;
  91767. }
  91768. }
  91769. return false;
  91770. };
  91771. 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()];
  91772. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  91773. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91774. return BoneLookController;
  91775. }());
  91776. BABYLON.BoneLookController = BoneLookController;
  91777. })(BABYLON || (BABYLON = {}));
  91778. //# sourceMappingURL=babylon.boneLookController.js.map
  91779. var BABYLON;
  91780. (function (BABYLON) {
  91781. /**
  91782. * Class used to handle skinning animations
  91783. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91784. */
  91785. var Skeleton = /** @class */ (function () {
  91786. /**
  91787. * Creates a new skeleton
  91788. * @param name defines the skeleton name
  91789. * @param id defines the skeleton Id
  91790. * @param scene defines the hosting scene
  91791. */
  91792. function Skeleton(
  91793. /** defines the skeleton name */
  91794. name,
  91795. /** defines the skeleton Id */
  91796. id, scene) {
  91797. this.name = name;
  91798. this.id = id;
  91799. /**
  91800. * Gets the list of child bones
  91801. */
  91802. this.bones = new Array();
  91803. /**
  91804. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  91805. */
  91806. this.needInitialSkinMatrix = false;
  91807. this._isDirty = true;
  91808. this._meshesWithPoseMatrix = new Array();
  91809. this._identity = BABYLON.Matrix.Identity();
  91810. this._ranges = {};
  91811. this._lastAbsoluteTransformsUpdateId = -1;
  91812. /**
  91813. * Specifies if the skeleton should be serialized
  91814. */
  91815. this.doNotSerialize = false;
  91816. this._animationPropertiesOverride = null;
  91817. // Events
  91818. /**
  91819. * An observable triggered before computing the skeleton's matrices
  91820. */
  91821. this.onBeforeComputeObservable = new BABYLON.Observable();
  91822. this.bones = [];
  91823. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91824. scene.skeletons.push(this);
  91825. //make sure it will recalculate the matrix next time prepare is called.
  91826. this._isDirty = true;
  91827. }
  91828. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  91829. /**
  91830. * Gets or sets the animation properties override
  91831. */
  91832. get: function () {
  91833. if (!this._animationPropertiesOverride) {
  91834. return this._scene.animationPropertiesOverride;
  91835. }
  91836. return this._animationPropertiesOverride;
  91837. },
  91838. set: function (value) {
  91839. this._animationPropertiesOverride = value;
  91840. },
  91841. enumerable: true,
  91842. configurable: true
  91843. });
  91844. // Members
  91845. /**
  91846. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  91847. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  91848. * @returns a Float32Array containing matrices data
  91849. */
  91850. Skeleton.prototype.getTransformMatrices = function (mesh) {
  91851. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  91852. return mesh._bonesTransformMatrices;
  91853. }
  91854. if (!this._transformMatrices) {
  91855. this.prepare();
  91856. }
  91857. return this._transformMatrices;
  91858. };
  91859. /**
  91860. * Gets the current hosting scene
  91861. * @returns a scene object
  91862. */
  91863. Skeleton.prototype.getScene = function () {
  91864. return this._scene;
  91865. };
  91866. // Methods
  91867. /**
  91868. * Gets a string representing the current skeleton data
  91869. * @param fullDetails defines a boolean indicating if we want a verbose version
  91870. * @returns a string representing the current skeleton data
  91871. */
  91872. Skeleton.prototype.toString = function (fullDetails) {
  91873. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  91874. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  91875. if (fullDetails) {
  91876. ret += ", Ranges: {";
  91877. var first = true;
  91878. for (var name_1 in this._ranges) {
  91879. if (first) {
  91880. ret += ", ";
  91881. first = false;
  91882. }
  91883. ret += name_1;
  91884. }
  91885. ret += "}";
  91886. }
  91887. return ret;
  91888. };
  91889. /**
  91890. * Get bone's index searching by name
  91891. * @param name defines bone's name to search for
  91892. * @return the indice of the bone. Returns -1 if not found
  91893. */
  91894. Skeleton.prototype.getBoneIndexByName = function (name) {
  91895. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  91896. if (this.bones[boneIndex].name === name) {
  91897. return boneIndex;
  91898. }
  91899. }
  91900. return -1;
  91901. };
  91902. /**
  91903. * Creater a new animation range
  91904. * @param name defines the name of the range
  91905. * @param from defines the start key
  91906. * @param to defines the end key
  91907. */
  91908. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  91909. // check name not already in use
  91910. if (!this._ranges[name]) {
  91911. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  91912. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91913. if (this.bones[i].animations[0]) {
  91914. this.bones[i].animations[0].createRange(name, from, to);
  91915. }
  91916. }
  91917. }
  91918. };
  91919. /**
  91920. * Delete a specific animation range
  91921. * @param name defines the name of the range
  91922. * @param deleteFrames defines if frames must be removed as well
  91923. */
  91924. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  91925. if (deleteFrames === void 0) { deleteFrames = true; }
  91926. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91927. if (this.bones[i].animations[0]) {
  91928. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  91929. }
  91930. }
  91931. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  91932. };
  91933. /**
  91934. * Gets a specific animation range
  91935. * @param name defines the name of the range to look for
  91936. * @returns the requested animation range or null if not found
  91937. */
  91938. Skeleton.prototype.getAnimationRange = function (name) {
  91939. return this._ranges[name];
  91940. };
  91941. /**
  91942. * Gets the list of all animation ranges defined on this skeleton
  91943. * @returns an array
  91944. */
  91945. Skeleton.prototype.getAnimationRanges = function () {
  91946. var animationRanges = [];
  91947. var name;
  91948. var i = 0;
  91949. for (name in this._ranges) {
  91950. animationRanges[i] = this._ranges[name];
  91951. i++;
  91952. }
  91953. return animationRanges;
  91954. };
  91955. /**
  91956. * Copy animation range from a source skeleton.
  91957. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  91958. * @param source defines the source skeleton
  91959. * @param name defines the name of the range to copy
  91960. * @param rescaleAsRequired defines if rescaling must be applied if required
  91961. * @returns true if operation was successful
  91962. */
  91963. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  91964. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91965. if (this._ranges[name] || !source.getAnimationRange(name)) {
  91966. return false;
  91967. }
  91968. var ret = true;
  91969. var frameOffset = this._getHighestAnimationFrame() + 1;
  91970. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  91971. var boneDict = {};
  91972. var sourceBones = source.bones;
  91973. var nBones;
  91974. var i;
  91975. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  91976. boneDict[sourceBones[i].name] = sourceBones[i];
  91977. }
  91978. if (this.bones.length !== sourceBones.length) {
  91979. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  91980. ret = false;
  91981. }
  91982. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  91983. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  91984. var boneName = this.bones[i].name;
  91985. var sourceBone = boneDict[boneName];
  91986. if (sourceBone) {
  91987. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  91988. }
  91989. else {
  91990. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  91991. ret = false;
  91992. }
  91993. }
  91994. // do not call createAnimationRange(), since it also is done to bones, which was already done
  91995. var range = source.getAnimationRange(name);
  91996. if (range) {
  91997. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  91998. }
  91999. return ret;
  92000. };
  92001. /**
  92002. * Forces the skeleton to go to rest pose
  92003. */
  92004. Skeleton.prototype.returnToRest = function () {
  92005. for (var index = 0; index < this.bones.length; index++) {
  92006. this.bones[index].returnToRest();
  92007. }
  92008. };
  92009. Skeleton.prototype._getHighestAnimationFrame = function () {
  92010. var ret = 0;
  92011. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  92012. if (this.bones[i].animations[0]) {
  92013. var highest = this.bones[i].animations[0].getHighestFrame();
  92014. if (ret < highest) {
  92015. ret = highest;
  92016. }
  92017. }
  92018. }
  92019. return ret;
  92020. };
  92021. /**
  92022. * Begin a specific animation range
  92023. * @param name defines the name of the range to start
  92024. * @param loop defines if looping must be turned on (false by default)
  92025. * @param speedRatio defines the speed ratio to apply (1 by default)
  92026. * @param onAnimationEnd defines a callback which will be called when animation will end
  92027. * @returns a new animatable
  92028. */
  92029. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  92030. var range = this.getAnimationRange(name);
  92031. if (!range) {
  92032. return null;
  92033. }
  92034. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  92035. };
  92036. /** @hidden */
  92037. Skeleton.prototype._markAsDirty = function () {
  92038. this._isDirty = true;
  92039. };
  92040. /** @hidden */
  92041. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  92042. this._meshesWithPoseMatrix.push(mesh);
  92043. };
  92044. /** @hidden */
  92045. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  92046. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  92047. if (index > -1) {
  92048. this._meshesWithPoseMatrix.splice(index, 1);
  92049. }
  92050. };
  92051. /** @hidden */
  92052. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  92053. this.onBeforeComputeObservable.notifyObservers(this);
  92054. for (var index = 0; index < this.bones.length; index++) {
  92055. var bone = this.bones[index];
  92056. var parentBone = bone.getParent();
  92057. if (parentBone) {
  92058. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  92059. }
  92060. else {
  92061. if (initialSkinMatrix) {
  92062. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  92063. }
  92064. else {
  92065. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  92066. }
  92067. }
  92068. if (bone._index !== -1) {
  92069. var mappedIndex = bone._index === null ? index : bone._index;
  92070. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  92071. }
  92072. }
  92073. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  92074. };
  92075. /**
  92076. * Build all resources required to render a skeleton
  92077. */
  92078. Skeleton.prototype.prepare = function () {
  92079. if (!this._isDirty) {
  92080. return;
  92081. }
  92082. if (this.needInitialSkinMatrix) {
  92083. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  92084. var mesh = this._meshesWithPoseMatrix[index];
  92085. var poseMatrix = mesh.getPoseMatrix();
  92086. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  92087. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  92088. }
  92089. if (this._synchronizedWithMesh !== mesh) {
  92090. this._synchronizedWithMesh = mesh;
  92091. // Prepare bones
  92092. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  92093. var bone = this.bones[boneIndex];
  92094. if (!bone.getParent()) {
  92095. var matrix = bone.getBaseMatrix();
  92096. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  92097. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  92098. }
  92099. }
  92100. }
  92101. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  92102. }
  92103. }
  92104. else {
  92105. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  92106. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  92107. }
  92108. this._computeTransformMatrices(this._transformMatrices, null);
  92109. }
  92110. this._isDirty = false;
  92111. this._scene._activeBones.addCount(this.bones.length, false);
  92112. };
  92113. /**
  92114. * Gets the list of animatables currently running for this skeleton
  92115. * @returns an array of animatables
  92116. */
  92117. Skeleton.prototype.getAnimatables = function () {
  92118. if (!this._animatables || this._animatables.length !== this.bones.length) {
  92119. this._animatables = [];
  92120. for (var index = 0; index < this.bones.length; index++) {
  92121. this._animatables.push(this.bones[index]);
  92122. }
  92123. }
  92124. return this._animatables;
  92125. };
  92126. /**
  92127. * Clone the current skeleton
  92128. * @param name defines the name of the new skeleton
  92129. * @param id defines the id of the enw skeleton
  92130. * @returns the new skeleton
  92131. */
  92132. Skeleton.prototype.clone = function (name, id) {
  92133. var result = new Skeleton(name, id || name, this._scene);
  92134. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  92135. for (var index = 0; index < this.bones.length; index++) {
  92136. var source = this.bones[index];
  92137. var parentBone = null;
  92138. var parent_1 = source.getParent();
  92139. if (parent_1) {
  92140. var parentIndex = this.bones.indexOf(parent_1);
  92141. parentBone = result.bones[parentIndex];
  92142. }
  92143. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  92144. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  92145. }
  92146. if (this._ranges) {
  92147. result._ranges = {};
  92148. for (var rangeName in this._ranges) {
  92149. var range = this._ranges[rangeName];
  92150. if (range) {
  92151. result._ranges[rangeName] = range.clone();
  92152. }
  92153. }
  92154. }
  92155. this._isDirty = true;
  92156. return result;
  92157. };
  92158. /**
  92159. * Enable animation blending for this skeleton
  92160. * @param blendingSpeed defines the blending speed to apply
  92161. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  92162. */
  92163. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  92164. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  92165. this.bones.forEach(function (bone) {
  92166. bone.animations.forEach(function (animation) {
  92167. animation.enableBlending = true;
  92168. animation.blendingSpeed = blendingSpeed;
  92169. });
  92170. });
  92171. };
  92172. /**
  92173. * Releases all resources associated with the current skeleton
  92174. */
  92175. Skeleton.prototype.dispose = function () {
  92176. this._meshesWithPoseMatrix = [];
  92177. // Animations
  92178. this.getScene().stopAnimation(this);
  92179. // Remove from scene
  92180. this.getScene().removeSkeleton(this);
  92181. };
  92182. /**
  92183. * Serialize the skeleton in a JSON object
  92184. * @returns a JSON object
  92185. */
  92186. Skeleton.prototype.serialize = function () {
  92187. var serializationObject = {};
  92188. serializationObject.name = this.name;
  92189. serializationObject.id = this.id;
  92190. if (this.dimensionsAtRest) {
  92191. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  92192. }
  92193. serializationObject.bones = [];
  92194. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  92195. for (var index = 0; index < this.bones.length; index++) {
  92196. var bone = this.bones[index];
  92197. var parent_2 = bone.getParent();
  92198. var serializedBone = {
  92199. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  92200. name: bone.name,
  92201. matrix: bone.getBaseMatrix().toArray(),
  92202. rest: bone.getRestPose().toArray()
  92203. };
  92204. serializationObject.bones.push(serializedBone);
  92205. if (bone.length) {
  92206. serializedBone.length = bone.length;
  92207. }
  92208. if (bone.metadata) {
  92209. serializedBone.metadata = bone.metadata;
  92210. }
  92211. if (bone.animations && bone.animations.length > 0) {
  92212. serializedBone.animation = bone.animations[0].serialize();
  92213. }
  92214. serializationObject.ranges = [];
  92215. for (var name in this._ranges) {
  92216. var source = this._ranges[name];
  92217. if (!source) {
  92218. continue;
  92219. }
  92220. var range = {};
  92221. range.name = name;
  92222. range.from = source.from;
  92223. range.to = source.to;
  92224. serializationObject.ranges.push(range);
  92225. }
  92226. }
  92227. return serializationObject;
  92228. };
  92229. /**
  92230. * Creates a new skeleton from serialized data
  92231. * @param parsedSkeleton defines the serialized data
  92232. * @param scene defines the hosting scene
  92233. * @returns a new skeleton
  92234. */
  92235. Skeleton.Parse = function (parsedSkeleton, scene) {
  92236. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  92237. if (parsedSkeleton.dimensionsAtRest) {
  92238. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  92239. }
  92240. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  92241. var index;
  92242. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  92243. var parsedBone = parsedSkeleton.bones[index];
  92244. var parentBone = null;
  92245. if (parsedBone.parentBoneIndex > -1) {
  92246. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  92247. }
  92248. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  92249. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  92250. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  92251. bone.id = parsedBone.id;
  92252. }
  92253. if (parsedBone.length) {
  92254. bone.length = parsedBone.length;
  92255. }
  92256. if (parsedBone.metadata) {
  92257. bone.metadata = parsedBone.metadata;
  92258. }
  92259. if (parsedBone.animation) {
  92260. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  92261. }
  92262. }
  92263. // placed after bones, so createAnimationRange can cascade down
  92264. if (parsedSkeleton.ranges) {
  92265. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  92266. var data = parsedSkeleton.ranges[index];
  92267. skeleton.createAnimationRange(data.name, data.from, data.to);
  92268. }
  92269. }
  92270. return skeleton;
  92271. };
  92272. /**
  92273. * Compute all node absolute transforms
  92274. * @param forceUpdate defines if computation must be done even if cache is up to date
  92275. */
  92276. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  92277. if (forceUpdate === void 0) { forceUpdate = false; }
  92278. var renderId = this._scene.getRenderId();
  92279. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  92280. this.bones[0].computeAbsoluteTransforms();
  92281. this._lastAbsoluteTransformsUpdateId = renderId;
  92282. }
  92283. };
  92284. /**
  92285. * Gets the root pose matrix
  92286. * @returns a matrix
  92287. */
  92288. Skeleton.prototype.getPoseMatrix = function () {
  92289. var poseMatrix = null;
  92290. if (this._meshesWithPoseMatrix.length > 0) {
  92291. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  92292. }
  92293. return poseMatrix;
  92294. };
  92295. /**
  92296. * Sorts bones per internal index
  92297. */
  92298. Skeleton.prototype.sortBones = function () {
  92299. var bones = new Array();
  92300. var visited = new Array(this.bones.length);
  92301. for (var index = 0; index < this.bones.length; index++) {
  92302. this._sortBones(index, bones, visited);
  92303. }
  92304. this.bones = bones;
  92305. };
  92306. Skeleton.prototype._sortBones = function (index, bones, visited) {
  92307. if (visited[index]) {
  92308. return;
  92309. }
  92310. visited[index] = true;
  92311. var bone = this.bones[index];
  92312. if (bone._index === undefined) {
  92313. bone._index = index;
  92314. }
  92315. var parentBone = bone.getParent();
  92316. if (parentBone) {
  92317. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  92318. }
  92319. bones.push(bone);
  92320. };
  92321. return Skeleton;
  92322. }());
  92323. BABYLON.Skeleton = Skeleton;
  92324. })(BABYLON || (BABYLON = {}));
  92325. //# sourceMappingURL=babylon.skeleton.js.map
  92326. var BABYLON;
  92327. (function (BABYLON) {
  92328. /**
  92329. * This groups tools to convert HDR texture to native colors array.
  92330. */
  92331. var HDRTools = /** @class */ (function () {
  92332. function HDRTools() {
  92333. }
  92334. HDRTools.Ldexp = function (mantissa, exponent) {
  92335. if (exponent > 1023) {
  92336. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  92337. }
  92338. if (exponent < -1074) {
  92339. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  92340. }
  92341. return mantissa * Math.pow(2, exponent);
  92342. };
  92343. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  92344. if (exponent > 0) { /*nonzero pixel*/
  92345. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  92346. float32array[index + 0] = red * exponent;
  92347. float32array[index + 1] = green * exponent;
  92348. float32array[index + 2] = blue * exponent;
  92349. }
  92350. else {
  92351. float32array[index + 0] = 0;
  92352. float32array[index + 1] = 0;
  92353. float32array[index + 2] = 0;
  92354. }
  92355. };
  92356. HDRTools.readStringLine = function (uint8array, startIndex) {
  92357. var line = "";
  92358. var character = "";
  92359. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  92360. character = String.fromCharCode(uint8array[i]);
  92361. if (character == "\n") {
  92362. break;
  92363. }
  92364. line += character;
  92365. }
  92366. return line;
  92367. };
  92368. /**
  92369. * Reads header information from an RGBE texture stored in a native array.
  92370. * More information on this format are available here:
  92371. * https://en.wikipedia.org/wiki/RGBE_image_format
  92372. *
  92373. * @param uint8array The binary file stored in native array.
  92374. * @return The header information.
  92375. */
  92376. HDRTools.RGBE_ReadHeader = function (uint8array) {
  92377. var height = 0;
  92378. var width = 0;
  92379. var line = this.readStringLine(uint8array, 0);
  92380. if (line[0] != '#' || line[1] != '?') {
  92381. throw "Bad HDR Format.";
  92382. }
  92383. var endOfHeader = false;
  92384. var findFormat = false;
  92385. var lineIndex = 0;
  92386. do {
  92387. lineIndex += (line.length + 1);
  92388. line = this.readStringLine(uint8array, lineIndex);
  92389. if (line == "FORMAT=32-bit_rle_rgbe") {
  92390. findFormat = true;
  92391. }
  92392. else if (line.length == 0) {
  92393. endOfHeader = true;
  92394. }
  92395. } while (!endOfHeader);
  92396. if (!findFormat) {
  92397. throw "HDR Bad header format, unsupported FORMAT";
  92398. }
  92399. lineIndex += (line.length + 1);
  92400. line = this.readStringLine(uint8array, lineIndex);
  92401. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  92402. var match = sizeRegexp.exec(line);
  92403. // TODO. Support +Y and -X if needed.
  92404. if (!match || match.length < 3) {
  92405. throw "HDR Bad header format, no size";
  92406. }
  92407. width = parseInt(match[2]);
  92408. height = parseInt(match[1]);
  92409. if (width < 8 || width > 0x7fff) {
  92410. throw "HDR Bad header format, unsupported size";
  92411. }
  92412. lineIndex += (line.length + 1);
  92413. return {
  92414. height: height,
  92415. width: width,
  92416. dataPosition: lineIndex
  92417. };
  92418. };
  92419. /**
  92420. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  92421. * This RGBE texture needs to store the information as a panorama.
  92422. *
  92423. * More information on this format are available here:
  92424. * https://en.wikipedia.org/wiki/RGBE_image_format
  92425. *
  92426. * @param buffer The binary file stored in an array buffer.
  92427. * @param size The expected size of the extracted cubemap.
  92428. * @return The Cube Map information.
  92429. */
  92430. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  92431. var uint8array = new Uint8Array(buffer);
  92432. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  92433. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92434. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  92435. return cubeMapData;
  92436. };
  92437. /**
  92438. * Returns the pixels data extracted from an RGBE texture.
  92439. * This pixels will be stored left to right up to down in the R G B order in one array.
  92440. *
  92441. * More information on this format are available here:
  92442. * https://en.wikipedia.org/wiki/RGBE_image_format
  92443. *
  92444. * @param uint8array The binary file stored in an array buffer.
  92445. * @param hdrInfo The header information of the file.
  92446. * @return The pixels data in RGB right to left up to down order.
  92447. */
  92448. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  92449. // Keep for multi format supports.
  92450. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92451. };
  92452. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  92453. var num_scanlines = hdrInfo.height;
  92454. var scanline_width = hdrInfo.width;
  92455. var a, b, c, d, count;
  92456. var dataIndex = hdrInfo.dataPosition;
  92457. var index = 0, endIndex = 0, i = 0;
  92458. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  92459. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  92460. // 3 channels of 4 bytes per pixel in float.
  92461. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  92462. var resultArray = new Float32Array(resultBuffer);
  92463. // read in each successive scanline
  92464. while (num_scanlines > 0) {
  92465. a = uint8array[dataIndex++];
  92466. b = uint8array[dataIndex++];
  92467. c = uint8array[dataIndex++];
  92468. d = uint8array[dataIndex++];
  92469. if (a != 2 || b != 2 || (c & 0x80)) {
  92470. // this file is not run length encoded
  92471. throw "HDR Bad header format, not RLE";
  92472. }
  92473. if (((c << 8) | d) != scanline_width) {
  92474. throw "HDR Bad header format, wrong scan line width";
  92475. }
  92476. index = 0;
  92477. // read each of the four channels for the scanline into the buffer
  92478. for (i = 0; i < 4; i++) {
  92479. endIndex = (i + 1) * scanline_width;
  92480. while (index < endIndex) {
  92481. a = uint8array[dataIndex++];
  92482. b = uint8array[dataIndex++];
  92483. if (a > 128) {
  92484. // a run of the same value
  92485. count = a - 128;
  92486. if ((count == 0) || (count > endIndex - index)) {
  92487. throw "HDR Bad Format, bad scanline data (run)";
  92488. }
  92489. while (count-- > 0) {
  92490. scanLineArray[index++] = b;
  92491. }
  92492. }
  92493. else {
  92494. // a non-run
  92495. count = a;
  92496. if ((count == 0) || (count > endIndex - index)) {
  92497. throw "HDR Bad Format, bad scanline data (non-run)";
  92498. }
  92499. scanLineArray[index++] = b;
  92500. if (--count > 0) {
  92501. for (var j = 0; j < count; j++) {
  92502. scanLineArray[index++] = uint8array[dataIndex++];
  92503. }
  92504. }
  92505. }
  92506. }
  92507. }
  92508. // now convert data from buffer into floats
  92509. for (i = 0; i < scanline_width; i++) {
  92510. a = scanLineArray[i];
  92511. b = scanLineArray[i + scanline_width];
  92512. c = scanLineArray[i + 2 * scanline_width];
  92513. d = scanLineArray[i + 3 * scanline_width];
  92514. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  92515. }
  92516. num_scanlines--;
  92517. }
  92518. return resultArray;
  92519. };
  92520. return HDRTools;
  92521. }());
  92522. BABYLON.HDRTools = HDRTools;
  92523. })(BABYLON || (BABYLON = {}));
  92524. //# sourceMappingURL=babylon.hdr.js.map
  92525. var BABYLON;
  92526. (function (BABYLON) {
  92527. /**
  92528. * This represents a texture coming from an HDR input.
  92529. *
  92530. * The only supported format is currently panorama picture stored in RGBE format.
  92531. * Example of such files can be found on HDRLib: http://hdrlib.com/
  92532. */
  92533. var HDRCubeTexture = /** @class */ (function (_super) {
  92534. __extends(HDRCubeTexture, _super);
  92535. /**
  92536. * Instantiates an HDRTexture from the following parameters.
  92537. *
  92538. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  92539. * @param scene The scene the texture will be used in
  92540. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  92541. * @param noMipmap Forces to not generate the mipmap if true
  92542. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  92543. * @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)
  92544. * @param reserved Reserved flag for internal use.
  92545. */
  92546. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  92547. if (noMipmap === void 0) { noMipmap = false; }
  92548. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92549. if (gammaSpace === void 0) { gammaSpace = false; }
  92550. if (reserved === void 0) { reserved = false; }
  92551. if (onLoad === void 0) { onLoad = null; }
  92552. if (onError === void 0) { onError = null; }
  92553. var _this = _super.call(this, scene) || this;
  92554. _this._generateHarmonics = true;
  92555. _this._onLoad = null;
  92556. _this._onError = null;
  92557. /**
  92558. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  92559. */
  92560. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  92561. _this._isBlocking = true;
  92562. _this._rotationY = 0;
  92563. /**
  92564. * Gets or sets the center of the bounding box associated with the cube texture
  92565. * It must define where the camera used to render the texture was set
  92566. */
  92567. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  92568. if (!url) {
  92569. return _this;
  92570. }
  92571. _this.name = url;
  92572. _this.url = url;
  92573. _this.hasAlpha = false;
  92574. _this.isCube = true;
  92575. _this._textureMatrix = BABYLON.Matrix.Identity();
  92576. _this._onLoad = onLoad;
  92577. _this._onError = onError;
  92578. _this.gammaSpace = gammaSpace;
  92579. _this._noMipmap = noMipmap;
  92580. _this._size = size;
  92581. _this._texture = _this._getFromCache(url, _this._noMipmap);
  92582. if (!_this._texture) {
  92583. if (!scene.useDelayedTextureLoading) {
  92584. _this.loadTexture();
  92585. }
  92586. else {
  92587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  92588. }
  92589. }
  92590. return _this;
  92591. }
  92592. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  92593. /**
  92594. * Gets wether or not the texture is blocking during loading.
  92595. */
  92596. get: function () {
  92597. return this._isBlocking;
  92598. },
  92599. /**
  92600. * Sets wether or not the texture is blocking during loading.
  92601. */
  92602. set: function (value) {
  92603. this._isBlocking = value;
  92604. },
  92605. enumerable: true,
  92606. configurable: true
  92607. });
  92608. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  92609. /**
  92610. * Gets texture matrix rotation angle around Y axis radians.
  92611. */
  92612. get: function () {
  92613. return this._rotationY;
  92614. },
  92615. /**
  92616. * Sets texture matrix rotation angle around Y axis in radians.
  92617. */
  92618. set: function (value) {
  92619. this._rotationY = value;
  92620. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  92621. },
  92622. enumerable: true,
  92623. configurable: true
  92624. });
  92625. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  92626. get: function () {
  92627. return this._boundingBoxSize;
  92628. },
  92629. /**
  92630. * Gets or sets the size of the bounding box associated with the cube texture
  92631. * When defined, the cubemap will switch to local mode
  92632. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  92633. * @example https://www.babylonjs-playground.com/#RNASML
  92634. */
  92635. set: function (value) {
  92636. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  92637. return;
  92638. }
  92639. this._boundingBoxSize = value;
  92640. var scene = this.getScene();
  92641. if (scene) {
  92642. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  92643. }
  92644. },
  92645. enumerable: true,
  92646. configurable: true
  92647. });
  92648. /**
  92649. * Occurs when the file is raw .hdr file.
  92650. */
  92651. HDRCubeTexture.prototype.loadTexture = function () {
  92652. var _this = this;
  92653. var callback = function (buffer) {
  92654. _this.lodGenerationOffset = 0.0;
  92655. _this.lodGenerationScale = 0.8;
  92656. var scene = _this.getScene();
  92657. if (!scene) {
  92658. return null;
  92659. }
  92660. // Extract the raw linear data.
  92661. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  92662. // Generate harmonics if needed.
  92663. if (_this._generateHarmonics) {
  92664. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  92665. _this.sphericalPolynomial = sphericalPolynomial;
  92666. }
  92667. var results = [];
  92668. var byteArray = null;
  92669. // Push each faces.
  92670. for (var j = 0; j < 6; j++) {
  92671. // Create uintarray fallback.
  92672. if (!scene.getEngine().getCaps().textureFloat) {
  92673. // 3 channels of 1 bytes per pixel in bytes.
  92674. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  92675. byteArray = new Uint8Array(byteBuffer);
  92676. }
  92677. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  92678. // If special cases.
  92679. if (_this.gammaSpace || byteArray) {
  92680. for (var i = 0; i < _this._size * _this._size; i++) {
  92681. // Put in gamma space if requested.
  92682. if (_this.gammaSpace) {
  92683. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  92684. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  92685. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  92686. }
  92687. // Convert to int texture for fallback.
  92688. if (byteArray) {
  92689. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  92690. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  92691. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  92692. // May use luminance instead if the result is not accurate.
  92693. var max = Math.max(Math.max(r, g), b);
  92694. if (max > 255) {
  92695. var scale = 255 / max;
  92696. r *= scale;
  92697. g *= scale;
  92698. b *= scale;
  92699. }
  92700. byteArray[(i * 3) + 0] = r;
  92701. byteArray[(i * 3) + 1] = g;
  92702. byteArray[(i * 3) + 2] = b;
  92703. }
  92704. }
  92705. }
  92706. if (byteArray) {
  92707. results.push(byteArray);
  92708. }
  92709. else {
  92710. results.push(dataFace);
  92711. }
  92712. }
  92713. return results;
  92714. };
  92715. var scene = this.getScene();
  92716. if (scene) {
  92717. 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);
  92718. }
  92719. };
  92720. HDRCubeTexture.prototype.clone = function () {
  92721. var scene = this.getScene();
  92722. if (!scene) {
  92723. return this;
  92724. }
  92725. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  92726. // Base texture
  92727. newTexture.level = this.level;
  92728. newTexture.wrapU = this.wrapU;
  92729. newTexture.wrapV = this.wrapV;
  92730. newTexture.coordinatesIndex = this.coordinatesIndex;
  92731. newTexture.coordinatesMode = this.coordinatesMode;
  92732. return newTexture;
  92733. };
  92734. // Methods
  92735. HDRCubeTexture.prototype.delayLoad = function () {
  92736. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  92737. return;
  92738. }
  92739. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  92740. this._texture = this._getFromCache(this.url, this._noMipmap);
  92741. if (!this._texture) {
  92742. this.loadTexture();
  92743. }
  92744. };
  92745. /**
  92746. * Get the texture reflection matrix used to rotate/transform the reflection.
  92747. * @returns the reflection matrix
  92748. */
  92749. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  92750. return this._textureMatrix;
  92751. };
  92752. /**
  92753. * Set the texture reflection matrix used to rotate/transform the reflection.
  92754. * @param value Define the reflection matrix to set
  92755. */
  92756. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  92757. this._textureMatrix = value;
  92758. };
  92759. /**
  92760. * Parses a JSON representation of an HDR Texture in order to create the texture
  92761. * @param parsedTexture Define the JSON representation
  92762. * @param scene Define the scene the texture should be created in
  92763. * @param rootUrl Define the root url in case we need to load relative dependencies
  92764. * @returns the newly created texture after parsing
  92765. */
  92766. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  92767. var texture = null;
  92768. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  92769. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  92770. texture.name = parsedTexture.name;
  92771. texture.hasAlpha = parsedTexture.hasAlpha;
  92772. texture.level = parsedTexture.level;
  92773. texture.coordinatesMode = parsedTexture.coordinatesMode;
  92774. texture.isBlocking = parsedTexture.isBlocking;
  92775. }
  92776. if (texture) {
  92777. if (parsedTexture.boundingBoxPosition) {
  92778. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  92779. }
  92780. if (parsedTexture.boundingBoxSize) {
  92781. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  92782. }
  92783. if (parsedTexture.rotationY) {
  92784. texture.rotationY = parsedTexture.rotationY;
  92785. }
  92786. }
  92787. return texture;
  92788. };
  92789. HDRCubeTexture.prototype.serialize = function () {
  92790. if (!this.name) {
  92791. return null;
  92792. }
  92793. var serializationObject = {};
  92794. serializationObject.name = this.name;
  92795. serializationObject.hasAlpha = this.hasAlpha;
  92796. serializationObject.isCube = true;
  92797. serializationObject.level = this.level;
  92798. serializationObject.size = this._size;
  92799. serializationObject.coordinatesMode = this.coordinatesMode;
  92800. serializationObject.useInGammaSpace = this.gammaSpace;
  92801. serializationObject.generateHarmonics = this._generateHarmonics;
  92802. serializationObject.customType = "BABYLON.HDRCubeTexture";
  92803. serializationObject.noMipmap = this._noMipmap;
  92804. serializationObject.isBlocking = this._isBlocking;
  92805. serializationObject.rotationY = this._rotationY;
  92806. return serializationObject;
  92807. };
  92808. HDRCubeTexture._facesMapping = [
  92809. "right",
  92810. "left",
  92811. "up",
  92812. "down",
  92813. "front",
  92814. "back"
  92815. ];
  92816. return HDRCubeTexture;
  92817. }(BABYLON.BaseTexture));
  92818. BABYLON.HDRCubeTexture = HDRCubeTexture;
  92819. })(BABYLON || (BABYLON = {}));
  92820. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  92821. var BABYLON;
  92822. (function (BABYLON) {
  92823. /**
  92824. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  92825. */
  92826. var PanoramaToCubeMapTools = /** @class */ (function () {
  92827. function PanoramaToCubeMapTools() {
  92828. }
  92829. /**
  92830. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  92831. *
  92832. * @param float32Array The source data.
  92833. * @param inputWidth The width of the input panorama.
  92834. * @param inputHeight The height of the input panorama.
  92835. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  92836. * @return The cubemap data
  92837. */
  92838. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  92839. if (!float32Array) {
  92840. throw "ConvertPanoramaToCubemap: input cannot be null";
  92841. }
  92842. if (float32Array.length != inputWidth * inputHeight * 3) {
  92843. throw "ConvertPanoramaToCubemap: input size is wrong";
  92844. }
  92845. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  92846. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  92847. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  92848. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  92849. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  92850. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  92851. return {
  92852. front: textureFront,
  92853. back: textureBack,
  92854. left: textureLeft,
  92855. right: textureRight,
  92856. up: textureUp,
  92857. down: textureDown,
  92858. size: size,
  92859. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  92860. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  92861. gammaSpace: false,
  92862. };
  92863. };
  92864. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  92865. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  92866. var textureArray = new Float32Array(buffer);
  92867. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  92868. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  92869. var dy = 1 / texSize;
  92870. var fy = 0;
  92871. for (var y = 0; y < texSize; y++) {
  92872. var xv1 = faceData[0];
  92873. var xv2 = faceData[2];
  92874. for (var x = 0; x < texSize; x++) {
  92875. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  92876. v.normalize();
  92877. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  92878. // 3 channels per pixels
  92879. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  92880. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  92881. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  92882. xv1 = xv1.add(rotDX1);
  92883. xv2 = xv2.add(rotDX2);
  92884. }
  92885. fy += dy;
  92886. }
  92887. return textureArray;
  92888. };
  92889. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  92890. var theta = Math.atan2(vDir.z, vDir.x);
  92891. var phi = Math.acos(vDir.y);
  92892. while (theta < -Math.PI) {
  92893. theta += 2 * Math.PI;
  92894. }
  92895. while (theta > Math.PI) {
  92896. theta -= 2 * Math.PI;
  92897. }
  92898. var dx = theta / Math.PI;
  92899. var dy = phi / Math.PI;
  92900. // recenter.
  92901. dx = dx * 0.5 + 0.5;
  92902. var px = Math.round(dx * inputWidth);
  92903. if (px < 0) {
  92904. px = 0;
  92905. }
  92906. else if (px >= inputWidth) {
  92907. px = inputWidth - 1;
  92908. }
  92909. var py = Math.round(dy * inputHeight);
  92910. if (py < 0) {
  92911. py = 0;
  92912. }
  92913. else if (py >= inputHeight) {
  92914. py = inputHeight - 1;
  92915. }
  92916. var inputY = (inputHeight - py - 1);
  92917. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  92918. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  92919. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  92920. return {
  92921. r: r,
  92922. g: g,
  92923. b: b
  92924. };
  92925. };
  92926. PanoramaToCubeMapTools.FACE_FRONT = [
  92927. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92928. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92929. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92930. new BABYLON.Vector3(1.0, 1.0, -1.0)
  92931. ];
  92932. PanoramaToCubeMapTools.FACE_BACK = [
  92933. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92934. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92935. new BABYLON.Vector3(1.0, 1.0, 1.0),
  92936. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  92937. ];
  92938. PanoramaToCubeMapTools.FACE_RIGHT = [
  92939. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92940. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92941. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92942. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92943. ];
  92944. PanoramaToCubeMapTools.FACE_LEFT = [
  92945. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92946. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92947. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92948. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  92949. ];
  92950. PanoramaToCubeMapTools.FACE_DOWN = [
  92951. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92952. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92953. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92954. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92955. ];
  92956. PanoramaToCubeMapTools.FACE_UP = [
  92957. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92958. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92959. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92960. new BABYLON.Vector3(1.0, -1.0, -1.0)
  92961. ];
  92962. return PanoramaToCubeMapTools;
  92963. }());
  92964. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  92965. })(BABYLON || (BABYLON = {}));
  92966. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  92967. var BABYLON;
  92968. (function (BABYLON) {
  92969. /**
  92970. * Vector2 wth index property
  92971. */
  92972. var IndexedVector2 = /** @class */ (function (_super) {
  92973. __extends(IndexedVector2, _super);
  92974. function IndexedVector2(original,
  92975. /** Index of the vector2 */
  92976. index) {
  92977. var _this = _super.call(this, original.x, original.y) || this;
  92978. _this.index = index;
  92979. return _this;
  92980. }
  92981. return IndexedVector2;
  92982. }(BABYLON.Vector2));
  92983. /**
  92984. * Defines points to create a polygon
  92985. */
  92986. var PolygonPoints = /** @class */ (function () {
  92987. function PolygonPoints() {
  92988. this.elements = new Array();
  92989. }
  92990. PolygonPoints.prototype.add = function (originalPoints) {
  92991. var _this = this;
  92992. var result = new Array();
  92993. originalPoints.forEach(function (point) {
  92994. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  92995. var newPoint = new IndexedVector2(point, _this.elements.length);
  92996. result.push(newPoint);
  92997. _this.elements.push(newPoint);
  92998. }
  92999. });
  93000. return result;
  93001. };
  93002. PolygonPoints.prototype.computeBounds = function () {
  93003. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  93004. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  93005. this.elements.forEach(function (point) {
  93006. // x
  93007. if (point.x < lmin.x) {
  93008. lmin.x = point.x;
  93009. }
  93010. else if (point.x > lmax.x) {
  93011. lmax.x = point.x;
  93012. }
  93013. // y
  93014. if (point.y < lmin.y) {
  93015. lmin.y = point.y;
  93016. }
  93017. else if (point.y > lmax.y) {
  93018. lmax.y = point.y;
  93019. }
  93020. });
  93021. return {
  93022. min: lmin,
  93023. max: lmax,
  93024. width: lmax.x - lmin.x,
  93025. height: lmax.y - lmin.y
  93026. };
  93027. };
  93028. return PolygonPoints;
  93029. }());
  93030. /**
  93031. * Polygon
  93032. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  93033. */
  93034. var Polygon = /** @class */ (function () {
  93035. function Polygon() {
  93036. }
  93037. /**
  93038. * Creates a rectangle
  93039. * @param xmin bottom X coord
  93040. * @param ymin bottom Y coord
  93041. * @param xmax top X coord
  93042. * @param ymax top Y coord
  93043. * @returns points that make the resulting rectation
  93044. */
  93045. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  93046. return [
  93047. new BABYLON.Vector2(xmin, ymin),
  93048. new BABYLON.Vector2(xmax, ymin),
  93049. new BABYLON.Vector2(xmax, ymax),
  93050. new BABYLON.Vector2(xmin, ymax)
  93051. ];
  93052. };
  93053. /**
  93054. * Creates a circle
  93055. * @param radius radius of circle
  93056. * @param cx scale in x
  93057. * @param cy scale in y
  93058. * @param numberOfSides number of sides that make up the circle
  93059. * @returns points that make the resulting circle
  93060. */
  93061. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  93062. if (cx === void 0) { cx = 0; }
  93063. if (cy === void 0) { cy = 0; }
  93064. if (numberOfSides === void 0) { numberOfSides = 32; }
  93065. var result = new Array();
  93066. var angle = 0;
  93067. var increment = (Math.PI * 2) / numberOfSides;
  93068. for (var i = 0; i < numberOfSides; i++) {
  93069. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  93070. angle -= increment;
  93071. }
  93072. return result;
  93073. };
  93074. /**
  93075. * Creates a polygon from input string
  93076. * @param input Input polygon data
  93077. * @returns the parsed points
  93078. */
  93079. Polygon.Parse = function (input) {
  93080. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  93081. var i, result = [];
  93082. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  93083. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  93084. }
  93085. return result;
  93086. };
  93087. /**
  93088. * Starts building a polygon from x and y coordinates
  93089. * @param x x coordinate
  93090. * @param y y coordinate
  93091. * @returns the started path2
  93092. */
  93093. Polygon.StartingAt = function (x, y) {
  93094. return BABYLON.Path2.StartingAt(x, y);
  93095. };
  93096. return Polygon;
  93097. }());
  93098. BABYLON.Polygon = Polygon;
  93099. /**
  93100. * Builds a polygon
  93101. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  93102. */
  93103. var PolygonMeshBuilder = /** @class */ (function () {
  93104. /**
  93105. * Creates a PolygonMeshBuilder
  93106. * @param name name of the builder
  93107. * @param contours Path of the polygon
  93108. * @param scene scene to add to
  93109. */
  93110. function PolygonMeshBuilder(name, contours, scene) {
  93111. this._points = new PolygonPoints();
  93112. this._outlinepoints = new PolygonPoints();
  93113. this._holes = new Array();
  93114. this._epoints = new Array();
  93115. this._eholes = new Array();
  93116. this._name = name;
  93117. this._scene = scene;
  93118. var points;
  93119. if (contours instanceof BABYLON.Path2) {
  93120. points = contours.getPoints();
  93121. }
  93122. else {
  93123. points = contours;
  93124. }
  93125. this._addToepoint(points);
  93126. this._points.add(points);
  93127. this._outlinepoints.add(points);
  93128. if (typeof earcut === 'undefined') {
  93129. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  93130. }
  93131. }
  93132. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  93133. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  93134. var p = points_1[_i];
  93135. this._epoints.push(p.x, p.y);
  93136. }
  93137. };
  93138. /**
  93139. * Adds a whole within the polygon
  93140. * @param hole Array of points defining the hole
  93141. * @returns this
  93142. */
  93143. PolygonMeshBuilder.prototype.addHole = function (hole) {
  93144. this._points.add(hole);
  93145. var holepoints = new PolygonPoints();
  93146. holepoints.add(hole);
  93147. this._holes.push(holepoints);
  93148. this._eholes.push(this._epoints.length / 2);
  93149. this._addToepoint(hole);
  93150. return this;
  93151. };
  93152. /**
  93153. * Creates the polygon
  93154. * @param updatable If the mesh should be updatable
  93155. * @param depth The depth of the mesh created
  93156. * @returns the created mesh
  93157. */
  93158. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  93159. var _this = this;
  93160. if (updatable === void 0) { updatable = false; }
  93161. if (depth === void 0) { depth = 0; }
  93162. var result = new BABYLON.Mesh(this._name, this._scene);
  93163. var normals = new Array();
  93164. var positions = new Array();
  93165. var uvs = new Array();
  93166. var bounds = this._points.computeBounds();
  93167. this._points.elements.forEach(function (p) {
  93168. normals.push(0, 1.0, 0);
  93169. positions.push(p.x, 0, p.y);
  93170. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  93171. });
  93172. var indices = new Array();
  93173. var res = earcut(this._epoints, this._eholes, 2);
  93174. for (var i = 0; i < res.length; i++) {
  93175. indices.push(res[i]);
  93176. }
  93177. if (depth > 0) {
  93178. var positionscount = (positions.length / 3); //get the current pointcount
  93179. this._points.elements.forEach(function (p) {
  93180. normals.push(0, -1.0, 0);
  93181. positions.push(p.x, -depth, p.y);
  93182. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  93183. });
  93184. var totalCount = indices.length;
  93185. for (var i = 0; i < totalCount; i += 3) {
  93186. var i0 = indices[i + 0];
  93187. var i1 = indices[i + 1];
  93188. var i2 = indices[i + 2];
  93189. indices.push(i2 + positionscount);
  93190. indices.push(i1 + positionscount);
  93191. indices.push(i0 + positionscount);
  93192. }
  93193. //Add the sides
  93194. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  93195. this._holes.forEach(function (hole) {
  93196. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  93197. });
  93198. }
  93199. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  93200. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  93201. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  93202. result.setIndices(indices);
  93203. return result;
  93204. };
  93205. /**
  93206. * Adds a side to the polygon
  93207. * @param positions points that make the polygon
  93208. * @param normals normals of the polygon
  93209. * @param uvs uvs of the polygon
  93210. * @param indices indices of the polygon
  93211. * @param bounds bounds of the polygon
  93212. * @param points points of the polygon
  93213. * @param depth depth of the polygon
  93214. * @param flip flip of the polygon
  93215. */
  93216. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  93217. var StartIndex = positions.length / 3;
  93218. var ulength = 0;
  93219. for (var i = 0; i < points.elements.length; i++) {
  93220. var p = points.elements[i];
  93221. var p1;
  93222. if ((i + 1) > points.elements.length - 1) {
  93223. p1 = points.elements[0];
  93224. }
  93225. else {
  93226. p1 = points.elements[i + 1];
  93227. }
  93228. positions.push(p.x, 0, p.y);
  93229. positions.push(p.x, -depth, p.y);
  93230. positions.push(p1.x, 0, p1.y);
  93231. positions.push(p1.x, -depth, p1.y);
  93232. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  93233. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  93234. var v3 = v2.subtract(v1);
  93235. var v4 = new BABYLON.Vector3(0, 1, 0);
  93236. var vn = BABYLON.Vector3.Cross(v3, v4);
  93237. vn = vn.normalize();
  93238. uvs.push(ulength / bounds.width, 0);
  93239. uvs.push(ulength / bounds.width, 1);
  93240. ulength += v3.length();
  93241. uvs.push((ulength / bounds.width), 0);
  93242. uvs.push((ulength / bounds.width), 1);
  93243. if (!flip) {
  93244. normals.push(-vn.x, -vn.y, -vn.z);
  93245. normals.push(-vn.x, -vn.y, -vn.z);
  93246. normals.push(-vn.x, -vn.y, -vn.z);
  93247. normals.push(-vn.x, -vn.y, -vn.z);
  93248. indices.push(StartIndex);
  93249. indices.push(StartIndex + 1);
  93250. indices.push(StartIndex + 2);
  93251. indices.push(StartIndex + 1);
  93252. indices.push(StartIndex + 3);
  93253. indices.push(StartIndex + 2);
  93254. }
  93255. else {
  93256. normals.push(vn.x, vn.y, vn.z);
  93257. normals.push(vn.x, vn.y, vn.z);
  93258. normals.push(vn.x, vn.y, vn.z);
  93259. normals.push(vn.x, vn.y, vn.z);
  93260. indices.push(StartIndex);
  93261. indices.push(StartIndex + 2);
  93262. indices.push(StartIndex + 1);
  93263. indices.push(StartIndex + 1);
  93264. indices.push(StartIndex + 2);
  93265. indices.push(StartIndex + 3);
  93266. }
  93267. StartIndex += 4;
  93268. }
  93269. };
  93270. return PolygonMeshBuilder;
  93271. }());
  93272. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  93273. })(BABYLON || (BABYLON = {}));
  93274. //# sourceMappingURL=babylon.polygonMesh.js.map
  93275. var BABYLON;
  93276. (function (BABYLON) {
  93277. /**
  93278. * Unique ID when we import meshes from Babylon to CSG
  93279. */
  93280. var currentCSGMeshId = 0;
  93281. /**
  93282. * Represents a vertex of a polygon. Use your own vertex class instead of this
  93283. * one to provide additional features like texture coordinates and vertex
  93284. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  93285. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  93286. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  93287. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  93288. * is not used anywhere else.
  93289. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  93290. */
  93291. var Vertex = /** @class */ (function () {
  93292. /**
  93293. * Initializes the vertex
  93294. * @param pos The position of the vertex
  93295. * @param normal The normal of the vertex
  93296. * @param uv The texture coordinate of the vertex
  93297. */
  93298. function Vertex(
  93299. /**
  93300. * The position of the vertex
  93301. */
  93302. pos,
  93303. /**
  93304. * The normal of the vertex
  93305. */
  93306. normal,
  93307. /**
  93308. * The texture coordinate of the vertex
  93309. */
  93310. uv) {
  93311. this.pos = pos;
  93312. this.normal = normal;
  93313. this.uv = uv;
  93314. }
  93315. /**
  93316. * Make a clone, or deep copy, of the vertex
  93317. * @returns A new Vertex
  93318. */
  93319. Vertex.prototype.clone = function () {
  93320. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  93321. };
  93322. /**
  93323. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  93324. * orientation of a polygon is flipped.
  93325. */
  93326. Vertex.prototype.flip = function () {
  93327. this.normal = this.normal.scale(-1);
  93328. };
  93329. /**
  93330. * Create a new vertex between this vertex and `other` by linearly
  93331. * interpolating all properties using a parameter of `t`. Subclasses should
  93332. * override this to interpolate additional properties.
  93333. * @param other the vertex to interpolate against
  93334. * @param t The factor used to linearly interpolate between the vertices
  93335. */
  93336. Vertex.prototype.interpolate = function (other, t) {
  93337. 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));
  93338. };
  93339. return Vertex;
  93340. }());
  93341. /**
  93342. * Represents a plane in 3D space.
  93343. */
  93344. var Plane = /** @class */ (function () {
  93345. /**
  93346. * Initializes the plane
  93347. * @param normal The normal for the plane
  93348. * @param w
  93349. */
  93350. function Plane(normal, w) {
  93351. this.normal = normal;
  93352. this.w = w;
  93353. }
  93354. /**
  93355. * Construct a plane from three points
  93356. * @param a Point a
  93357. * @param b Point b
  93358. * @param c Point c
  93359. */
  93360. Plane.FromPoints = function (a, b, c) {
  93361. var v0 = c.subtract(a);
  93362. var v1 = b.subtract(a);
  93363. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  93364. return null;
  93365. }
  93366. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  93367. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  93368. };
  93369. /**
  93370. * Clone, or make a deep copy of the plane
  93371. * @returns a new Plane
  93372. */
  93373. Plane.prototype.clone = function () {
  93374. return new Plane(this.normal.clone(), this.w);
  93375. };
  93376. /**
  93377. * Flip the face of the plane
  93378. */
  93379. Plane.prototype.flip = function () {
  93380. this.normal.scaleInPlace(-1);
  93381. this.w = -this.w;
  93382. };
  93383. /**
  93384. * Split `polygon` by this plane if needed, then put the polygon or polygon
  93385. * fragments in the appropriate lists. Coplanar polygons go into either
  93386. `* coplanarFront` or `coplanarBack` depending on their orientation with
  93387. * respect to this plane. Polygons in front or in back of this plane go into
  93388. * either `front` or `back`
  93389. * @param polygon The polygon to be split
  93390. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  93391. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  93392. * @param front Will contain the polygons in front of the plane
  93393. * @param back Will contain the polygons begind the plane
  93394. */
  93395. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  93396. var COPLANAR = 0;
  93397. var FRONT = 1;
  93398. var BACK = 2;
  93399. var SPANNING = 3;
  93400. // Classify each point as well as the entire polygon into one of the above
  93401. // four classes.
  93402. var polygonType = 0;
  93403. var types = [];
  93404. var i;
  93405. var t;
  93406. for (i = 0; i < polygon.vertices.length; i++) {
  93407. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  93408. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  93409. polygonType |= type;
  93410. types.push(type);
  93411. }
  93412. // Put the polygon in the correct list, splitting it when necessary
  93413. switch (polygonType) {
  93414. case COPLANAR:
  93415. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  93416. break;
  93417. case FRONT:
  93418. front.push(polygon);
  93419. break;
  93420. case BACK:
  93421. back.push(polygon);
  93422. break;
  93423. case SPANNING:
  93424. var f = [], b = [];
  93425. for (i = 0; i < polygon.vertices.length; i++) {
  93426. var j = (i + 1) % polygon.vertices.length;
  93427. var ti = types[i], tj = types[j];
  93428. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  93429. if (ti !== BACK) {
  93430. f.push(vi);
  93431. }
  93432. if (ti !== FRONT) {
  93433. b.push(ti !== BACK ? vi.clone() : vi);
  93434. }
  93435. if ((ti | tj) === SPANNING) {
  93436. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  93437. var v = vi.interpolate(vj, t);
  93438. f.push(v);
  93439. b.push(v.clone());
  93440. }
  93441. }
  93442. var poly;
  93443. if (f.length >= 3) {
  93444. poly = new Polygon(f, polygon.shared);
  93445. if (poly.plane) {
  93446. front.push(poly);
  93447. }
  93448. }
  93449. if (b.length >= 3) {
  93450. poly = new Polygon(b, polygon.shared);
  93451. if (poly.plane) {
  93452. back.push(poly);
  93453. }
  93454. }
  93455. break;
  93456. }
  93457. };
  93458. /**
  93459. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  93460. * point is on the plane
  93461. */
  93462. Plane.EPSILON = 1e-5;
  93463. return Plane;
  93464. }());
  93465. /**
  93466. * Represents a convex polygon. The vertices used to initialize a polygon must
  93467. * be coplanar and form a convex loop.
  93468. *
  93469. * Each convex polygon has a `shared` property, which is shared between all
  93470. * polygons that are clones of each other or were split from the same polygon.
  93471. * This can be used to define per-polygon properties (such as surface color)
  93472. */
  93473. var Polygon = /** @class */ (function () {
  93474. /**
  93475. * Initializes the polygon
  93476. * @param vertices The vertices of the polygon
  93477. * @param shared The properties shared across all polygons
  93478. */
  93479. function Polygon(vertices, shared) {
  93480. this.vertices = vertices;
  93481. this.shared = shared;
  93482. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  93483. }
  93484. /**
  93485. * Clones, or makes a deep copy, or the polygon
  93486. */
  93487. Polygon.prototype.clone = function () {
  93488. var vertices = this.vertices.map(function (v) { return v.clone(); });
  93489. return new Polygon(vertices, this.shared);
  93490. };
  93491. /**
  93492. * Flips the faces of the polygon
  93493. */
  93494. Polygon.prototype.flip = function () {
  93495. this.vertices.reverse().map(function (v) { v.flip(); });
  93496. this.plane.flip();
  93497. };
  93498. return Polygon;
  93499. }());
  93500. /**
  93501. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  93502. * by picking a polygon to split along. That polygon (and all other coplanar
  93503. * polygons) are added directly to that node and the other polygons are added to
  93504. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  93505. * no distinction between internal and leaf nodes
  93506. */
  93507. var Node = /** @class */ (function () {
  93508. /**
  93509. * Initializes the node
  93510. * @param polygons A collection of polygons held in the node
  93511. */
  93512. function Node(polygons) {
  93513. this.plane = null;
  93514. this.front = null;
  93515. this.back = null;
  93516. this.polygons = new Array();
  93517. if (polygons) {
  93518. this.build(polygons);
  93519. }
  93520. }
  93521. /**
  93522. * Clones, or makes a deep copy, of the node
  93523. * @returns The cloned node
  93524. */
  93525. Node.prototype.clone = function () {
  93526. var node = new Node();
  93527. node.plane = this.plane && this.plane.clone();
  93528. node.front = this.front && this.front.clone();
  93529. node.back = this.back && this.back.clone();
  93530. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  93531. return node;
  93532. };
  93533. /**
  93534. * Convert solid space to empty space and empty space to solid space
  93535. */
  93536. Node.prototype.invert = function () {
  93537. for (var i = 0; i < this.polygons.length; i++) {
  93538. this.polygons[i].flip();
  93539. }
  93540. if (this.plane) {
  93541. this.plane.flip();
  93542. }
  93543. if (this.front) {
  93544. this.front.invert();
  93545. }
  93546. if (this.back) {
  93547. this.back.invert();
  93548. }
  93549. var temp = this.front;
  93550. this.front = this.back;
  93551. this.back = temp;
  93552. };
  93553. /**
  93554. * Recursively remove all polygons in `polygons` that are inside this BSP
  93555. * tree.
  93556. * @param polygons Polygons to remove from the BSP
  93557. * @returns Polygons clipped from the BSP
  93558. */
  93559. Node.prototype.clipPolygons = function (polygons) {
  93560. if (!this.plane) {
  93561. return polygons.slice();
  93562. }
  93563. var front = new Array(), back = new Array();
  93564. for (var i = 0; i < polygons.length; i++) {
  93565. this.plane.splitPolygon(polygons[i], front, back, front, back);
  93566. }
  93567. if (this.front) {
  93568. front = this.front.clipPolygons(front);
  93569. }
  93570. if (this.back) {
  93571. back = this.back.clipPolygons(back);
  93572. }
  93573. else {
  93574. back = [];
  93575. }
  93576. return front.concat(back);
  93577. };
  93578. /**
  93579. * Remove all polygons in this BSP tree that are inside the other BSP tree
  93580. * `bsp`.
  93581. * @param bsp BSP containing polygons to remove from this BSP
  93582. */
  93583. Node.prototype.clipTo = function (bsp) {
  93584. this.polygons = bsp.clipPolygons(this.polygons);
  93585. if (this.front) {
  93586. this.front.clipTo(bsp);
  93587. }
  93588. if (this.back) {
  93589. this.back.clipTo(bsp);
  93590. }
  93591. };
  93592. /**
  93593. * Return a list of all polygons in this BSP tree
  93594. * @returns List of all polygons in this BSP tree
  93595. */
  93596. Node.prototype.allPolygons = function () {
  93597. var polygons = this.polygons.slice();
  93598. if (this.front) {
  93599. polygons = polygons.concat(this.front.allPolygons());
  93600. }
  93601. if (this.back) {
  93602. polygons = polygons.concat(this.back.allPolygons());
  93603. }
  93604. return polygons;
  93605. };
  93606. /**
  93607. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  93608. * new polygons are filtered down to the bottom of the tree and become new
  93609. * nodes there. Each set of polygons is partitioned using the first polygon
  93610. * (no heuristic is used to pick a good split)
  93611. * @param polygons Polygons used to construct the BSP tree
  93612. */
  93613. Node.prototype.build = function (polygons) {
  93614. if (!polygons.length) {
  93615. return;
  93616. }
  93617. if (!this.plane) {
  93618. this.plane = polygons[0].plane.clone();
  93619. }
  93620. var front = new Array(), back = new Array();
  93621. for (var i = 0; i < polygons.length; i++) {
  93622. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  93623. }
  93624. if (front.length) {
  93625. if (!this.front) {
  93626. this.front = new Node();
  93627. }
  93628. this.front.build(front);
  93629. }
  93630. if (back.length) {
  93631. if (!this.back) {
  93632. this.back = new Node();
  93633. }
  93634. this.back.build(back);
  93635. }
  93636. };
  93637. return Node;
  93638. }());
  93639. /**
  93640. * Class for building Constructive Solid Geometry
  93641. */
  93642. var CSG = /** @class */ (function () {
  93643. function CSG() {
  93644. this.polygons = new Array();
  93645. }
  93646. /**
  93647. * Convert the BABYLON.Mesh to BABYLON.CSG
  93648. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  93649. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  93650. */
  93651. CSG.FromMesh = function (mesh) {
  93652. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  93653. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  93654. if (mesh instanceof BABYLON.Mesh) {
  93655. mesh.computeWorldMatrix(true);
  93656. matrix = mesh.getWorldMatrix();
  93657. meshPosition = mesh.position.clone();
  93658. meshRotation = mesh.rotation.clone();
  93659. if (mesh.rotationQuaternion) {
  93660. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  93661. }
  93662. meshScaling = mesh.scaling.clone();
  93663. }
  93664. else {
  93665. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  93666. }
  93667. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93668. var subMeshes = mesh.subMeshes;
  93669. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  93670. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  93671. vertices = [];
  93672. for (var j = 0; j < 3; j++) {
  93673. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  93674. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  93675. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  93676. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  93677. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  93678. vertex = new Vertex(position, normal, uv);
  93679. vertices.push(vertex);
  93680. }
  93681. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  93682. // To handle the case of degenerated triangle
  93683. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  93684. if (polygon.plane) {
  93685. polygons.push(polygon);
  93686. }
  93687. }
  93688. }
  93689. var csg = CSG.FromPolygons(polygons);
  93690. csg.matrix = matrix;
  93691. csg.position = meshPosition;
  93692. csg.rotation = meshRotation;
  93693. csg.scaling = meshScaling;
  93694. csg.rotationQuaternion = meshRotationQuaternion;
  93695. currentCSGMeshId++;
  93696. return csg;
  93697. };
  93698. /**
  93699. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  93700. * @param polygons Polygons used to construct a BABYLON.CSG solid
  93701. */
  93702. CSG.FromPolygons = function (polygons) {
  93703. var csg = new CSG();
  93704. csg.polygons = polygons;
  93705. return csg;
  93706. };
  93707. /**
  93708. * Clones, or makes a deep copy, of the BABYLON.CSG
  93709. * @returns A new BABYLON.CSG
  93710. */
  93711. CSG.prototype.clone = function () {
  93712. var csg = new CSG();
  93713. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  93714. csg.copyTransformAttributes(this);
  93715. return csg;
  93716. };
  93717. /**
  93718. * Unions this CSG with another CSG
  93719. * @param csg The CSG to union against this CSG
  93720. * @returns The unioned CSG
  93721. */
  93722. CSG.prototype.union = function (csg) {
  93723. var a = new Node(this.clone().polygons);
  93724. var b = new Node(csg.clone().polygons);
  93725. a.clipTo(b);
  93726. b.clipTo(a);
  93727. b.invert();
  93728. b.clipTo(a);
  93729. b.invert();
  93730. a.build(b.allPolygons());
  93731. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93732. };
  93733. /**
  93734. * Unions this CSG with another CSG in place
  93735. * @param csg The CSG to union against this CSG
  93736. */
  93737. CSG.prototype.unionInPlace = function (csg) {
  93738. var a = new Node(this.polygons);
  93739. var b = new Node(csg.polygons);
  93740. a.clipTo(b);
  93741. b.clipTo(a);
  93742. b.invert();
  93743. b.clipTo(a);
  93744. b.invert();
  93745. a.build(b.allPolygons());
  93746. this.polygons = a.allPolygons();
  93747. };
  93748. /**
  93749. * Subtracts this CSG with another CSG
  93750. * @param csg The CSG to subtract against this CSG
  93751. * @returns A new BABYLON.CSG
  93752. */
  93753. CSG.prototype.subtract = function (csg) {
  93754. var a = new Node(this.clone().polygons);
  93755. var b = new Node(csg.clone().polygons);
  93756. a.invert();
  93757. a.clipTo(b);
  93758. b.clipTo(a);
  93759. b.invert();
  93760. b.clipTo(a);
  93761. b.invert();
  93762. a.build(b.allPolygons());
  93763. a.invert();
  93764. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93765. };
  93766. /**
  93767. * Subtracts this CSG with another CSG in place
  93768. * @param csg The CSG to subtact against this CSG
  93769. */
  93770. CSG.prototype.subtractInPlace = function (csg) {
  93771. var a = new Node(this.polygons);
  93772. var b = new Node(csg.polygons);
  93773. a.invert();
  93774. a.clipTo(b);
  93775. b.clipTo(a);
  93776. b.invert();
  93777. b.clipTo(a);
  93778. b.invert();
  93779. a.build(b.allPolygons());
  93780. a.invert();
  93781. this.polygons = a.allPolygons();
  93782. };
  93783. /**
  93784. * Intersect this CSG with another CSG
  93785. * @param csg The CSG to intersect against this CSG
  93786. * @returns A new BABYLON.CSG
  93787. */
  93788. CSG.prototype.intersect = function (csg) {
  93789. var a = new Node(this.clone().polygons);
  93790. var b = new Node(csg.clone().polygons);
  93791. a.invert();
  93792. b.clipTo(a);
  93793. b.invert();
  93794. a.clipTo(b);
  93795. b.clipTo(a);
  93796. a.build(b.allPolygons());
  93797. a.invert();
  93798. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93799. };
  93800. /**
  93801. * Intersects this CSG with another CSG in place
  93802. * @param csg The CSG to intersect against this CSG
  93803. */
  93804. CSG.prototype.intersectInPlace = function (csg) {
  93805. var a = new Node(this.polygons);
  93806. var b = new Node(csg.polygons);
  93807. a.invert();
  93808. b.clipTo(a);
  93809. b.invert();
  93810. a.clipTo(b);
  93811. b.clipTo(a);
  93812. a.build(b.allPolygons());
  93813. a.invert();
  93814. this.polygons = a.allPolygons();
  93815. };
  93816. /**
  93817. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  93818. * not modified.
  93819. * @returns A new BABYLON.CSG solid with solid and empty space switched
  93820. */
  93821. CSG.prototype.inverse = function () {
  93822. var csg = this.clone();
  93823. csg.inverseInPlace();
  93824. return csg;
  93825. };
  93826. /**
  93827. * Inverses the BABYLON.CSG in place
  93828. */
  93829. CSG.prototype.inverseInPlace = function () {
  93830. this.polygons.map(function (p) { p.flip(); });
  93831. };
  93832. /**
  93833. * This is used to keep meshes transformations so they can be restored
  93834. * when we build back a Babylon Mesh
  93835. * NB : All CSG operations are performed in world coordinates
  93836. * @param csg The BABYLON.CSG to copy the transform attributes from
  93837. * @returns This BABYLON.CSG
  93838. */
  93839. CSG.prototype.copyTransformAttributes = function (csg) {
  93840. this.matrix = csg.matrix;
  93841. this.position = csg.position;
  93842. this.rotation = csg.rotation;
  93843. this.scaling = csg.scaling;
  93844. this.rotationQuaternion = csg.rotationQuaternion;
  93845. return this;
  93846. };
  93847. /**
  93848. * Build Raw mesh from CSG
  93849. * Coordinates here are in world space
  93850. * @param name The name of the mesh geometry
  93851. * @param scene The BABYLON.Scene
  93852. * @param keepSubMeshes Specifies if the submeshes should be kept
  93853. * @returns A new BABYLON.Mesh
  93854. */
  93855. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  93856. var matrix = this.matrix.clone();
  93857. matrix.invert();
  93858. 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;
  93859. if (keepSubMeshes) {
  93860. // Sort Polygons, since subMeshes are indices range
  93861. polygons.sort(function (a, b) {
  93862. if (a.shared.meshId === b.shared.meshId) {
  93863. return a.shared.subMeshId - b.shared.subMeshId;
  93864. }
  93865. else {
  93866. return a.shared.meshId - b.shared.meshId;
  93867. }
  93868. });
  93869. }
  93870. for (var i = 0, il = polygons.length; i < il; i++) {
  93871. polygon = polygons[i];
  93872. // Building SubMeshes
  93873. if (!subMesh_dict[polygon.shared.meshId]) {
  93874. subMesh_dict[polygon.shared.meshId] = {};
  93875. }
  93876. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  93877. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  93878. indexStart: +Infinity,
  93879. indexEnd: -Infinity,
  93880. materialIndex: polygon.shared.materialIndex
  93881. };
  93882. }
  93883. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  93884. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  93885. polygonIndices[0] = 0;
  93886. polygonIndices[1] = j - 1;
  93887. polygonIndices[2] = j;
  93888. for (var k = 0; k < 3; k++) {
  93889. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  93890. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  93891. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  93892. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  93893. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  93894. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  93895. // Check if 2 points can be merged
  93896. if (!(typeof vertex_idx !== 'undefined' &&
  93897. normals[vertex_idx * 3] === localNormal.x &&
  93898. normals[vertex_idx * 3 + 1] === localNormal.y &&
  93899. normals[vertex_idx * 3 + 2] === localNormal.z &&
  93900. uvs[vertex_idx * 2] === uv.x &&
  93901. uvs[vertex_idx * 2 + 1] === uv.y)) {
  93902. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  93903. uvs.push(uv.x, uv.y);
  93904. normals.push(normal.x, normal.y, normal.z);
  93905. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  93906. }
  93907. indices.push(vertex_idx);
  93908. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  93909. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  93910. currentIndex++;
  93911. }
  93912. }
  93913. }
  93914. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  93915. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  93916. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  93917. mesh.setIndices(indices, null);
  93918. if (keepSubMeshes) {
  93919. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  93920. var materialIndexOffset = 0, materialMaxIndex;
  93921. mesh.subMeshes = new Array();
  93922. for (var m in subMesh_dict) {
  93923. materialMaxIndex = -1;
  93924. for (var sm in subMesh_dict[m]) {
  93925. subMesh_obj = subMesh_dict[m][sm];
  93926. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  93927. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  93928. }
  93929. materialIndexOffset += ++materialMaxIndex;
  93930. }
  93931. }
  93932. return mesh;
  93933. };
  93934. /**
  93935. * Build Mesh from CSG taking material and transforms into account
  93936. * @param name The name of the BABYLON.Mesh
  93937. * @param material The material of the BABYLON.Mesh
  93938. * @param scene The BABYLON.Scene
  93939. * @param keepSubMeshes Specifies if submeshes should be kept
  93940. * @returns The new BABYLON.Mesh
  93941. */
  93942. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  93943. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  93944. mesh.material = material;
  93945. mesh.position.copyFrom(this.position);
  93946. mesh.rotation.copyFrom(this.rotation);
  93947. if (this.rotationQuaternion) {
  93948. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  93949. }
  93950. mesh.scaling.copyFrom(this.scaling);
  93951. mesh.computeWorldMatrix(true);
  93952. return mesh;
  93953. };
  93954. return CSG;
  93955. }());
  93956. BABYLON.CSG = CSG;
  93957. })(BABYLON || (BABYLON = {}));
  93958. //# sourceMappingURL=babylon.csg.js.map
  93959. var BABYLON;
  93960. (function (BABYLON) {
  93961. /**
  93962. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93963. * It controls one of the indiviual texture used in the effect.
  93964. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93965. */
  93966. var LensFlare = /** @class */ (function () {
  93967. /**
  93968. * Instantiates a new Lens Flare.
  93969. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93970. * It controls one of the indiviual texture used in the effect.
  93971. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93972. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  93973. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  93974. * @param color Define the lens color
  93975. * @param imgUrl Define the lens texture url
  93976. * @param system Define the `lensFlareSystem` this flare is part of
  93977. */
  93978. function LensFlare(
  93979. /**
  93980. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  93981. */
  93982. size,
  93983. /**
  93984. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  93985. */
  93986. position, color, imgUrl, system) {
  93987. this.size = size;
  93988. this.position = position;
  93989. /**
  93990. * Define the alpha mode to render this particular lens.
  93991. */
  93992. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93993. this.color = color || new BABYLON.Color3(1, 1, 1);
  93994. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  93995. this._system = system;
  93996. system.lensFlares.push(this);
  93997. }
  93998. /**
  93999. * Creates a new Lens Flare.
  94000. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  94001. * It controls one of the indiviual texture used in the effect.
  94002. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94003. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  94004. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  94005. * @param color Define the lens color
  94006. * @param imgUrl Define the lens texture url
  94007. * @param system Define the `lensFlareSystem` this flare is part of
  94008. * @returns The newly created Lens Flare
  94009. */
  94010. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  94011. return new LensFlare(size, position, color, imgUrl, system);
  94012. };
  94013. /**
  94014. * Dispose and release the lens flare with its associated resources.
  94015. */
  94016. LensFlare.prototype.dispose = function () {
  94017. if (this.texture) {
  94018. this.texture.dispose();
  94019. }
  94020. // Remove from scene
  94021. var index = this._system.lensFlares.indexOf(this);
  94022. this._system.lensFlares.splice(index, 1);
  94023. };
  94024. return LensFlare;
  94025. }());
  94026. BABYLON.LensFlare = LensFlare;
  94027. })(BABYLON || (BABYLON = {}));
  94028. //# sourceMappingURL=babylon.lensFlare.js.map
  94029. var BABYLON;
  94030. (function (BABYLON) {
  94031. // Adds the parser to the scene parsers.
  94032. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  94033. // Lens flares
  94034. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  94035. if (!container.lensFlareSystems) {
  94036. container.lensFlareSystems = new Array();
  94037. }
  94038. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  94039. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  94040. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  94041. container.lensFlareSystems.push(lf);
  94042. }
  94043. }
  94044. });
  94045. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  94046. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  94047. if (this.lensFlareSystems[index].name === name) {
  94048. return this.lensFlareSystems[index];
  94049. }
  94050. }
  94051. return null;
  94052. };
  94053. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  94054. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  94055. if (this.lensFlareSystems[index].id === id) {
  94056. return this.lensFlareSystems[index];
  94057. }
  94058. }
  94059. return null;
  94060. };
  94061. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  94062. var index = this.lensFlareSystems.indexOf(toRemove);
  94063. if (index !== -1) {
  94064. this.lensFlareSystems.splice(index, 1);
  94065. }
  94066. return index;
  94067. };
  94068. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  94069. this.lensFlareSystems.push(newLensFlareSystem);
  94070. };
  94071. /**
  94072. * Defines the lens flare scene component responsible to manage any lens flares
  94073. * in a given scene.
  94074. */
  94075. var LensFlareSystemSceneComponent = /** @class */ (function () {
  94076. /**
  94077. * Creates a new instance of the component for the given scene
  94078. * @param scene Defines the scene to register the component in
  94079. */
  94080. function LensFlareSystemSceneComponent(scene) {
  94081. /**
  94082. * The component name helpfull to identify the component in the list of scene components.
  94083. */
  94084. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  94085. this.scene = scene;
  94086. scene.lensFlareSystems = new Array();
  94087. }
  94088. /**
  94089. * Registers the component in a given scene
  94090. */
  94091. LensFlareSystemSceneComponent.prototype.register = function () {
  94092. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  94093. };
  94094. /**
  94095. * Rebuilds the elements related to this component in case of
  94096. * context lost for instance.
  94097. */
  94098. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  94099. // Nothing to do for lens flare
  94100. };
  94101. /**
  94102. * Adds all the element from the container to the scene
  94103. * @param container the container holding the elements
  94104. */
  94105. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  94106. var _this = this;
  94107. if (!container.lensFlareSystems) {
  94108. return;
  94109. }
  94110. container.lensFlareSystems.forEach(function (o) {
  94111. _this.scene.addLensFlareSystem(o);
  94112. });
  94113. };
  94114. /**
  94115. * Removes all the elements in the container from the scene
  94116. * @param container contains the elements to remove
  94117. */
  94118. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  94119. var _this = this;
  94120. if (!container.lensFlareSystems) {
  94121. return;
  94122. }
  94123. container.lensFlareSystems.forEach(function (o) {
  94124. _this.scene.removeLensFlareSystem(o);
  94125. });
  94126. };
  94127. /**
  94128. * Serializes the component data to the specified json object
  94129. * @param serializationObject The object to serialize to
  94130. */
  94131. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  94132. // Lens flares
  94133. serializationObject.lensFlareSystems = [];
  94134. var lensFlareSystems = this.scene.lensFlareSystems;
  94135. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  94136. var lensFlareSystem = lensFlareSystems_1[_i];
  94137. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  94138. }
  94139. };
  94140. /**
  94141. * Disposes the component and the associated ressources.
  94142. */
  94143. LensFlareSystemSceneComponent.prototype.dispose = function () {
  94144. var lensFlareSystems = this.scene.lensFlareSystems;
  94145. while (lensFlareSystems.length) {
  94146. lensFlareSystems[0].dispose();
  94147. }
  94148. };
  94149. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  94150. // Lens flares
  94151. if (this.scene.lensFlaresEnabled) {
  94152. var lensFlareSystems = this.scene.lensFlareSystems;
  94153. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  94154. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  94155. var lensFlareSystem = lensFlareSystems_2[_i];
  94156. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  94157. lensFlareSystem.render();
  94158. }
  94159. }
  94160. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  94161. }
  94162. };
  94163. return LensFlareSystemSceneComponent;
  94164. }());
  94165. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  94166. })(BABYLON || (BABYLON = {}));
  94167. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  94168. var BABYLON;
  94169. (function (BABYLON) {
  94170. /**
  94171. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  94172. * It is usually composed of several `BABYLON.lensFlare`.
  94173. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94174. */
  94175. var LensFlareSystem = /** @class */ (function () {
  94176. /**
  94177. * Instantiates a lens flare system.
  94178. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  94179. * It is usually composed of several `BABYLON.lensFlare`.
  94180. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  94181. * @param name Define the name of the lens flare system in the scene
  94182. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  94183. * @param scene Define the scene the lens flare system belongs to
  94184. */
  94185. function LensFlareSystem(
  94186. /**
  94187. * Define the name of the lens flare system
  94188. */
  94189. name, emitter, scene) {
  94190. this.name = name;
  94191. /**
  94192. * List of lens flares used in this system.
  94193. */
  94194. this.lensFlares = new Array();
  94195. /**
  94196. * Define a limit from the border the lens flare can be visible.
  94197. */
  94198. this.borderLimit = 300;
  94199. /**
  94200. * Define a viewport border we do not want to see the lens flare in.
  94201. */
  94202. this.viewportBorder = 0;
  94203. /**
  94204. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  94205. */
  94206. this.layerMask = 0x0FFFFFFF;
  94207. this._vertexBuffers = {};
  94208. this._isEnabled = true;
  94209. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94210. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  94211. if (!component) {
  94212. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  94213. scene._addComponent(component);
  94214. }
  94215. this._emitter = emitter;
  94216. this.id = name;
  94217. scene.lensFlareSystems.push(this);
  94218. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  94219. var engine = scene.getEngine();
  94220. // VBO
  94221. var vertices = [];
  94222. vertices.push(1, 1);
  94223. vertices.push(-1, 1);
  94224. vertices.push(-1, -1);
  94225. vertices.push(1, -1);
  94226. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94227. // Indices
  94228. var indices = [];
  94229. indices.push(0);
  94230. indices.push(1);
  94231. indices.push(2);
  94232. indices.push(0);
  94233. indices.push(2);
  94234. indices.push(3);
  94235. this._indexBuffer = engine.createIndexBuffer(indices);
  94236. // Effects
  94237. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  94238. }
  94239. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  94240. /**
  94241. * Define if the lens flare system is enabled.
  94242. */
  94243. get: function () {
  94244. return this._isEnabled;
  94245. },
  94246. set: function (value) {
  94247. this._isEnabled = value;
  94248. },
  94249. enumerable: true,
  94250. configurable: true
  94251. });
  94252. /**
  94253. * Get the scene the effects belongs to.
  94254. * @returns the scene holding the lens flare system
  94255. */
  94256. LensFlareSystem.prototype.getScene = function () {
  94257. return this._scene;
  94258. };
  94259. /**
  94260. * Get the emitter of the lens flare system.
  94261. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  94262. * @returns the emitter of the lens flare system
  94263. */
  94264. LensFlareSystem.prototype.getEmitter = function () {
  94265. return this._emitter;
  94266. };
  94267. /**
  94268. * Set the emitter of the lens flare system.
  94269. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  94270. * @param newEmitter Define the new emitter of the system
  94271. */
  94272. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  94273. this._emitter = newEmitter;
  94274. };
  94275. /**
  94276. * Get the lens flare system emitter position.
  94277. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  94278. * @returns the position
  94279. */
  94280. LensFlareSystem.prototype.getEmitterPosition = function () {
  94281. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  94282. };
  94283. /**
  94284. * @hidden
  94285. */
  94286. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  94287. var position = this.getEmitterPosition();
  94288. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  94289. this._positionX = position.x;
  94290. this._positionY = position.y;
  94291. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  94292. if (this.viewportBorder > 0) {
  94293. globalViewport.x -= this.viewportBorder;
  94294. globalViewport.y -= this.viewportBorder;
  94295. globalViewport.width += this.viewportBorder * 2;
  94296. globalViewport.height += this.viewportBorder * 2;
  94297. position.x += this.viewportBorder;
  94298. position.y += this.viewportBorder;
  94299. this._positionX += this.viewportBorder;
  94300. this._positionY += this.viewportBorder;
  94301. }
  94302. if (position.z > 0) {
  94303. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  94304. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  94305. return true;
  94306. }
  94307. }
  94308. return true;
  94309. }
  94310. return false;
  94311. };
  94312. /** @hidden */
  94313. LensFlareSystem.prototype._isVisible = function () {
  94314. if (!this._isEnabled || !this._scene.activeCamera) {
  94315. return false;
  94316. }
  94317. var emitterPosition = this.getEmitterPosition();
  94318. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  94319. var distance = direction.length();
  94320. direction.normalize();
  94321. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  94322. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  94323. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  94324. };
  94325. /**
  94326. * @hidden
  94327. */
  94328. LensFlareSystem.prototype.render = function () {
  94329. if (!this._effect.isReady() || !this._scene.activeCamera) {
  94330. return false;
  94331. }
  94332. var engine = this._scene.getEngine();
  94333. var viewport = this._scene.activeCamera.viewport;
  94334. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  94335. // Position
  94336. if (!this.computeEffectivePosition(globalViewport)) {
  94337. return false;
  94338. }
  94339. // Visibility
  94340. if (!this._isVisible()) {
  94341. return false;
  94342. }
  94343. // Intensity
  94344. var awayX;
  94345. var awayY;
  94346. if (this._positionX < this.borderLimit + globalViewport.x) {
  94347. awayX = this.borderLimit + globalViewport.x - this._positionX;
  94348. }
  94349. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  94350. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  94351. }
  94352. else {
  94353. awayX = 0;
  94354. }
  94355. if (this._positionY < this.borderLimit + globalViewport.y) {
  94356. awayY = this.borderLimit + globalViewport.y - this._positionY;
  94357. }
  94358. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  94359. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  94360. }
  94361. else {
  94362. awayY = 0;
  94363. }
  94364. var away = (awayX > awayY) ? awayX : awayY;
  94365. away -= this.viewportBorder;
  94366. if (away > this.borderLimit) {
  94367. away = this.borderLimit;
  94368. }
  94369. var intensity = 1.0 - (away / this.borderLimit);
  94370. if (intensity < 0) {
  94371. return false;
  94372. }
  94373. if (intensity > 1.0) {
  94374. intensity = 1.0;
  94375. }
  94376. if (this.viewportBorder > 0) {
  94377. globalViewport.x += this.viewportBorder;
  94378. globalViewport.y += this.viewportBorder;
  94379. globalViewport.width -= this.viewportBorder * 2;
  94380. globalViewport.height -= this.viewportBorder * 2;
  94381. this._positionX -= this.viewportBorder;
  94382. this._positionY -= this.viewportBorder;
  94383. }
  94384. // Position
  94385. var centerX = globalViewport.x + globalViewport.width / 2;
  94386. var centerY = globalViewport.y + globalViewport.height / 2;
  94387. var distX = centerX - this._positionX;
  94388. var distY = centerY - this._positionY;
  94389. // Effects
  94390. engine.enableEffect(this._effect);
  94391. engine.setState(false);
  94392. engine.setDepthBuffer(false);
  94393. // VBOs
  94394. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  94395. // Flares
  94396. for (var index = 0; index < this.lensFlares.length; index++) {
  94397. var flare = this.lensFlares[index];
  94398. engine.setAlphaMode(flare.alphaMode);
  94399. var x = centerX - (distX * flare.position);
  94400. var y = centerY - (distY * flare.position);
  94401. var cw = flare.size;
  94402. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  94403. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  94404. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  94405. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  94406. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  94407. // Texture
  94408. this._effect.setTexture("textureSampler", flare.texture);
  94409. // Color
  94410. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  94411. // Draw order
  94412. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94413. }
  94414. engine.setDepthBuffer(true);
  94415. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94416. return true;
  94417. };
  94418. /**
  94419. * Dispose and release the lens flare with its associated resources.
  94420. */
  94421. LensFlareSystem.prototype.dispose = function () {
  94422. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94423. if (vertexBuffer) {
  94424. vertexBuffer.dispose();
  94425. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94426. }
  94427. if (this._indexBuffer) {
  94428. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94429. this._indexBuffer = null;
  94430. }
  94431. while (this.lensFlares.length) {
  94432. this.lensFlares[0].dispose();
  94433. }
  94434. // Remove from scene
  94435. var index = this._scene.lensFlareSystems.indexOf(this);
  94436. this._scene.lensFlareSystems.splice(index, 1);
  94437. };
  94438. /**
  94439. * Parse a lens flare system from a JSON repressentation
  94440. * @param parsedLensFlareSystem Define the JSON to parse
  94441. * @param scene Define the scene the parsed system should be instantiated in
  94442. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  94443. * @returns the parsed system
  94444. */
  94445. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  94446. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  94447. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  94448. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  94449. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  94450. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  94451. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  94452. var parsedFlare = parsedLensFlareSystem.flares[index];
  94453. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  94454. }
  94455. return lensFlareSystem;
  94456. };
  94457. /**
  94458. * Serialize the current Lens Flare System into a JSON representation.
  94459. * @returns the serialized JSON
  94460. */
  94461. LensFlareSystem.prototype.serialize = function () {
  94462. var serializationObject = {};
  94463. serializationObject.id = this.id;
  94464. serializationObject.name = this.name;
  94465. serializationObject.emitterId = this.getEmitter().id;
  94466. serializationObject.borderLimit = this.borderLimit;
  94467. serializationObject.flares = [];
  94468. for (var index = 0; index < this.lensFlares.length; index++) {
  94469. var flare = this.lensFlares[index];
  94470. serializationObject.flares.push({
  94471. size: flare.size,
  94472. position: flare.position,
  94473. color: flare.color.asArray(),
  94474. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  94475. });
  94476. }
  94477. return serializationObject;
  94478. };
  94479. return LensFlareSystem;
  94480. }());
  94481. BABYLON.LensFlareSystem = LensFlareSystem;
  94482. })(BABYLON || (BABYLON = {}));
  94483. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  94484. var BABYLON;
  94485. (function (BABYLON) {
  94486. /**
  94487. * This is a holder class for the physics joint created by the physics plugin
  94488. * It holds a set of functions to control the underlying joint
  94489. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94490. */
  94491. var PhysicsJoint = /** @class */ (function () {
  94492. /**
  94493. * Initializes the physics joint
  94494. * @param type The type of the physics joint
  94495. * @param jointData The data for the physics joint
  94496. */
  94497. function PhysicsJoint(
  94498. /**
  94499. * The type of the physics joint
  94500. */
  94501. type,
  94502. /**
  94503. * The data for the physics joint
  94504. */
  94505. jointData) {
  94506. this.type = type;
  94507. this.jointData = jointData;
  94508. jointData.nativeParams = jointData.nativeParams || {};
  94509. }
  94510. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  94511. /**
  94512. * Gets the physics joint
  94513. */
  94514. get: function () {
  94515. return this._physicsJoint;
  94516. },
  94517. /**
  94518. * Sets the physics joint
  94519. */
  94520. set: function (newJoint) {
  94521. if (this._physicsJoint) {
  94522. //remove from the wolrd
  94523. }
  94524. this._physicsJoint = newJoint;
  94525. },
  94526. enumerable: true,
  94527. configurable: true
  94528. });
  94529. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  94530. /**
  94531. * Sets the physics plugin
  94532. */
  94533. set: function (physicsPlugin) {
  94534. this._physicsPlugin = physicsPlugin;
  94535. },
  94536. enumerable: true,
  94537. configurable: true
  94538. });
  94539. /**
  94540. * Execute a function that is physics-plugin specific.
  94541. * @param {Function} func the function that will be executed.
  94542. * It accepts two parameters: the physics world and the physics joint
  94543. */
  94544. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  94545. func(this._physicsPlugin.world, this._physicsJoint);
  94546. };
  94547. //TODO check if the native joints are the same
  94548. //Joint Types
  94549. /**
  94550. * Distance-Joint type
  94551. */
  94552. PhysicsJoint.DistanceJoint = 0;
  94553. /**
  94554. * Hinge-Joint type
  94555. */
  94556. PhysicsJoint.HingeJoint = 1;
  94557. /**
  94558. * Ball-and-Socket joint type
  94559. */
  94560. PhysicsJoint.BallAndSocketJoint = 2;
  94561. /**
  94562. * Wheel-Joint type
  94563. */
  94564. PhysicsJoint.WheelJoint = 3;
  94565. /**
  94566. * Slider-Joint type
  94567. */
  94568. PhysicsJoint.SliderJoint = 4;
  94569. //OIMO
  94570. /**
  94571. * Prismatic-Joint type
  94572. */
  94573. PhysicsJoint.PrismaticJoint = 5;
  94574. //
  94575. /**
  94576. * Universal-Joint type
  94577. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  94578. */
  94579. PhysicsJoint.UniversalJoint = 6;
  94580. /**
  94581. * Hinge-Joint 2 type
  94582. */
  94583. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  94584. //Cannon
  94585. /**
  94586. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  94587. */
  94588. PhysicsJoint.PointToPointJoint = 8;
  94589. //Cannon only at the moment
  94590. /**
  94591. * Spring-Joint type
  94592. */
  94593. PhysicsJoint.SpringJoint = 9;
  94594. /**
  94595. * Lock-Joint type
  94596. */
  94597. PhysicsJoint.LockJoint = 10;
  94598. return PhysicsJoint;
  94599. }());
  94600. BABYLON.PhysicsJoint = PhysicsJoint;
  94601. /**
  94602. * A class representing a physics distance joint
  94603. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94604. */
  94605. var DistanceJoint = /** @class */ (function (_super) {
  94606. __extends(DistanceJoint, _super);
  94607. /**
  94608. *
  94609. * @param jointData The data for the Distance-Joint
  94610. */
  94611. function DistanceJoint(jointData) {
  94612. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  94613. }
  94614. /**
  94615. * Update the predefined distance.
  94616. * @param maxDistance The maximum preferred distance
  94617. * @param minDistance The minimum preferred distance
  94618. */
  94619. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  94620. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  94621. };
  94622. return DistanceJoint;
  94623. }(PhysicsJoint));
  94624. BABYLON.DistanceJoint = DistanceJoint;
  94625. /**
  94626. * Represents a Motor-Enabled Joint
  94627. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94628. */
  94629. var MotorEnabledJoint = /** @class */ (function (_super) {
  94630. __extends(MotorEnabledJoint, _super);
  94631. /**
  94632. * Initializes the Motor-Enabled Joint
  94633. * @param type The type of the joint
  94634. * @param jointData The physica joint data for the joint
  94635. */
  94636. function MotorEnabledJoint(type, jointData) {
  94637. return _super.call(this, type, jointData) || this;
  94638. }
  94639. /**
  94640. * Set the motor values.
  94641. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94642. * @param force the force to apply
  94643. * @param maxForce max force for this motor.
  94644. */
  94645. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  94646. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94647. };
  94648. /**
  94649. * Set the motor's limits.
  94650. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94651. * @param upperLimit The upper limit of the motor
  94652. * @param lowerLimit The lower limit of the motor
  94653. */
  94654. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94655. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94656. };
  94657. return MotorEnabledJoint;
  94658. }(PhysicsJoint));
  94659. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  94660. /**
  94661. * This class represents a single physics Hinge-Joint
  94662. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94663. */
  94664. var HingeJoint = /** @class */ (function (_super) {
  94665. __extends(HingeJoint, _super);
  94666. /**
  94667. * Initializes the Hinge-Joint
  94668. * @param jointData The joint data for the Hinge-Joint
  94669. */
  94670. function HingeJoint(jointData) {
  94671. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  94672. }
  94673. /**
  94674. * Set the motor values.
  94675. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94676. * @param {number} force the force to apply
  94677. * @param {number} maxForce max force for this motor.
  94678. */
  94679. HingeJoint.prototype.setMotor = function (force, maxForce) {
  94680. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94681. };
  94682. /**
  94683. * Set the motor's limits.
  94684. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94685. * @param upperLimit The upper limit of the motor
  94686. * @param lowerLimit The lower limit of the motor
  94687. */
  94688. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94689. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94690. };
  94691. return HingeJoint;
  94692. }(MotorEnabledJoint));
  94693. BABYLON.HingeJoint = HingeJoint;
  94694. /**
  94695. * This class represents a dual hinge physics joint (same as wheel joint)
  94696. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94697. */
  94698. var Hinge2Joint = /** @class */ (function (_super) {
  94699. __extends(Hinge2Joint, _super);
  94700. /**
  94701. * Initializes the Hinge2-Joint
  94702. * @param jointData The joint data for the Hinge2-Joint
  94703. */
  94704. function Hinge2Joint(jointData) {
  94705. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  94706. }
  94707. /**
  94708. * Set the motor values.
  94709. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94710. * @param {number} force the force to apply
  94711. * @param {number} maxForce max force for this motor.
  94712. * @param {motorIndex} the motor's index, 0 or 1.
  94713. */
  94714. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  94715. if (motorIndex === void 0) { motorIndex = 0; }
  94716. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  94717. };
  94718. /**
  94719. * Set the motor limits.
  94720. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94721. * @param {number} upperLimit the upper limit
  94722. * @param {number} lowerLimit lower limit
  94723. * @param {motorIndex} the motor's index, 0 or 1.
  94724. */
  94725. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  94726. if (motorIndex === void 0) { motorIndex = 0; }
  94727. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  94728. };
  94729. return Hinge2Joint;
  94730. }(MotorEnabledJoint));
  94731. BABYLON.Hinge2Joint = Hinge2Joint;
  94732. })(BABYLON || (BABYLON = {}));
  94733. //# sourceMappingURL=babylon.physicsJoint.js.map
  94734. var BABYLON;
  94735. (function (BABYLON) {
  94736. /**
  94737. * Represents a physics imposter
  94738. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94739. */
  94740. var PhysicsImpostor = /** @class */ (function () {
  94741. /**
  94742. * Initializes the physics imposter
  94743. * @param object The physics-enabled object used as the physics imposter
  94744. * @param type The type of the physics imposter
  94745. * @param _options The options for the physics imposter
  94746. * @param _scene The Babylon scene
  94747. */
  94748. function PhysicsImpostor(
  94749. /**
  94750. * The physics-enabled object used as the physics imposter
  94751. */
  94752. object,
  94753. /**
  94754. * The type of the physics imposter
  94755. */
  94756. type, _options, _scene) {
  94757. if (_options === void 0) { _options = { mass: 0 }; }
  94758. var _this = this;
  94759. this.object = object;
  94760. this.type = type;
  94761. this._options = _options;
  94762. this._scene = _scene;
  94763. this._bodyUpdateRequired = false;
  94764. this._onBeforePhysicsStepCallbacks = new Array();
  94765. this._onAfterPhysicsStepCallbacks = new Array();
  94766. this._onPhysicsCollideCallbacks = [];
  94767. this._deltaPosition = BABYLON.Vector3.Zero();
  94768. this._isDisposed = false;
  94769. //temp variables for parent rotation calculations
  94770. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  94771. this._tmpQuat = new BABYLON.Quaternion();
  94772. this._tmpQuat2 = new BABYLON.Quaternion();
  94773. /**
  94774. * this function is executed by the physics engine.
  94775. */
  94776. this.beforeStep = function () {
  94777. if (!_this._physicsEngine) {
  94778. return;
  94779. }
  94780. _this.object.translate(_this._deltaPosition, -1);
  94781. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  94782. _this.object.computeWorldMatrix(false);
  94783. if (_this.object.parent && _this.object.rotationQuaternion) {
  94784. _this.getParentsRotation();
  94785. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  94786. }
  94787. else {
  94788. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  94789. }
  94790. if (!_this._options.disableBidirectionalTransformation) {
  94791. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  94792. }
  94793. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  94794. func(_this);
  94795. });
  94796. };
  94797. /**
  94798. * this function is executed by the physics engine
  94799. */
  94800. this.afterStep = function () {
  94801. if (!_this._physicsEngine) {
  94802. return;
  94803. }
  94804. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  94805. func(_this);
  94806. });
  94807. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  94808. // object has now its world rotation. needs to be converted to local.
  94809. if (_this.object.parent && _this.object.rotationQuaternion) {
  94810. _this.getParentsRotation();
  94811. _this._tmpQuat.conjugateInPlace();
  94812. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  94813. }
  94814. // take the position set and make it the absolute position of this object.
  94815. _this.object.setAbsolutePosition(_this.object.position);
  94816. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  94817. _this.object.translate(_this._deltaPosition, 1);
  94818. };
  94819. /**
  94820. * Legacy collision detection event support
  94821. */
  94822. this.onCollideEvent = null;
  94823. /**
  94824. * event and body object due to cannon's event-based architecture.
  94825. */
  94826. this.onCollide = function (e) {
  94827. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  94828. return;
  94829. }
  94830. if (!_this._physicsEngine) {
  94831. return;
  94832. }
  94833. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  94834. if (otherImpostor) {
  94835. // Legacy collision detection event support
  94836. if (_this.onCollideEvent) {
  94837. _this.onCollideEvent(_this, otherImpostor);
  94838. }
  94839. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  94840. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  94841. }).forEach(function (obj) {
  94842. obj.callback(_this, otherImpostor);
  94843. });
  94844. }
  94845. };
  94846. //sanity check!
  94847. if (!this.object) {
  94848. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  94849. return;
  94850. }
  94851. //legacy support for old syntax.
  94852. if (!this._scene && object.getScene) {
  94853. this._scene = object.getScene();
  94854. }
  94855. if (!this._scene) {
  94856. return;
  94857. }
  94858. this._physicsEngine = this._scene.getPhysicsEngine();
  94859. if (!this._physicsEngine) {
  94860. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  94861. }
  94862. else {
  94863. //set the object's quaternion, if not set
  94864. if (!this.object.rotationQuaternion) {
  94865. if (this.object.rotation) {
  94866. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  94867. }
  94868. else {
  94869. this.object.rotationQuaternion = new BABYLON.Quaternion();
  94870. }
  94871. }
  94872. //default options params
  94873. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  94874. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  94875. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  94876. this._joints = [];
  94877. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  94878. if (!this.object.parent || this._options.ignoreParent) {
  94879. this._init();
  94880. }
  94881. else if (this.object.parent.physicsImpostor) {
  94882. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  94883. }
  94884. }
  94885. }
  94886. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  94887. /**
  94888. * Specifies if the physics imposter is disposed
  94889. */
  94890. get: function () {
  94891. return this._isDisposed;
  94892. },
  94893. enumerable: true,
  94894. configurable: true
  94895. });
  94896. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  94897. /**
  94898. * Gets the mass of the physics imposter
  94899. */
  94900. get: function () {
  94901. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  94902. },
  94903. set: function (value) {
  94904. this.setMass(value);
  94905. },
  94906. enumerable: true,
  94907. configurable: true
  94908. });
  94909. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  94910. /**
  94911. * Gets the coefficient of friction
  94912. */
  94913. get: function () {
  94914. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  94915. },
  94916. /**
  94917. * Sets the coefficient of friction
  94918. */
  94919. set: function (value) {
  94920. if (!this._physicsEngine) {
  94921. return;
  94922. }
  94923. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  94924. },
  94925. enumerable: true,
  94926. configurable: true
  94927. });
  94928. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  94929. /**
  94930. * Gets the coefficient of restitution
  94931. */
  94932. get: function () {
  94933. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  94934. },
  94935. /**
  94936. * Sets the coefficient of restitution
  94937. */
  94938. set: function (value) {
  94939. if (!this._physicsEngine) {
  94940. return;
  94941. }
  94942. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  94943. },
  94944. enumerable: true,
  94945. configurable: true
  94946. });
  94947. /**
  94948. * This function will completly initialize this impostor.
  94949. * It will create a new body - but only if this mesh has no parent.
  94950. * If it has, this impostor will not be used other than to define the impostor
  94951. * of the child mesh.
  94952. * @hidden
  94953. */
  94954. PhysicsImpostor.prototype._init = function () {
  94955. if (!this._physicsEngine) {
  94956. return;
  94957. }
  94958. this._physicsEngine.removeImpostor(this);
  94959. this.physicsBody = null;
  94960. this._parent = this._parent || this._getPhysicsParent();
  94961. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  94962. this._physicsEngine.addImpostor(this);
  94963. }
  94964. };
  94965. PhysicsImpostor.prototype._getPhysicsParent = function () {
  94966. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  94967. var parentMesh = this.object.parent;
  94968. return parentMesh.physicsImpostor;
  94969. }
  94970. return null;
  94971. };
  94972. /**
  94973. * Should a new body be generated.
  94974. * @returns boolean specifying if body initialization is required
  94975. */
  94976. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  94977. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  94978. };
  94979. /**
  94980. * Sets the updated scaling
  94981. * @param updated Specifies if the scaling is updated
  94982. */
  94983. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  94984. this.forceUpdate();
  94985. };
  94986. /**
  94987. * Force a regeneration of this or the parent's impostor's body.
  94988. * Use under cautious - This will remove all joints already implemented.
  94989. */
  94990. PhysicsImpostor.prototype.forceUpdate = function () {
  94991. this._init();
  94992. if (this.parent && !this._options.ignoreParent) {
  94993. this.parent.forceUpdate();
  94994. }
  94995. };
  94996. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  94997. /*public get mesh(): AbstractMesh {
  94998. return this._mesh;
  94999. }*/
  95000. /**
  95001. * Gets the body that holds this impostor. Either its own, or its parent.
  95002. */
  95003. get: function () {
  95004. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  95005. },
  95006. /**
  95007. * Set the physics body. Used mainly by the physics engine/plugin
  95008. */
  95009. set: function (physicsBody) {
  95010. if (this._physicsBody && this._physicsEngine) {
  95011. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  95012. }
  95013. this._physicsBody = physicsBody;
  95014. this.resetUpdateFlags();
  95015. },
  95016. enumerable: true,
  95017. configurable: true
  95018. });
  95019. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  95020. /**
  95021. * Get the parent of the physics imposter
  95022. * @returns Physics imposter or null
  95023. */
  95024. get: function () {
  95025. return !this._options.ignoreParent && this._parent ? this._parent : null;
  95026. },
  95027. /**
  95028. * Sets the parent of the physics imposter
  95029. */
  95030. set: function (value) {
  95031. this._parent = value;
  95032. },
  95033. enumerable: true,
  95034. configurable: true
  95035. });
  95036. /**
  95037. * Resets the update flags
  95038. */
  95039. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  95040. this._bodyUpdateRequired = false;
  95041. };
  95042. /**
  95043. * Gets the object extend size
  95044. * @returns the object extend size
  95045. */
  95046. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  95047. if (this.object.getBoundingInfo) {
  95048. var q = this.object.rotationQuaternion;
  95049. //reset rotation
  95050. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  95051. //calculate the world matrix with no rotation
  95052. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  95053. var boundingInfo = this.object.getBoundingInfo();
  95054. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  95055. //bring back the rotation
  95056. this.object.rotationQuaternion = q;
  95057. //calculate the world matrix with the new rotation
  95058. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  95059. return size;
  95060. }
  95061. else {
  95062. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  95063. }
  95064. };
  95065. /**
  95066. * Gets the object center
  95067. * @returns The object center
  95068. */
  95069. PhysicsImpostor.prototype.getObjectCenter = function () {
  95070. if (this.object.getBoundingInfo) {
  95071. var boundingInfo = this.object.getBoundingInfo();
  95072. return boundingInfo.boundingBox.centerWorld;
  95073. }
  95074. else {
  95075. return this.object.position;
  95076. }
  95077. };
  95078. /**
  95079. * Get a specific parametes from the options parameter
  95080. * @param paramName The object parameter name
  95081. * @returns The object parameter
  95082. */
  95083. PhysicsImpostor.prototype.getParam = function (paramName) {
  95084. return this._options[paramName];
  95085. };
  95086. /**
  95087. * Sets a specific parameter in the options given to the physics plugin
  95088. * @param paramName The parameter name
  95089. * @param value The value of the parameter
  95090. */
  95091. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  95092. this._options[paramName] = value;
  95093. this._bodyUpdateRequired = true;
  95094. };
  95095. /**
  95096. * Specifically change the body's mass option. Won't recreate the physics body object
  95097. * @param mass The mass of the physics imposter
  95098. */
  95099. PhysicsImpostor.prototype.setMass = function (mass) {
  95100. if (this.getParam("mass") !== mass) {
  95101. this.setParam("mass", mass);
  95102. }
  95103. if (this._physicsEngine) {
  95104. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  95105. }
  95106. };
  95107. /**
  95108. * Gets the linear velocity
  95109. * @returns linear velocity or null
  95110. */
  95111. PhysicsImpostor.prototype.getLinearVelocity = function () {
  95112. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  95113. };
  95114. /**
  95115. * Sets the linear velocity
  95116. * @param velocity linear velocity or null
  95117. */
  95118. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  95119. if (this._physicsEngine) {
  95120. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  95121. }
  95122. };
  95123. /**
  95124. * Gets the angular velocity
  95125. * @returns angular velocity or null
  95126. */
  95127. PhysicsImpostor.prototype.getAngularVelocity = function () {
  95128. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  95129. };
  95130. /**
  95131. * Sets the angular velocity
  95132. * @param velocity The velocity or null
  95133. */
  95134. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  95135. if (this._physicsEngine) {
  95136. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  95137. }
  95138. };
  95139. /**
  95140. * Execute a function with the physics plugin native code
  95141. * Provide a function the will have two variables - the world object and the physics body object
  95142. * @param func The function to execute with the physics plugin native code
  95143. */
  95144. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  95145. if (this._physicsEngine) {
  95146. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  95147. }
  95148. };
  95149. /**
  95150. * Register a function that will be executed before the physics world is stepping forward
  95151. * @param func The function to execute before the physics world is stepped forward
  95152. */
  95153. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  95154. this._onBeforePhysicsStepCallbacks.push(func);
  95155. };
  95156. /**
  95157. * Unregister a function that will be executed before the physics world is stepping forward
  95158. * @param func The function to execute before the physics world is stepped forward
  95159. */
  95160. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  95161. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  95162. if (index > -1) {
  95163. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  95164. }
  95165. else {
  95166. BABYLON.Tools.Warn("Function to remove was not found");
  95167. }
  95168. };
  95169. /**
  95170. * Register a function that will be executed after the physics step
  95171. * @param func The function to execute after physics step
  95172. */
  95173. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  95174. this._onAfterPhysicsStepCallbacks.push(func);
  95175. };
  95176. /**
  95177. * Unregisters a function that will be executed after the physics step
  95178. * @param func The function to execute after physics step
  95179. */
  95180. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  95181. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  95182. if (index > -1) {
  95183. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  95184. }
  95185. else {
  95186. BABYLON.Tools.Warn("Function to remove was not found");
  95187. }
  95188. };
  95189. /**
  95190. * register a function that will be executed when this impostor collides against a different body
  95191. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  95192. * @param func Callback that is executed on collision
  95193. */
  95194. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  95195. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  95196. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  95197. };
  95198. /**
  95199. * Unregisters the physics imposter on contact
  95200. * @param collideAgainst The physics object to collide against
  95201. * @param func Callback to execute on collision
  95202. */
  95203. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  95204. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  95205. var index = -1;
  95206. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  95207. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  95208. // chcek the arrays match
  95209. var sameList = cbDef.otherImpostors.every(function (impostor) {
  95210. return collidedAgainstList.indexOf(impostor) > -1;
  95211. });
  95212. if (sameList) {
  95213. index = idx;
  95214. }
  95215. return sameList;
  95216. }
  95217. return false;
  95218. });
  95219. if (found) {
  95220. this._onPhysicsCollideCallbacks.splice(index, 1);
  95221. }
  95222. else {
  95223. BABYLON.Tools.Warn("Function to remove was not found");
  95224. }
  95225. };
  95226. /**
  95227. * Get the parent rotation
  95228. * @returns The parent rotation
  95229. */
  95230. PhysicsImpostor.prototype.getParentsRotation = function () {
  95231. var parent = this.object.parent;
  95232. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  95233. while (parent) {
  95234. if (parent.rotationQuaternion) {
  95235. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  95236. }
  95237. else {
  95238. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  95239. }
  95240. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  95241. parent = parent.parent;
  95242. }
  95243. return this._tmpQuat;
  95244. };
  95245. /**
  95246. * Apply a force
  95247. * @param force The force to apply
  95248. * @param contactPoint The contact point for the force
  95249. * @returns The physics imposter
  95250. */
  95251. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  95252. if (this._physicsEngine) {
  95253. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  95254. }
  95255. return this;
  95256. };
  95257. /**
  95258. * Apply an impulse
  95259. * @param force The impulse force
  95260. * @param contactPoint The contact point for the impulse force
  95261. * @returns The physics imposter
  95262. */
  95263. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  95264. if (this._physicsEngine) {
  95265. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  95266. }
  95267. return this;
  95268. };
  95269. /**
  95270. * A help function to create a joint
  95271. * @param otherImpostor A physics imposter used to create a joint
  95272. * @param jointType The type of joint
  95273. * @param jointData The data for the joint
  95274. * @returns The physics imposter
  95275. */
  95276. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  95277. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  95278. this.addJoint(otherImpostor, joint);
  95279. return this;
  95280. };
  95281. /**
  95282. * Add a joint to this impostor with a different impostor
  95283. * @param otherImpostor A physics imposter used to add a joint
  95284. * @param joint The joint to add
  95285. * @returns The physics imposter
  95286. */
  95287. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  95288. this._joints.push({
  95289. otherImpostor: otherImpostor,
  95290. joint: joint
  95291. });
  95292. if (this._physicsEngine) {
  95293. this._physicsEngine.addJoint(this, otherImpostor, joint);
  95294. }
  95295. return this;
  95296. };
  95297. /**
  95298. * Will keep this body still, in a sleep mode.
  95299. * @returns the physics imposter
  95300. */
  95301. PhysicsImpostor.prototype.sleep = function () {
  95302. if (this._physicsEngine) {
  95303. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  95304. }
  95305. return this;
  95306. };
  95307. /**
  95308. * Wake the body up.
  95309. * @returns The physics imposter
  95310. */
  95311. PhysicsImpostor.prototype.wakeUp = function () {
  95312. if (this._physicsEngine) {
  95313. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  95314. }
  95315. return this;
  95316. };
  95317. /**
  95318. * Clones the physics imposter
  95319. * @param newObject The physics imposter clones to this physics-enabled object
  95320. * @returns A nullable physics imposter
  95321. */
  95322. PhysicsImpostor.prototype.clone = function (newObject) {
  95323. if (!newObject) {
  95324. return null;
  95325. }
  95326. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  95327. };
  95328. /**
  95329. * Disposes the physics imposter
  95330. */
  95331. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  95332. var _this = this;
  95333. //no dispose if no physics engine is available.
  95334. if (!this._physicsEngine) {
  95335. return;
  95336. }
  95337. this._joints.forEach(function (j) {
  95338. if (_this._physicsEngine) {
  95339. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  95340. }
  95341. });
  95342. //dispose the physics body
  95343. this._physicsEngine.removeImpostor(this);
  95344. if (this.parent) {
  95345. this.parent.forceUpdate();
  95346. }
  95347. else {
  95348. /*this._object.getChildMeshes().forEach(function(mesh) {
  95349. if (mesh.physicsImpostor) {
  95350. if (disposeChildren) {
  95351. mesh.physicsImpostor.dispose();
  95352. mesh.physicsImpostor = null;
  95353. }
  95354. }
  95355. })*/
  95356. }
  95357. this._isDisposed = true;
  95358. };
  95359. /**
  95360. * Sets the delta position
  95361. * @param position The delta position amount
  95362. */
  95363. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  95364. this._deltaPosition.copyFrom(position);
  95365. };
  95366. /**
  95367. * Sets the delta rotation
  95368. * @param rotation The delta rotation amount
  95369. */
  95370. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  95371. if (!this._deltaRotation) {
  95372. this._deltaRotation = new BABYLON.Quaternion();
  95373. }
  95374. this._deltaRotation.copyFrom(rotation);
  95375. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  95376. };
  95377. /**
  95378. * Gets the box size of the physics imposter and stores the result in the input parameter
  95379. * @param result Stores the box size
  95380. * @returns The physics imposter
  95381. */
  95382. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  95383. if (this._physicsEngine) {
  95384. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  95385. }
  95386. return this;
  95387. };
  95388. /**
  95389. * Gets the radius of the physics imposter
  95390. * @returns Radius of the physics imposter
  95391. */
  95392. PhysicsImpostor.prototype.getRadius = function () {
  95393. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  95394. };
  95395. /**
  95396. * Sync a bone with this impostor
  95397. * @param bone The bone to sync to the impostor.
  95398. * @param boneMesh The mesh that the bone is influencing.
  95399. * @param jointPivot The pivot of the joint / bone in local space.
  95400. * @param distToJoint Optional distance from the impostor to the joint.
  95401. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95402. */
  95403. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  95404. var tempVec = PhysicsImpostor._tmpVecs[0];
  95405. var mesh = this.object;
  95406. if (mesh.rotationQuaternion) {
  95407. if (adjustRotation) {
  95408. var tempQuat = PhysicsImpostor._tmpQuat;
  95409. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  95410. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  95411. }
  95412. else {
  95413. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  95414. }
  95415. }
  95416. tempVec.x = 0;
  95417. tempVec.y = 0;
  95418. tempVec.z = 0;
  95419. if (jointPivot) {
  95420. tempVec.x = jointPivot.x;
  95421. tempVec.y = jointPivot.y;
  95422. tempVec.z = jointPivot.z;
  95423. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  95424. if (distToJoint === undefined || distToJoint === null) {
  95425. distToJoint = jointPivot.length();
  95426. }
  95427. tempVec.x *= distToJoint;
  95428. tempVec.y *= distToJoint;
  95429. tempVec.z *= distToJoint;
  95430. }
  95431. if (bone.getParent()) {
  95432. tempVec.addInPlace(mesh.getAbsolutePosition());
  95433. bone.setAbsolutePosition(tempVec, boneMesh);
  95434. }
  95435. else {
  95436. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  95437. boneMesh.position.x -= tempVec.x;
  95438. boneMesh.position.y -= tempVec.y;
  95439. boneMesh.position.z -= tempVec.z;
  95440. }
  95441. };
  95442. /**
  95443. * Sync impostor to a bone
  95444. * @param bone The bone that the impostor will be synced to.
  95445. * @param boneMesh The mesh that the bone is influencing.
  95446. * @param jointPivot The pivot of the joint / bone in local space.
  95447. * @param distToJoint Optional distance from the impostor to the joint.
  95448. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95449. * @param boneAxis Optional vector3 axis the bone is aligned with
  95450. */
  95451. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  95452. var mesh = this.object;
  95453. if (mesh.rotationQuaternion) {
  95454. if (adjustRotation) {
  95455. var tempQuat = PhysicsImpostor._tmpQuat;
  95456. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  95457. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  95458. }
  95459. else {
  95460. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  95461. }
  95462. }
  95463. var pos = PhysicsImpostor._tmpVecs[0];
  95464. var boneDir = PhysicsImpostor._tmpVecs[1];
  95465. if (!boneAxis) {
  95466. boneAxis = PhysicsImpostor._tmpVecs[2];
  95467. boneAxis.x = 0;
  95468. boneAxis.y = 1;
  95469. boneAxis.z = 0;
  95470. }
  95471. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  95472. bone.getAbsolutePositionToRef(boneMesh, pos);
  95473. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  95474. distToJoint = jointPivot.length();
  95475. }
  95476. if (distToJoint !== undefined && distToJoint !== null) {
  95477. pos.x += boneDir.x * distToJoint;
  95478. pos.y += boneDir.y * distToJoint;
  95479. pos.z += boneDir.z * distToJoint;
  95480. }
  95481. mesh.setAbsolutePosition(pos);
  95482. };
  95483. /**
  95484. * The default object size of the imposter
  95485. */
  95486. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  95487. /**
  95488. * The identity quaternion of the imposter
  95489. */
  95490. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  95491. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  95492. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  95493. //Impostor types
  95494. /**
  95495. * No-Imposter type
  95496. */
  95497. PhysicsImpostor.NoImpostor = 0;
  95498. /**
  95499. * Sphere-Imposter type
  95500. */
  95501. PhysicsImpostor.SphereImpostor = 1;
  95502. /**
  95503. * Box-Imposter type
  95504. */
  95505. PhysicsImpostor.BoxImpostor = 2;
  95506. /**
  95507. * Plane-Imposter type
  95508. */
  95509. PhysicsImpostor.PlaneImpostor = 3;
  95510. /**
  95511. * Mesh-imposter type
  95512. */
  95513. PhysicsImpostor.MeshImpostor = 4;
  95514. /**
  95515. * Cylinder-Imposter type
  95516. */
  95517. PhysicsImpostor.CylinderImpostor = 7;
  95518. /**
  95519. * Particle-Imposter type
  95520. */
  95521. PhysicsImpostor.ParticleImpostor = 8;
  95522. /**
  95523. * Heightmap-Imposter type
  95524. */
  95525. PhysicsImpostor.HeightmapImpostor = 9;
  95526. return PhysicsImpostor;
  95527. }());
  95528. BABYLON.PhysicsImpostor = PhysicsImpostor;
  95529. })(BABYLON || (BABYLON = {}));
  95530. //# sourceMappingURL=babylon.physicsImpostor.js.map
  95531. var BABYLON;
  95532. (function (BABYLON) {
  95533. /**
  95534. * Class used to control physics engine
  95535. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95536. */
  95537. var PhysicsEngine = /** @class */ (function () {
  95538. /**
  95539. * Creates a new Physics Engine
  95540. * @param gravity defines the gravity vector used by the simulation
  95541. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  95542. */
  95543. function PhysicsEngine(gravity, _physicsPlugin) {
  95544. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  95545. this._physicsPlugin = _physicsPlugin;
  95546. this._impostors = [];
  95547. this._joints = [];
  95548. if (!this._physicsPlugin.isSupported()) {
  95549. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  95550. + "Please make sure it is included.");
  95551. }
  95552. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  95553. this.setGravity(gravity);
  95554. this.setTimeStep();
  95555. }
  95556. /**
  95557. * Sets the gravity vector used by the simulation
  95558. * @param gravity defines the gravity vector to use
  95559. */
  95560. PhysicsEngine.prototype.setGravity = function (gravity) {
  95561. this.gravity = gravity;
  95562. this._physicsPlugin.setGravity(this.gravity);
  95563. };
  95564. /**
  95565. * Set the time step of the physics engine.
  95566. * Default is 1/60.
  95567. * To slow it down, enter 1/600 for example.
  95568. * To speed it up, 1/30
  95569. * @param newTimeStep defines the new timestep to apply to this world.
  95570. */
  95571. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  95572. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  95573. this._physicsPlugin.setTimeStep(newTimeStep);
  95574. };
  95575. /**
  95576. * Get the time step of the physics engine.
  95577. * @returns the current time step
  95578. */
  95579. PhysicsEngine.prototype.getTimeStep = function () {
  95580. return this._physicsPlugin.getTimeStep();
  95581. };
  95582. /**
  95583. * Release all resources
  95584. */
  95585. PhysicsEngine.prototype.dispose = function () {
  95586. this._impostors.forEach(function (impostor) {
  95587. impostor.dispose();
  95588. });
  95589. this._physicsPlugin.dispose();
  95590. };
  95591. /**
  95592. * Gets the name of the current physics plugin
  95593. * @returns the name of the plugin
  95594. */
  95595. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  95596. return this._physicsPlugin.name;
  95597. };
  95598. /**
  95599. * Adding a new impostor for the impostor tracking.
  95600. * This will be done by the impostor itself.
  95601. * @param impostor the impostor to add
  95602. */
  95603. PhysicsEngine.prototype.addImpostor = function (impostor) {
  95604. impostor.uniqueId = this._impostors.push(impostor);
  95605. //if no parent, generate the body
  95606. if (!impostor.parent) {
  95607. this._physicsPlugin.generatePhysicsBody(impostor);
  95608. }
  95609. };
  95610. /**
  95611. * Remove an impostor from the engine.
  95612. * This impostor and its mesh will not longer be updated by the physics engine.
  95613. * @param impostor the impostor to remove
  95614. */
  95615. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  95616. var index = this._impostors.indexOf(impostor);
  95617. if (index > -1) {
  95618. var removed = this._impostors.splice(index, 1);
  95619. //Is it needed?
  95620. if (removed.length) {
  95621. //this will also remove it from the world.
  95622. removed[0].physicsBody = null;
  95623. }
  95624. }
  95625. };
  95626. /**
  95627. * Add a joint to the physics engine
  95628. * @param mainImpostor defines the main impostor to which the joint is added.
  95629. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  95630. * @param joint defines the joint that will connect both impostors.
  95631. */
  95632. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  95633. var impostorJoint = {
  95634. mainImpostor: mainImpostor,
  95635. connectedImpostor: connectedImpostor,
  95636. joint: joint
  95637. };
  95638. joint.physicsPlugin = this._physicsPlugin;
  95639. this._joints.push(impostorJoint);
  95640. this._physicsPlugin.generateJoint(impostorJoint);
  95641. };
  95642. /**
  95643. * Removes a joint from the simulation
  95644. * @param mainImpostor defines the impostor used with the joint
  95645. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  95646. * @param joint defines the joint to remove
  95647. */
  95648. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  95649. var matchingJoints = this._joints.filter(function (impostorJoint) {
  95650. return (impostorJoint.connectedImpostor === connectedImpostor
  95651. && impostorJoint.joint === joint
  95652. && impostorJoint.mainImpostor === mainImpostor);
  95653. });
  95654. if (matchingJoints.length) {
  95655. this._physicsPlugin.removeJoint(matchingJoints[0]);
  95656. //TODO remove it from the list as well
  95657. }
  95658. };
  95659. /**
  95660. * Called by the scene. No need to call it.
  95661. * @param delta defines the timespam between frames
  95662. */
  95663. PhysicsEngine.prototype._step = function (delta) {
  95664. var _this = this;
  95665. //check if any mesh has no body / requires an update
  95666. this._impostors.forEach(function (impostor) {
  95667. if (impostor.isBodyInitRequired()) {
  95668. _this._physicsPlugin.generatePhysicsBody(impostor);
  95669. }
  95670. });
  95671. if (delta > 0.1) {
  95672. delta = 0.1;
  95673. }
  95674. else if (delta <= 0) {
  95675. delta = 1.0 / 60.0;
  95676. }
  95677. this._physicsPlugin.executeStep(delta, this._impostors);
  95678. };
  95679. /**
  95680. * Gets the current plugin used to run the simulation
  95681. * @returns current plugin
  95682. */
  95683. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  95684. return this._physicsPlugin;
  95685. };
  95686. /**
  95687. * Gets the list of physic impostors
  95688. * @returns an array of PhysicsImpostor
  95689. */
  95690. PhysicsEngine.prototype.getImpostors = function () {
  95691. return this._impostors;
  95692. };
  95693. /**
  95694. * Gets the impostor for a physics enabled object
  95695. * @param object defines the object impersonated by the impostor
  95696. * @returns the PhysicsImpostor or null if not found
  95697. */
  95698. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  95699. for (var i = 0; i < this._impostors.length; ++i) {
  95700. if (this._impostors[i].object === object) {
  95701. return this._impostors[i];
  95702. }
  95703. }
  95704. return null;
  95705. };
  95706. /**
  95707. * Gets the impostor for a physics body object
  95708. * @param body defines physics body used by the impostor
  95709. * @returns the PhysicsImpostor or null if not found
  95710. */
  95711. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  95712. for (var i = 0; i < this._impostors.length; ++i) {
  95713. if (this._impostors[i].physicsBody === body) {
  95714. return this._impostors[i];
  95715. }
  95716. }
  95717. return null;
  95718. };
  95719. /**
  95720. * Global value used to control the smallest number supported by the simulation
  95721. */
  95722. PhysicsEngine.Epsilon = 0.001;
  95723. return PhysicsEngine;
  95724. }());
  95725. BABYLON.PhysicsEngine = PhysicsEngine;
  95726. })(BABYLON || (BABYLON = {}));
  95727. //# sourceMappingURL=babylon.physicsEngine.js.map
  95728. var BABYLON;
  95729. (function (BABYLON) {
  95730. /**
  95731. * A helper for physics simulations
  95732. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95733. */
  95734. var PhysicsHelper = /** @class */ (function () {
  95735. /**
  95736. * Initializes the Physics helper
  95737. * @param scene Babylon.js scene
  95738. */
  95739. function PhysicsHelper(scene) {
  95740. this._scene = scene;
  95741. this._physicsEngine = this._scene.getPhysicsEngine();
  95742. if (!this._physicsEngine) {
  95743. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  95744. }
  95745. }
  95746. /**
  95747. * Applies a radial explosion impulse
  95748. * @param origin the origin of the explosion
  95749. * @param radius the explosion radius
  95750. * @param strength the explosion strength
  95751. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95752. * @returns A physics radial explosion event, or null
  95753. */
  95754. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  95755. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95756. if (!this._physicsEngine) {
  95757. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  95758. return null;
  95759. }
  95760. var impostors = this._physicsEngine.getImpostors();
  95761. if (impostors.length === 0) {
  95762. return null;
  95763. }
  95764. var event = new PhysicsRadialExplosionEvent(this._scene);
  95765. impostors.forEach(function (impostor) {
  95766. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95767. if (!impostorForceAndContactPoint) {
  95768. return;
  95769. }
  95770. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95771. });
  95772. event.dispose(false);
  95773. return event;
  95774. };
  95775. /**
  95776. * Applies a radial explosion force
  95777. * @param origin the origin of the explosion
  95778. * @param radius the explosion radius
  95779. * @param strength the explosion strength
  95780. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95781. * @returns A physics radial explosion event, or null
  95782. */
  95783. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  95784. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95785. if (!this._physicsEngine) {
  95786. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95787. return null;
  95788. }
  95789. var impostors = this._physicsEngine.getImpostors();
  95790. if (impostors.length === 0) {
  95791. return null;
  95792. }
  95793. var event = new PhysicsRadialExplosionEvent(this._scene);
  95794. impostors.forEach(function (impostor) {
  95795. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95796. if (!impostorForceAndContactPoint) {
  95797. return;
  95798. }
  95799. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95800. });
  95801. event.dispose(false);
  95802. return event;
  95803. };
  95804. /**
  95805. * Creates a gravitational field
  95806. * @param origin the origin of the explosion
  95807. * @param radius the explosion radius
  95808. * @param strength the explosion strength
  95809. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95810. * @returns A physics gravitational field event, or null
  95811. */
  95812. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  95813. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95814. if (!this._physicsEngine) {
  95815. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95816. return null;
  95817. }
  95818. var impostors = this._physicsEngine.getImpostors();
  95819. if (impostors.length === 0) {
  95820. return null;
  95821. }
  95822. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  95823. event.dispose(false);
  95824. return event;
  95825. };
  95826. /**
  95827. * Creates a physics updraft event
  95828. * @param origin the origin of the updraft
  95829. * @param radius the radius of the updraft
  95830. * @param strength the strength of the updraft
  95831. * @param height the height of the updraft
  95832. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  95833. * @returns A physics updraft event, or null
  95834. */
  95835. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  95836. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  95837. if (!this._physicsEngine) {
  95838. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95839. return null;
  95840. }
  95841. if (this._physicsEngine.getImpostors().length === 0) {
  95842. return null;
  95843. }
  95844. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  95845. event.dispose(false);
  95846. return event;
  95847. };
  95848. /**
  95849. * Creates a physics vortex event
  95850. * @param origin the of the vortex
  95851. * @param radius the radius of the vortex
  95852. * @param strength the strength of the vortex
  95853. * @param height the height of the vortex
  95854. * @returns a Physics vortex event, or null
  95855. * A physics vortex event or null
  95856. */
  95857. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  95858. if (!this._physicsEngine) {
  95859. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95860. return null;
  95861. }
  95862. if (this._physicsEngine.getImpostors().length === 0) {
  95863. return null;
  95864. }
  95865. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  95866. event.dispose(false);
  95867. return event;
  95868. };
  95869. return PhysicsHelper;
  95870. }());
  95871. BABYLON.PhysicsHelper = PhysicsHelper;
  95872. /**
  95873. * Represents a physics radial explosion event
  95874. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95875. */
  95876. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  95877. /**
  95878. * Initializes a radial explosioin event
  95879. * @param scene BabylonJS scene
  95880. */
  95881. function PhysicsRadialExplosionEvent(scene) {
  95882. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  95883. this._rays = [];
  95884. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  95885. this._scene = scene;
  95886. }
  95887. /**
  95888. * Returns the data related to the radial explosion event (sphere & rays).
  95889. * @returns The radial explosion event data
  95890. */
  95891. PhysicsRadialExplosionEvent.prototype.getData = function () {
  95892. this._dataFetched = true;
  95893. return {
  95894. sphere: this._sphere,
  95895. rays: this._rays,
  95896. };
  95897. };
  95898. /**
  95899. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  95900. * @param impostor A physics imposter
  95901. * @param origin the origin of the explosion
  95902. * @param radius the explosion radius
  95903. * @param strength the explosion strength
  95904. * @param falloff possible options: Constant & Linear
  95905. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  95906. */
  95907. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  95908. if (impostor.mass === 0) {
  95909. return null;
  95910. }
  95911. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  95912. return null;
  95913. }
  95914. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95915. return null;
  95916. }
  95917. var impostorObjectCenter = impostor.getObjectCenter();
  95918. var direction = impostorObjectCenter.subtract(origin);
  95919. var ray = new BABYLON.Ray(origin, direction, radius);
  95920. this._rays.push(ray);
  95921. var hit = ray.intersectsMesh(impostor.object);
  95922. var contactPoint = hit.pickedPoint;
  95923. if (!contactPoint) {
  95924. return null;
  95925. }
  95926. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  95927. if (distanceFromOrigin > radius) {
  95928. return null;
  95929. }
  95930. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  95931. ? strength
  95932. : strength * (1 - (distanceFromOrigin / radius));
  95933. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95934. return { force: force, contactPoint: contactPoint };
  95935. };
  95936. /**
  95937. * Disposes the sphere.
  95938. * @param force Specifies if the sphere should be disposed by force
  95939. */
  95940. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  95941. var _this = this;
  95942. if (force === void 0) { force = true; }
  95943. if (force) {
  95944. this._sphere.dispose();
  95945. }
  95946. else {
  95947. setTimeout(function () {
  95948. if (!_this._dataFetched) {
  95949. _this._sphere.dispose();
  95950. }
  95951. }, 0);
  95952. }
  95953. };
  95954. /*** Helpers ***/
  95955. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  95956. if (!this._sphere) {
  95957. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  95958. this._sphere.isVisible = false;
  95959. }
  95960. };
  95961. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  95962. var impostorObject = impostor.object;
  95963. this._prepareSphere();
  95964. this._sphere.position = origin;
  95965. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  95966. this._sphere._updateBoundingInfo();
  95967. this._sphere.computeWorldMatrix(true);
  95968. return this._sphere.intersectsMesh(impostorObject, true);
  95969. };
  95970. return PhysicsRadialExplosionEvent;
  95971. }());
  95972. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  95973. /**
  95974. * Represents a gravitational field event
  95975. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95976. */
  95977. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  95978. /**
  95979. * Initializes the physics gravitational field event
  95980. * @param physicsHelper A physics helper
  95981. * @param scene BabylonJS scene
  95982. * @param origin The origin position of the gravitational field event
  95983. * @param radius The radius of the gravitational field event
  95984. * @param strength The strength of the gravitational field event
  95985. * @param falloff The falloff for the gravitational field event
  95986. */
  95987. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  95988. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95989. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95990. this._physicsHelper = physicsHelper;
  95991. this._scene = scene;
  95992. this._origin = origin;
  95993. this._radius = radius;
  95994. this._strength = strength;
  95995. this._falloff = falloff;
  95996. this._tickCallback = this._tick.bind(this);
  95997. }
  95998. /**
  95999. * Returns the data related to the gravitational field event (sphere).
  96000. * @returns A gravitational field event
  96001. */
  96002. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  96003. this._dataFetched = true;
  96004. return {
  96005. sphere: this._sphere,
  96006. };
  96007. };
  96008. /**
  96009. * Enables the gravitational field.
  96010. */
  96011. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  96012. this._tickCallback.call(this);
  96013. this._scene.registerBeforeRender(this._tickCallback);
  96014. };
  96015. /**
  96016. * Disables the gravitational field.
  96017. */
  96018. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  96019. this._scene.unregisterBeforeRender(this._tickCallback);
  96020. };
  96021. /**
  96022. * Disposes the sphere.
  96023. * @param force The force to dispose from the gravitational field event
  96024. */
  96025. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  96026. var _this = this;
  96027. if (force === void 0) { force = true; }
  96028. if (force) {
  96029. this._sphere.dispose();
  96030. }
  96031. else {
  96032. setTimeout(function () {
  96033. if (!_this._dataFetched) {
  96034. _this._sphere.dispose();
  96035. }
  96036. }, 0);
  96037. }
  96038. };
  96039. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  96040. // Since the params won't change, we fetch the event only once
  96041. if (this._sphere) {
  96042. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  96043. }
  96044. else {
  96045. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  96046. if (radialExplosionEvent) {
  96047. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  96048. }
  96049. }
  96050. };
  96051. return PhysicsGravitationalFieldEvent;
  96052. }());
  96053. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  96054. /**
  96055. * Represents a physics updraft event
  96056. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96057. */
  96058. var PhysicsUpdraftEvent = /** @class */ (function () {
  96059. /**
  96060. * Initializes the physics updraft event
  96061. * @param _scene BabylonJS scene
  96062. * @param _origin The origin position of the updraft
  96063. * @param _radius The radius of the updraft
  96064. * @param _strength The strength of the updraft
  96065. * @param _height The height of the updraft
  96066. * @param _updraftMode The mode of the updraft
  96067. */
  96068. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  96069. this._scene = _scene;
  96070. this._origin = _origin;
  96071. this._radius = _radius;
  96072. this._strength = _strength;
  96073. this._height = _height;
  96074. this._updraftMode = _updraftMode;
  96075. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  96076. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  96077. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  96078. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96079. this._physicsEngine = this._scene.getPhysicsEngine();
  96080. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  96081. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  96082. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  96083. this._originDirection = this._origin.subtract(this._originTop).normalize();
  96084. }
  96085. this._tickCallback = this._tick.bind(this);
  96086. }
  96087. /**
  96088. * Returns the data related to the updraft event (cylinder).
  96089. * @returns A physics updraft event
  96090. */
  96091. PhysicsUpdraftEvent.prototype.getData = function () {
  96092. this._dataFetched = true;
  96093. return {
  96094. cylinder: this._cylinder,
  96095. };
  96096. };
  96097. /**
  96098. * Enables the updraft.
  96099. */
  96100. PhysicsUpdraftEvent.prototype.enable = function () {
  96101. this._tickCallback.call(this);
  96102. this._scene.registerBeforeRender(this._tickCallback);
  96103. };
  96104. /**
  96105. * Disables the cortex.
  96106. */
  96107. PhysicsUpdraftEvent.prototype.disable = function () {
  96108. this._scene.unregisterBeforeRender(this._tickCallback);
  96109. };
  96110. /**
  96111. * Disposes the sphere.
  96112. * @param force Specifies if the updraft should be disposed by force
  96113. */
  96114. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  96115. var _this = this;
  96116. if (force === void 0) { force = true; }
  96117. if (force) {
  96118. this._cylinder.dispose();
  96119. }
  96120. else {
  96121. setTimeout(function () {
  96122. if (!_this._dataFetched) {
  96123. _this._cylinder.dispose();
  96124. }
  96125. }, 0);
  96126. }
  96127. };
  96128. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  96129. if (impostor.mass === 0) {
  96130. return null;
  96131. }
  96132. if (!this._intersectsWithCylinder(impostor)) {
  96133. return null;
  96134. }
  96135. var impostorObjectCenter = impostor.getObjectCenter();
  96136. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  96137. var direction = this._originDirection;
  96138. }
  96139. else {
  96140. var direction = impostorObjectCenter.subtract(this._originTop);
  96141. }
  96142. var multiplier = this._strength * -1;
  96143. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  96144. return { force: force, contactPoint: impostorObjectCenter };
  96145. };
  96146. PhysicsUpdraftEvent.prototype._tick = function () {
  96147. var _this = this;
  96148. this._physicsEngine.getImpostors().forEach(function (impostor) {
  96149. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  96150. if (!impostorForceAndContactPoint) {
  96151. return;
  96152. }
  96153. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96154. });
  96155. };
  96156. /*** Helpers ***/
  96157. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  96158. if (!this._cylinder) {
  96159. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  96160. height: this._height,
  96161. diameter: this._radius * 2,
  96162. }, this._scene);
  96163. this._cylinder.isVisible = false;
  96164. }
  96165. };
  96166. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  96167. var impostorObject = impostor.object;
  96168. this._prepareCylinder();
  96169. this._cylinder.position = this._cylinderPosition;
  96170. return this._cylinder.intersectsMesh(impostorObject, true);
  96171. };
  96172. return PhysicsUpdraftEvent;
  96173. }());
  96174. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  96175. /**
  96176. * Represents a physics vortex event
  96177. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96178. */
  96179. var PhysicsVortexEvent = /** @class */ (function () {
  96180. /**
  96181. * Initializes the physics vortex event
  96182. * @param _scene The BabylonJS scene
  96183. * @param _origin The origin position of the vortex
  96184. * @param _radius The radius of the vortex
  96185. * @param _strength The strength of the vortex
  96186. * @param _height The height of the vortex
  96187. */
  96188. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  96189. this._scene = _scene;
  96190. this._origin = _origin;
  96191. this._radius = _radius;
  96192. this._strength = _strength;
  96193. this._height = _height;
  96194. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  96195. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  96196. this._updraftMultiplier = 0.02;
  96197. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  96198. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  96199. this._physicsEngine = this._scene.getPhysicsEngine();
  96200. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  96201. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  96202. this._tickCallback = this._tick.bind(this);
  96203. }
  96204. /**
  96205. * Returns the data related to the vortex event (cylinder).
  96206. * @returns The physics vortex event data
  96207. */
  96208. PhysicsVortexEvent.prototype.getData = function () {
  96209. this._dataFetched = true;
  96210. return {
  96211. cylinder: this._cylinder,
  96212. };
  96213. };
  96214. /**
  96215. * Enables the vortex.
  96216. */
  96217. PhysicsVortexEvent.prototype.enable = function () {
  96218. this._tickCallback.call(this);
  96219. this._scene.registerBeforeRender(this._tickCallback);
  96220. };
  96221. /**
  96222. * Disables the cortex.
  96223. */
  96224. PhysicsVortexEvent.prototype.disable = function () {
  96225. this._scene.unregisterBeforeRender(this._tickCallback);
  96226. };
  96227. /**
  96228. * Disposes the sphere.
  96229. * @param force
  96230. */
  96231. PhysicsVortexEvent.prototype.dispose = function (force) {
  96232. var _this = this;
  96233. if (force === void 0) { force = true; }
  96234. if (force) {
  96235. this._cylinder.dispose();
  96236. }
  96237. else {
  96238. setTimeout(function () {
  96239. if (!_this._dataFetched) {
  96240. _this._cylinder.dispose();
  96241. }
  96242. }, 0);
  96243. }
  96244. };
  96245. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  96246. if (impostor.mass === 0) {
  96247. return null;
  96248. }
  96249. if (!this._intersectsWithCylinder(impostor)) {
  96250. return null;
  96251. }
  96252. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  96253. return null;
  96254. }
  96255. var impostorObjectCenter = impostor.getObjectCenter();
  96256. 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)
  96257. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  96258. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  96259. var hit = ray.intersectsMesh(impostor.object);
  96260. var contactPoint = hit.pickedPoint;
  96261. if (!contactPoint) {
  96262. return null;
  96263. }
  96264. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  96265. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  96266. var directionToOrigin = contactPoint.normalize();
  96267. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  96268. directionToOrigin = directionToOrigin.negate();
  96269. }
  96270. // TODO: find a more physically based solution
  96271. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  96272. var forceX = directionToOrigin.x * this._strength / 8;
  96273. var forceY = directionToOrigin.y * this._updraftMultiplier;
  96274. var forceZ = directionToOrigin.z * this._strength / 8;
  96275. }
  96276. else {
  96277. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  96278. var forceY = this._originTop.y * this._updraftMultiplier;
  96279. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  96280. }
  96281. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  96282. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  96283. return { force: force, contactPoint: impostorObjectCenter };
  96284. };
  96285. PhysicsVortexEvent.prototype._tick = function () {
  96286. var _this = this;
  96287. this._physicsEngine.getImpostors().forEach(function (impostor) {
  96288. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  96289. if (!impostorForceAndContactPoint) {
  96290. return;
  96291. }
  96292. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96293. });
  96294. };
  96295. /*** Helpers ***/
  96296. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  96297. if (!this._cylinder) {
  96298. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  96299. height: this._height,
  96300. diameter: this._radius * 2,
  96301. }, this._scene);
  96302. this._cylinder.isVisible = false;
  96303. }
  96304. };
  96305. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  96306. var impostorObject = impostor.object;
  96307. this._prepareCylinder();
  96308. this._cylinder.position = this._cylinderPosition;
  96309. return this._cylinder.intersectsMesh(impostorObject, true);
  96310. };
  96311. return PhysicsVortexEvent;
  96312. }());
  96313. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  96314. /**
  96315. * The strenght of the force in correspondence to the distance of the affected object
  96316. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96317. */
  96318. var PhysicsRadialImpulseFalloff;
  96319. (function (PhysicsRadialImpulseFalloff) {
  96320. /** Defines that impulse is constant in strength across it's whole radius */
  96321. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  96322. /** DEfines that impulse gets weaker if it's further from the origin */
  96323. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  96324. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  96325. /**
  96326. * The strength of the force in correspondence to the distance of the affected object
  96327. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96328. */
  96329. var PhysicsUpdraftMode;
  96330. (function (PhysicsUpdraftMode) {
  96331. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  96332. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  96333. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  96334. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  96335. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  96336. })(BABYLON || (BABYLON = {}));
  96337. //# sourceMappingURL=babylon.physicsHelper.js.map
  96338. var BABYLON;
  96339. (function (BABYLON) {
  96340. /** @hidden */
  96341. var CannonJSPlugin = /** @class */ (function () {
  96342. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  96343. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  96344. if (iterations === void 0) { iterations = 10; }
  96345. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  96346. this.name = "CannonJSPlugin";
  96347. this._physicsMaterials = new Array();
  96348. this._fixedTimeStep = 1 / 60;
  96349. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  96350. this.BJSCANNON = CANNON;
  96351. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  96352. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  96353. this._tmpPosition = BABYLON.Vector3.Zero();
  96354. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  96355. this._tmpUnityRotation = new BABYLON.Quaternion();
  96356. if (!this.isSupported()) {
  96357. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  96358. return;
  96359. }
  96360. this._extendNamespace();
  96361. this.world = new this.BJSCANNON.World();
  96362. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  96363. this.world.solver.iterations = iterations;
  96364. }
  96365. CannonJSPlugin.prototype.setGravity = function (gravity) {
  96366. this.world.gravity.copy(gravity);
  96367. };
  96368. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  96369. this._fixedTimeStep = timeStep;
  96370. };
  96371. CannonJSPlugin.prototype.getTimeStep = function () {
  96372. return this._fixedTimeStep;
  96373. };
  96374. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  96375. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  96376. };
  96377. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96378. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96379. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96380. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  96381. };
  96382. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96383. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96384. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96385. impostor.physicsBody.applyForce(impulse, worldPoint);
  96386. };
  96387. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96388. //parent-child relationship. Does this impostor has a parent impostor?
  96389. if (impostor.parent) {
  96390. if (impostor.physicsBody) {
  96391. this.removePhysicsBody(impostor);
  96392. //TODO is that needed?
  96393. impostor.forceUpdate();
  96394. }
  96395. return;
  96396. }
  96397. //should a new body be created for this impostor?
  96398. if (impostor.isBodyInitRequired()) {
  96399. var shape = this._createShape(impostor);
  96400. //unregister events, if body is being changed
  96401. var oldBody = impostor.physicsBody;
  96402. if (oldBody) {
  96403. this.removePhysicsBody(impostor);
  96404. }
  96405. //create the body and material
  96406. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  96407. var bodyCreationObject = {
  96408. mass: impostor.getParam("mass"),
  96409. material: material
  96410. };
  96411. // A simple extend, in case native options were used.
  96412. var nativeOptions = impostor.getParam("nativeOptions");
  96413. for (var key in nativeOptions) {
  96414. if (nativeOptions.hasOwnProperty(key)) {
  96415. bodyCreationObject[key] = nativeOptions[key];
  96416. }
  96417. }
  96418. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  96419. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  96420. this.world.addEventListener("preStep", impostor.beforeStep);
  96421. this.world.addEventListener("postStep", impostor.afterStep);
  96422. impostor.physicsBody.addShape(shape);
  96423. this.world.add(impostor.physicsBody);
  96424. //try to keep the body moving in the right direction by taking old properties.
  96425. //Should be tested!
  96426. if (oldBody) {
  96427. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  96428. impostor.physicsBody[param].copy(oldBody[param]);
  96429. });
  96430. }
  96431. this._processChildMeshes(impostor);
  96432. }
  96433. //now update the body's transformation
  96434. this._updatePhysicsBodyTransformation(impostor);
  96435. };
  96436. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  96437. var _this = this;
  96438. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  96439. var currentRotation = mainImpostor.object.rotationQuaternion;
  96440. if (meshChildren.length) {
  96441. var processMesh = function (localPosition, mesh) {
  96442. if (!currentRotation || !mesh.rotationQuaternion) {
  96443. return;
  96444. }
  96445. var childImpostor = mesh.getPhysicsImpostor();
  96446. if (childImpostor) {
  96447. var parent = childImpostor.parent;
  96448. if (parent !== mainImpostor) {
  96449. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  96450. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  96451. if (childImpostor.physicsBody) {
  96452. _this.removePhysicsBody(childImpostor);
  96453. childImpostor.physicsBody = null;
  96454. }
  96455. childImpostor.parent = mainImpostor;
  96456. childImpostor.resetUpdateFlags();
  96457. 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));
  96458. //Add the mass of the children.
  96459. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  96460. }
  96461. }
  96462. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  96463. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  96464. };
  96465. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  96466. }
  96467. };
  96468. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96469. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  96470. this.world.removeEventListener("preStep", impostor.beforeStep);
  96471. this.world.removeEventListener("postStep", impostor.afterStep);
  96472. this.world.remove(impostor.physicsBody);
  96473. };
  96474. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96475. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96476. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96477. if (!mainBody || !connectedBody) {
  96478. return;
  96479. }
  96480. var constraint;
  96481. var jointData = impostorJoint.joint.jointData;
  96482. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  96483. var constraintData = {
  96484. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  96485. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  96486. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  96487. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  96488. maxForce: jointData.nativeParams.maxForce,
  96489. collideConnected: !!jointData.collision
  96490. };
  96491. switch (impostorJoint.joint.type) {
  96492. case BABYLON.PhysicsJoint.HingeJoint:
  96493. case BABYLON.PhysicsJoint.Hinge2Joint:
  96494. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  96495. break;
  96496. case BABYLON.PhysicsJoint.DistanceJoint:
  96497. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  96498. break;
  96499. case BABYLON.PhysicsJoint.SpringJoint:
  96500. var springData = jointData;
  96501. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  96502. restLength: springData.length,
  96503. stiffness: springData.stiffness,
  96504. damping: springData.damping,
  96505. localAnchorA: constraintData.pivotA,
  96506. localAnchorB: constraintData.pivotB
  96507. });
  96508. break;
  96509. case BABYLON.PhysicsJoint.LockJoint:
  96510. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  96511. break;
  96512. case BABYLON.PhysicsJoint.PointToPointJoint:
  96513. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96514. default:
  96515. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  96516. break;
  96517. }
  96518. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  96519. constraint.collideConnected = !!jointData.collision;
  96520. impostorJoint.joint.physicsJoint = constraint;
  96521. //don't add spring as constraint, as it is not one.
  96522. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96523. this.world.addConstraint(constraint);
  96524. }
  96525. else {
  96526. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  96527. constraint.applyForce();
  96528. };
  96529. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96530. }
  96531. };
  96532. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96533. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96534. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  96535. }
  96536. else {
  96537. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96538. }
  96539. };
  96540. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  96541. var index;
  96542. var mat;
  96543. for (index = 0; index < this._physicsMaterials.length; index++) {
  96544. mat = this._physicsMaterials[index];
  96545. if (mat.friction === friction && mat.restitution === restitution) {
  96546. return mat;
  96547. }
  96548. }
  96549. var currentMat = new this.BJSCANNON.Material(name);
  96550. currentMat.friction = friction;
  96551. currentMat.restitution = restitution;
  96552. this._physicsMaterials.push(currentMat);
  96553. return currentMat;
  96554. };
  96555. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  96556. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  96557. };
  96558. CannonJSPlugin.prototype._createShape = function (impostor) {
  96559. var object = impostor.object;
  96560. var returnValue;
  96561. var extendSize = impostor.getObjectExtendSize();
  96562. switch (impostor.type) {
  96563. case BABYLON.PhysicsImpostor.SphereImpostor:
  96564. var radiusX = extendSize.x;
  96565. var radiusY = extendSize.y;
  96566. var radiusZ = extendSize.z;
  96567. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  96568. break;
  96569. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  96570. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96571. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  96572. break;
  96573. case BABYLON.PhysicsImpostor.BoxImpostor:
  96574. var box = extendSize.scale(0.5);
  96575. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  96576. break;
  96577. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96578. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  96579. returnValue = new this.BJSCANNON.Plane();
  96580. break;
  96581. case BABYLON.PhysicsImpostor.MeshImpostor:
  96582. // should transform the vertex data to world coordinates!!
  96583. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  96584. var rawFaces = object.getIndices ? object.getIndices() : [];
  96585. if (!rawVerts) {
  96586. return;
  96587. }
  96588. // get only scale! so the object could transform correctly.
  96589. var oldPosition = object.position.clone();
  96590. var oldRotation = object.rotation && object.rotation.clone();
  96591. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  96592. object.position.copyFromFloats(0, 0, 0);
  96593. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96594. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96595. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96596. var transform = object.computeWorldMatrix(true);
  96597. // convert rawVerts to object space
  96598. var temp = new Array();
  96599. var index;
  96600. for (index = 0; index < rawVerts.length; index += 3) {
  96601. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  96602. }
  96603. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  96604. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  96605. //now set back the transformation!
  96606. object.position.copyFrom(oldPosition);
  96607. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  96608. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  96609. break;
  96610. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  96611. var oldPosition2 = object.position.clone();
  96612. var oldRotation2 = object.rotation && object.rotation.clone();
  96613. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  96614. object.position.copyFromFloats(0, 0, 0);
  96615. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96616. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96617. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96618. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  96619. returnValue = this._createHeightmap(object);
  96620. object.position.copyFrom(oldPosition2);
  96621. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  96622. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  96623. object.computeWorldMatrix(true);
  96624. break;
  96625. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96626. returnValue = new this.BJSCANNON.Particle();
  96627. break;
  96628. }
  96629. return returnValue;
  96630. };
  96631. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  96632. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  96633. var transform = object.computeWorldMatrix(true);
  96634. // convert rawVerts to object space
  96635. var temp = new Array();
  96636. var index;
  96637. for (index = 0; index < pos.length; index += 3) {
  96638. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  96639. }
  96640. pos = temp;
  96641. var matrix = new Array();
  96642. //For now pointDepth will not be used and will be automatically calculated.
  96643. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  96644. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  96645. var boundingInfo = object.getBoundingInfo();
  96646. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  96647. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  96648. var elementSize = dim * 2 / arraySize;
  96649. for (var i = 0; i < pos.length; i = i + 3) {
  96650. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  96651. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  96652. var y = -pos[i + 2] + minY;
  96653. if (!matrix[x]) {
  96654. matrix[x] = [];
  96655. }
  96656. if (!matrix[x][z]) {
  96657. matrix[x][z] = y;
  96658. }
  96659. matrix[x][z] = Math.max(y, matrix[x][z]);
  96660. }
  96661. for (var x = 0; x <= arraySize; ++x) {
  96662. if (!matrix[x]) {
  96663. var loc = 1;
  96664. while (!matrix[(x + loc) % arraySize]) {
  96665. loc++;
  96666. }
  96667. matrix[x] = matrix[(x + loc) % arraySize].slice();
  96668. //console.log("missing x", x);
  96669. }
  96670. for (var z = 0; z <= arraySize; ++z) {
  96671. if (!matrix[x][z]) {
  96672. var loc = 1;
  96673. var newValue;
  96674. while (newValue === undefined) {
  96675. newValue = matrix[x][(z + loc++) % arraySize];
  96676. }
  96677. matrix[x][z] = newValue;
  96678. }
  96679. }
  96680. }
  96681. var shape = new this.BJSCANNON.Heightfield(matrix, {
  96682. elementSize: elementSize
  96683. });
  96684. //For future reference, needed for body transformation
  96685. shape.minY = minY;
  96686. return shape;
  96687. };
  96688. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  96689. var object = impostor.object;
  96690. //make sure it is updated...
  96691. object.computeWorldMatrix && object.computeWorldMatrix(true);
  96692. // The delta between the mesh position and the mesh bounding box center
  96693. var bInfo = object.getBoundingInfo();
  96694. if (!bInfo) {
  96695. return;
  96696. }
  96697. var center = impostor.getObjectCenter();
  96698. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  96699. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  96700. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  96701. this._tmpPosition.copyFrom(center);
  96702. var quaternion = object.rotationQuaternion;
  96703. if (!quaternion) {
  96704. return;
  96705. }
  96706. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  96707. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  96708. //-90 DEG in X, precalculated
  96709. quaternion = quaternion.multiply(this._minus90X);
  96710. //Invert! (Precalculated, 90 deg in X)
  96711. //No need to clone. this will never change.
  96712. impostor.setDeltaRotation(this._plus90X);
  96713. }
  96714. //If it is a heightfield, if should be centered.
  96715. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  96716. var mesh = object;
  96717. var boundingInfo = mesh.getBoundingInfo();
  96718. //calculate the correct body position:
  96719. var rotationQuaternion = mesh.rotationQuaternion;
  96720. mesh.rotationQuaternion = this._tmpUnityRotation;
  96721. mesh.computeWorldMatrix(true);
  96722. //get original center with no rotation
  96723. var c = center.clone();
  96724. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  96725. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  96726. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  96727. mesh.setPreTransformMatrix(p);
  96728. mesh.computeWorldMatrix(true);
  96729. //calculate the translation
  96730. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  96731. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  96732. //add it inverted to the delta
  96733. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  96734. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  96735. //rotation is back
  96736. mesh.rotationQuaternion = rotationQuaternion;
  96737. mesh.setPreTransformMatrix(oldPivot);
  96738. mesh.computeWorldMatrix(true);
  96739. }
  96740. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  96741. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  96742. //this._tmpPosition.copyFrom(object.position);
  96743. }
  96744. impostor.setDeltaPosition(this._tmpDeltaPosition);
  96745. //Now update the impostor object
  96746. impostor.physicsBody.position.copy(this._tmpPosition);
  96747. impostor.physicsBody.quaternion.copy(quaternion);
  96748. };
  96749. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96750. impostor.object.position.copyFrom(impostor.physicsBody.position);
  96751. if (impostor.object.rotationQuaternion) {
  96752. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  96753. }
  96754. };
  96755. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96756. impostor.physicsBody.position.copy(newPosition);
  96757. impostor.physicsBody.quaternion.copy(newRotation);
  96758. };
  96759. CannonJSPlugin.prototype.isSupported = function () {
  96760. return this.BJSCANNON !== undefined;
  96761. };
  96762. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96763. impostor.physicsBody.velocity.copy(velocity);
  96764. };
  96765. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96766. impostor.physicsBody.angularVelocity.copy(velocity);
  96767. };
  96768. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96769. var v = impostor.physicsBody.velocity;
  96770. if (!v) {
  96771. return null;
  96772. }
  96773. return new BABYLON.Vector3(v.x, v.y, v.z);
  96774. };
  96775. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96776. var v = impostor.physicsBody.angularVelocity;
  96777. if (!v) {
  96778. return null;
  96779. }
  96780. return new BABYLON.Vector3(v.x, v.y, v.z);
  96781. };
  96782. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96783. impostor.physicsBody.mass = mass;
  96784. impostor.physicsBody.updateMassProperties();
  96785. };
  96786. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  96787. return impostor.physicsBody.mass;
  96788. };
  96789. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  96790. return impostor.physicsBody.material.friction;
  96791. };
  96792. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96793. impostor.physicsBody.material.friction = friction;
  96794. };
  96795. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96796. return impostor.physicsBody.material.restitution;
  96797. };
  96798. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96799. impostor.physicsBody.material.restitution = restitution;
  96800. };
  96801. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  96802. impostor.physicsBody.sleep();
  96803. };
  96804. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  96805. impostor.physicsBody.wakeUp();
  96806. };
  96807. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96808. joint.physicsJoint.distance = maxDistance;
  96809. };
  96810. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96811. // if (!motorIndex) {
  96812. // joint.physicsJoint.enableMotor();
  96813. // }
  96814. // }
  96815. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96816. // if (!motorIndex) {
  96817. // joint.physicsJoint.disableMotor();
  96818. // }
  96819. // }
  96820. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96821. if (!motorIndex) {
  96822. joint.physicsJoint.enableMotor();
  96823. joint.physicsJoint.setMotorSpeed(speed);
  96824. if (maxForce) {
  96825. this.setLimit(joint, maxForce);
  96826. }
  96827. }
  96828. };
  96829. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  96830. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  96831. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  96832. };
  96833. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96834. var body = impostor.physicsBody;
  96835. mesh.position.x = body.position.x;
  96836. mesh.position.y = body.position.y;
  96837. mesh.position.z = body.position.z;
  96838. if (mesh.rotationQuaternion) {
  96839. mesh.rotationQuaternion.x = body.quaternion.x;
  96840. mesh.rotationQuaternion.y = body.quaternion.y;
  96841. mesh.rotationQuaternion.z = body.quaternion.z;
  96842. mesh.rotationQuaternion.w = body.quaternion.w;
  96843. }
  96844. };
  96845. CannonJSPlugin.prototype.getRadius = function (impostor) {
  96846. var shape = impostor.physicsBody.shapes[0];
  96847. return shape.boundingSphereRadius;
  96848. };
  96849. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96850. var shape = impostor.physicsBody.shapes[0];
  96851. result.x = shape.halfExtents.x * 2;
  96852. result.y = shape.halfExtents.y * 2;
  96853. result.z = shape.halfExtents.z * 2;
  96854. };
  96855. CannonJSPlugin.prototype.dispose = function () {
  96856. };
  96857. CannonJSPlugin.prototype._extendNamespace = function () {
  96858. //this will force cannon to execute at least one step when using interpolation
  96859. var step_tmp1 = new this.BJSCANNON.Vec3();
  96860. var Engine = this.BJSCANNON;
  96861. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  96862. maxSubSteps = maxSubSteps || 10;
  96863. timeSinceLastCalled = timeSinceLastCalled || 0;
  96864. if (timeSinceLastCalled === 0) {
  96865. this.internalStep(dt);
  96866. this.time += dt;
  96867. }
  96868. else {
  96869. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  96870. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  96871. var t0 = performance.now();
  96872. for (var i = 0; i !== internalSteps; i++) {
  96873. this.internalStep(dt);
  96874. if (performance.now() - t0 > dt * 1000) {
  96875. break;
  96876. }
  96877. }
  96878. this.time += timeSinceLastCalled;
  96879. var h = this.time % dt;
  96880. var h_div_dt = h / dt;
  96881. var interpvelo = step_tmp1;
  96882. var bodies = this.bodies;
  96883. for (var j = 0; j !== bodies.length; j++) {
  96884. var b = bodies[j];
  96885. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  96886. b.position.vsub(b.previousPosition, interpvelo);
  96887. interpvelo.scale(h_div_dt, interpvelo);
  96888. b.position.vadd(interpvelo, b.interpolatedPosition);
  96889. }
  96890. else {
  96891. b.interpolatedPosition.copy(b.position);
  96892. b.interpolatedQuaternion.copy(b.quaternion);
  96893. }
  96894. }
  96895. }
  96896. };
  96897. };
  96898. return CannonJSPlugin;
  96899. }());
  96900. BABYLON.CannonJSPlugin = CannonJSPlugin;
  96901. })(BABYLON || (BABYLON = {}));
  96902. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  96903. var BABYLON;
  96904. (function (BABYLON) {
  96905. /** @hidden */
  96906. var OimoJSPlugin = /** @class */ (function () {
  96907. function OimoJSPlugin(iterations) {
  96908. this.name = "OimoJSPlugin";
  96909. this._tmpImpostorsArray = [];
  96910. this._tmpPositionVector = BABYLON.Vector3.Zero();
  96911. this.BJSOIMO = OIMO;
  96912. this.world = new this.BJSOIMO.World({
  96913. iterations: iterations
  96914. });
  96915. this.world.clear();
  96916. }
  96917. OimoJSPlugin.prototype.setGravity = function (gravity) {
  96918. this.world.gravity.copy(gravity);
  96919. };
  96920. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  96921. this.world.timeStep = timeStep;
  96922. };
  96923. OimoJSPlugin.prototype.getTimeStep = function () {
  96924. return this.world.timeStep;
  96925. };
  96926. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  96927. var _this = this;
  96928. impostors.forEach(function (impostor) {
  96929. impostor.beforeStep();
  96930. });
  96931. this.world.step();
  96932. impostors.forEach(function (impostor) {
  96933. impostor.afterStep();
  96934. //update the ordered impostors array
  96935. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  96936. });
  96937. //check for collisions
  96938. var contact = this.world.contacts;
  96939. while (contact !== null) {
  96940. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  96941. contact = contact.next;
  96942. continue;
  96943. }
  96944. //is this body colliding with any other? get the impostor
  96945. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  96946. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  96947. if (!mainImpostor || !collidingImpostor) {
  96948. contact = contact.next;
  96949. continue;
  96950. }
  96951. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  96952. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  96953. contact = contact.next;
  96954. }
  96955. };
  96956. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96957. var mass = impostor.physicsBody.mass;
  96958. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  96959. };
  96960. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96961. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  96962. this.applyImpulse(impostor, force, contactPoint);
  96963. };
  96964. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96965. var _this = this;
  96966. //parent-child relationship. Does this impostor has a parent impostor?
  96967. if (impostor.parent) {
  96968. if (impostor.physicsBody) {
  96969. this.removePhysicsBody(impostor);
  96970. //TODO is that needed?
  96971. impostor.forceUpdate();
  96972. }
  96973. return;
  96974. }
  96975. if (impostor.isBodyInitRequired()) {
  96976. var bodyConfig = {
  96977. name: impostor.uniqueId,
  96978. //Oimo must have mass, also for static objects.
  96979. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  96980. size: [],
  96981. type: [],
  96982. pos: [],
  96983. posShape: [],
  96984. rot: [],
  96985. rotShape: [],
  96986. move: impostor.getParam("mass") !== 0,
  96987. density: impostor.getParam("mass"),
  96988. friction: impostor.getParam("friction"),
  96989. restitution: impostor.getParam("restitution"),
  96990. //Supporting older versions of Oimo
  96991. world: this.world
  96992. };
  96993. var impostors = [impostor];
  96994. var addToArray = function (parent) {
  96995. if (!parent.getChildMeshes) {
  96996. return;
  96997. }
  96998. parent.getChildMeshes().forEach(function (m) {
  96999. if (m.physicsImpostor) {
  97000. impostors.push(m.physicsImpostor);
  97001. //m.physicsImpostor._init();
  97002. }
  97003. });
  97004. };
  97005. addToArray(impostor.object);
  97006. var checkWithEpsilon_1 = function (value) {
  97007. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  97008. };
  97009. var globalQuaternion_1 = new BABYLON.Quaternion();
  97010. impostors.forEach(function (i) {
  97011. if (!i.object.rotationQuaternion) {
  97012. return;
  97013. }
  97014. //get the correct bounding box
  97015. var oldQuaternion = i.object.rotationQuaternion;
  97016. globalQuaternion_1 = oldQuaternion.clone();
  97017. var rot = oldQuaternion.toEulerAngles();
  97018. var extendSize = i.getObjectExtendSize();
  97019. var radToDeg = 57.295779513082320876;
  97020. if (i === impostor) {
  97021. var center = impostor.getObjectCenter();
  97022. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  97023. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  97024. //Can also use Array.prototype.push.apply
  97025. bodyConfig.pos.push(center.x);
  97026. bodyConfig.pos.push(center.y);
  97027. bodyConfig.pos.push(center.z);
  97028. bodyConfig.posShape.push(0, 0, 0);
  97029. //tmp solution
  97030. bodyConfig.rot.push(0);
  97031. bodyConfig.rot.push(0);
  97032. bodyConfig.rot.push(0);
  97033. bodyConfig.rotShape.push(0, 0, 0);
  97034. }
  97035. else {
  97036. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  97037. bodyConfig.posShape.push(localPosition.x);
  97038. bodyConfig.posShape.push(localPosition.y);
  97039. bodyConfig.posShape.push(localPosition.z);
  97040. bodyConfig.pos.push(0, 0, 0);
  97041. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  97042. bodyConfig.rot.push(0);
  97043. bodyConfig.rot.push(0);
  97044. bodyConfig.rot.push(0);
  97045. bodyConfig.rotShape.push(rot.x * radToDeg);
  97046. bodyConfig.rotShape.push(rot.y * radToDeg);
  97047. bodyConfig.rotShape.push(rot.z * radToDeg);
  97048. }
  97049. // register mesh
  97050. switch (i.type) {
  97051. case BABYLON.PhysicsImpostor.ParticleImpostor:
  97052. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  97053. case BABYLON.PhysicsImpostor.SphereImpostor:
  97054. var radiusX = extendSize.x;
  97055. var radiusY = extendSize.y;
  97056. var radiusZ = extendSize.z;
  97057. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  97058. bodyConfig.type.push('sphere');
  97059. //due to the way oimo works with compounds, add 3 times
  97060. bodyConfig.size.push(size);
  97061. bodyConfig.size.push(size);
  97062. bodyConfig.size.push(size);
  97063. break;
  97064. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97065. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  97066. var sizeY = checkWithEpsilon_1(extendSize.y);
  97067. bodyConfig.type.push('cylinder');
  97068. bodyConfig.size.push(sizeX);
  97069. bodyConfig.size.push(sizeY);
  97070. //due to the way oimo works with compounds, add one more value.
  97071. bodyConfig.size.push(sizeY);
  97072. break;
  97073. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97074. case BABYLON.PhysicsImpostor.BoxImpostor:
  97075. default:
  97076. var sizeX = checkWithEpsilon_1(extendSize.x);
  97077. var sizeY = checkWithEpsilon_1(extendSize.y);
  97078. var sizeZ = checkWithEpsilon_1(extendSize.z);
  97079. bodyConfig.type.push('box');
  97080. //if (i === impostor) {
  97081. bodyConfig.size.push(sizeX);
  97082. bodyConfig.size.push(sizeY);
  97083. bodyConfig.size.push(sizeZ);
  97084. //} else {
  97085. // bodyConfig.size.push(0,0,0);
  97086. //}
  97087. break;
  97088. }
  97089. //actually not needed, but hey...
  97090. i.object.rotationQuaternion = oldQuaternion;
  97091. });
  97092. impostor.physicsBody = this.world.add(bodyConfig);
  97093. // set the quaternion, ignoring the previously defined (euler) rotation
  97094. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  97095. // update with delta 0, so the body will reveive the new rotation.
  97096. impostor.physicsBody.updatePosition(0);
  97097. }
  97098. else {
  97099. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  97100. }
  97101. impostor.setDeltaPosition(this._tmpPositionVector);
  97102. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  97103. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  97104. };
  97105. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97106. //impostor.physicsBody.dispose();
  97107. //Same as : (older oimo versions)
  97108. this.world.removeRigidBody(impostor.physicsBody);
  97109. };
  97110. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97111. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97112. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97113. if (!mainBody || !connectedBody) {
  97114. return;
  97115. }
  97116. var jointData = impostorJoint.joint.jointData;
  97117. var options = jointData.nativeParams || {};
  97118. var type;
  97119. var nativeJointData = {
  97120. body1: mainBody,
  97121. body2: connectedBody,
  97122. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  97123. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  97124. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  97125. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  97126. min: options.min,
  97127. max: options.max,
  97128. collision: options.collision || jointData.collision,
  97129. spring: options.spring,
  97130. //supporting older version of Oimo
  97131. world: this.world
  97132. };
  97133. switch (impostorJoint.joint.type) {
  97134. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97135. type = "jointBall";
  97136. break;
  97137. case BABYLON.PhysicsJoint.SpringJoint:
  97138. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  97139. var springData = jointData;
  97140. nativeJointData.min = springData.length || nativeJointData.min;
  97141. //Max should also be set, just make sure it is at least min
  97142. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  97143. case BABYLON.PhysicsJoint.DistanceJoint:
  97144. type = "jointDistance";
  97145. nativeJointData.max = jointData.maxDistance;
  97146. break;
  97147. case BABYLON.PhysicsJoint.PrismaticJoint:
  97148. type = "jointPrisme";
  97149. break;
  97150. case BABYLON.PhysicsJoint.SliderJoint:
  97151. type = "jointSlide";
  97152. break;
  97153. case BABYLON.PhysicsJoint.WheelJoint:
  97154. type = "jointWheel";
  97155. break;
  97156. case BABYLON.PhysicsJoint.HingeJoint:
  97157. default:
  97158. type = "jointHinge";
  97159. break;
  97160. }
  97161. nativeJointData.type = type;
  97162. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  97163. };
  97164. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97165. //Bug in Oimo prevents us from disposing a joint in the playground
  97166. //joint.joint.physicsJoint.dispose();
  97167. //So we will bruteforce it!
  97168. try {
  97169. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  97170. }
  97171. catch (e) {
  97172. BABYLON.Tools.Warn(e);
  97173. }
  97174. };
  97175. OimoJSPlugin.prototype.isSupported = function () {
  97176. return this.BJSOIMO !== undefined;
  97177. };
  97178. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  97179. if (!impostor.physicsBody.sleeping) {
  97180. //TODO check that
  97181. /*if (impostor.physicsBody.shapes.next) {
  97182. var parentShape = this._getLastShape(impostor.physicsBody);
  97183. impostor.object.position.copyFrom(parentShape.position);
  97184. console.log(parentShape.position);
  97185. } else {*/
  97186. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  97187. //}
  97188. if (impostor.object.rotationQuaternion) {
  97189. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  97190. }
  97191. }
  97192. };
  97193. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  97194. var body = impostor.physicsBody;
  97195. body.position.copy(newPosition);
  97196. body.orientation.copy(newRotation);
  97197. body.syncShapes();
  97198. body.awake();
  97199. };
  97200. /*private _getLastShape(body: any): any {
  97201. var lastShape = body.shapes;
  97202. while (lastShape.next) {
  97203. lastShape = lastShape.next;
  97204. }
  97205. return lastShape;
  97206. }*/
  97207. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  97208. impostor.physicsBody.linearVelocity.copy(velocity);
  97209. };
  97210. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  97211. impostor.physicsBody.angularVelocity.copy(velocity);
  97212. };
  97213. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  97214. var v = impostor.physicsBody.linearVelocity;
  97215. if (!v) {
  97216. return null;
  97217. }
  97218. return new BABYLON.Vector3(v.x, v.y, v.z);
  97219. };
  97220. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  97221. var v = impostor.physicsBody.angularVelocity;
  97222. if (!v) {
  97223. return null;
  97224. }
  97225. return new BABYLON.Vector3(v.x, v.y, v.z);
  97226. };
  97227. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  97228. var staticBody = mass === 0;
  97229. //this will actually set the body's density and not its mass.
  97230. //But this is how oimo treats the mass variable.
  97231. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  97232. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  97233. };
  97234. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  97235. return impostor.physicsBody.shapes.density;
  97236. };
  97237. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  97238. return impostor.physicsBody.shapes.friction;
  97239. };
  97240. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  97241. impostor.physicsBody.shapes.friction = friction;
  97242. };
  97243. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  97244. return impostor.physicsBody.shapes.restitution;
  97245. };
  97246. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  97247. impostor.physicsBody.shapes.restitution = restitution;
  97248. };
  97249. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  97250. impostor.physicsBody.sleep();
  97251. };
  97252. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  97253. impostor.physicsBody.awake();
  97254. };
  97255. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  97256. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  97257. if (minDistance !== void 0) {
  97258. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  97259. }
  97260. };
  97261. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  97262. //TODO separate rotational and transational motors.
  97263. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  97264. if (motor) {
  97265. motor.setMotor(speed, maxForce);
  97266. }
  97267. };
  97268. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  97269. //TODO separate rotational and transational motors.
  97270. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  97271. if (motor) {
  97272. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  97273. }
  97274. };
  97275. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  97276. var body = impostor.physicsBody;
  97277. mesh.position.x = body.position.x;
  97278. mesh.position.y = body.position.y;
  97279. mesh.position.z = body.position.z;
  97280. if (mesh.rotationQuaternion) {
  97281. mesh.rotationQuaternion.x = body.orientation.x;
  97282. mesh.rotationQuaternion.y = body.orientation.y;
  97283. mesh.rotationQuaternion.z = body.orientation.z;
  97284. mesh.rotationQuaternion.w = body.orientation.s;
  97285. }
  97286. };
  97287. OimoJSPlugin.prototype.getRadius = function (impostor) {
  97288. return impostor.physicsBody.shapes.radius;
  97289. };
  97290. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  97291. var shape = impostor.physicsBody.shapes;
  97292. result.x = shape.halfWidth * 2;
  97293. result.y = shape.halfHeight * 2;
  97294. result.z = shape.halfDepth * 2;
  97295. };
  97296. OimoJSPlugin.prototype.dispose = function () {
  97297. this.world.clear();
  97298. };
  97299. return OimoJSPlugin;
  97300. }());
  97301. BABYLON.OimoJSPlugin = OimoJSPlugin;
  97302. })(BABYLON || (BABYLON = {}));
  97303. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  97304. var BABYLON;
  97305. (function (BABYLON) {
  97306. /**
  97307. * Gets the current physics engine
  97308. * @returns a IPhysicsEngine or null if none attached
  97309. */
  97310. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  97311. return this._physicsEngine;
  97312. };
  97313. /**
  97314. * Enables physics to the current scene
  97315. * @param gravity defines the scene's gravity for the physics engine
  97316. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  97317. * @return a boolean indicating if the physics engine was initialized
  97318. */
  97319. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  97320. if (gravity === void 0) { gravity = null; }
  97321. if (this._physicsEngine) {
  97322. return true;
  97323. }
  97324. // Register the component to the scene
  97325. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  97326. if (!component) {
  97327. component = new PhysicsEngineSceneComponent(this);
  97328. this._addComponent(component);
  97329. }
  97330. try {
  97331. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  97332. return true;
  97333. }
  97334. catch (e) {
  97335. BABYLON.Tools.Error(e.message);
  97336. return false;
  97337. }
  97338. };
  97339. /**
  97340. * Disables and disposes the physics engine associated with the scene
  97341. */
  97342. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  97343. if (!this._physicsEngine) {
  97344. return;
  97345. }
  97346. this._physicsEngine.dispose();
  97347. this._physicsEngine = null;
  97348. };
  97349. /**
  97350. * Gets a boolean indicating if there is an active physics engine
  97351. * @returns a boolean indicating if there is an active physics engine
  97352. */
  97353. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  97354. return this._physicsEngine !== undefined;
  97355. };
  97356. /**
  97357. * Deletes a physics compound impostor
  97358. * @param compound defines the compound to delete
  97359. */
  97360. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  97361. var mesh = compound.parts[0].mesh;
  97362. if (mesh.physicsImpostor) {
  97363. mesh.physicsImpostor.dispose( /*true*/);
  97364. mesh.physicsImpostor = null;
  97365. }
  97366. };
  97367. /** @hidden */
  97368. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  97369. if (this._physicsEngine) {
  97370. this.onBeforePhysicsObservable.notifyObservers(this);
  97371. this._physicsEngine._step(step / 1000);
  97372. this.onAfterPhysicsObservable.notifyObservers(this);
  97373. }
  97374. };
  97375. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  97376. get: function () {
  97377. return this._physicsImpostor;
  97378. },
  97379. set: function (value) {
  97380. var _this = this;
  97381. if (this._physicsImpostor === value) {
  97382. return;
  97383. }
  97384. if (this._disposePhysicsObserver) {
  97385. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  97386. }
  97387. this._physicsImpostor = value;
  97388. if (value) {
  97389. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  97390. // Physics
  97391. if (_this.physicsImpostor) {
  97392. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  97393. _this.physicsImpostor = null;
  97394. }
  97395. });
  97396. }
  97397. },
  97398. enumerable: true,
  97399. configurable: true
  97400. });
  97401. /**
  97402. * Gets the current physics impostor
  97403. * @see http://doc.babylonjs.com/features/physics_engine
  97404. * @returns a physics impostor or null
  97405. */
  97406. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  97407. return this.physicsImpostor;
  97408. };
  97409. /**
  97410. * Apply a physic impulse to the mesh
  97411. * @param force defines the force to apply
  97412. * @param contactPoint defines where to apply the force
  97413. * @returns the current mesh
  97414. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97415. */
  97416. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  97417. if (!this.physicsImpostor) {
  97418. return this;
  97419. }
  97420. this.physicsImpostor.applyImpulse(force, contactPoint);
  97421. return this;
  97422. };
  97423. /**
  97424. * Creates a physic joint between two meshes
  97425. * @param otherMesh defines the other mesh to use
  97426. * @param pivot1 defines the pivot to use on this mesh
  97427. * @param pivot2 defines the pivot to use on the other mesh
  97428. * @param options defines additional options (can be plugin dependent)
  97429. * @returns the current mesh
  97430. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  97431. */
  97432. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  97433. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  97434. return this;
  97435. }
  97436. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  97437. mainPivot: pivot1,
  97438. connectedPivot: pivot2,
  97439. nativeParams: options
  97440. });
  97441. return this;
  97442. };
  97443. /**
  97444. * Defines the physics engine scene component responsible to manage a physics engine
  97445. */
  97446. var PhysicsEngineSceneComponent = /** @class */ (function () {
  97447. /**
  97448. * Creates a new instance of the component for the given scene
  97449. * @param scene Defines the scene to register the component in
  97450. */
  97451. function PhysicsEngineSceneComponent(scene) {
  97452. var _this = this;
  97453. /**
  97454. * The component name helpful to identify the component in the list of scene components.
  97455. */
  97456. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  97457. this.scene = scene;
  97458. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  97459. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  97460. // Replace the function used to get the deterministic frame time
  97461. this.scene.getDeterministicFrameTime = function () {
  97462. if (_this.scene._physicsEngine) {
  97463. return _this.scene._physicsEngine.getTimeStep() * 1000;
  97464. }
  97465. return 1000.0 / 60.0;
  97466. };
  97467. }
  97468. /**
  97469. * Registers the component in a given scene
  97470. */
  97471. PhysicsEngineSceneComponent.prototype.register = function () {
  97472. };
  97473. /**
  97474. * Rebuilds the elements related to this component in case of
  97475. * context lost for instance.
  97476. */
  97477. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  97478. // Nothing to do for this component
  97479. };
  97480. /**
  97481. * Disposes the component and the associated ressources
  97482. */
  97483. PhysicsEngineSceneComponent.prototype.dispose = function () {
  97484. this.scene.onBeforePhysicsObservable.clear();
  97485. this.scene.onAfterPhysicsObservable.clear();
  97486. if (this.scene._physicsEngine) {
  97487. this.scene.disablePhysicsEngine();
  97488. }
  97489. };
  97490. return PhysicsEngineSceneComponent;
  97491. }());
  97492. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  97493. })(BABYLON || (BABYLON = {}));
  97494. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  97495. var BABYLON;
  97496. (function (BABYLON) {
  97497. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  97498. // All values and structures referenced from:
  97499. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  97500. var DDS_MAGIC = 0x20534444;
  97501. var
  97502. //DDSD_CAPS = 0x1,
  97503. //DDSD_HEIGHT = 0x2,
  97504. //DDSD_WIDTH = 0x4,
  97505. //DDSD_PITCH = 0x8,
  97506. //DDSD_PIXELFORMAT = 0x1000,
  97507. DDSD_MIPMAPCOUNT = 0x20000;
  97508. //DDSD_LINEARSIZE = 0x80000,
  97509. //DDSD_DEPTH = 0x800000;
  97510. // var DDSCAPS_COMPLEX = 0x8,
  97511. // DDSCAPS_MIPMAP = 0x400000,
  97512. // DDSCAPS_TEXTURE = 0x1000;
  97513. var DDSCAPS2_CUBEMAP = 0x200;
  97514. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  97515. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  97516. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  97517. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  97518. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  97519. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  97520. // DDSCAPS2_VOLUME = 0x200000;
  97521. var
  97522. //DDPF_ALPHAPIXELS = 0x1,
  97523. //DDPF_ALPHA = 0x2,
  97524. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  97525. //DDPF_YUV = 0x200,
  97526. DDPF_LUMINANCE = 0x20000;
  97527. function FourCCToInt32(value) {
  97528. return value.charCodeAt(0) +
  97529. (value.charCodeAt(1) << 8) +
  97530. (value.charCodeAt(2) << 16) +
  97531. (value.charCodeAt(3) << 24);
  97532. }
  97533. function Int32ToFourCC(value) {
  97534. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  97535. }
  97536. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  97537. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  97538. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  97539. var FOURCC_DX10 = FourCCToInt32("DX10");
  97540. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  97541. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  97542. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  97543. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  97544. var headerLengthInt = 31; // The header length in 32 bit ints
  97545. // Offsets into the header array
  97546. var off_magic = 0;
  97547. var off_size = 1;
  97548. var off_flags = 2;
  97549. var off_height = 3;
  97550. var off_width = 4;
  97551. var off_mipmapCount = 7;
  97552. var off_pfFlags = 20;
  97553. var off_pfFourCC = 21;
  97554. var off_RGBbpp = 22;
  97555. var off_RMask = 23;
  97556. var off_GMask = 24;
  97557. var off_BMask = 25;
  97558. var off_AMask = 26;
  97559. // var off_caps1 = 27;
  97560. var off_caps2 = 28;
  97561. // var off_caps3 = 29;
  97562. // var off_caps4 = 30;
  97563. var off_dxgiFormat = 32;
  97564. /**
  97565. * Class used to provide DDS decompression tools
  97566. */
  97567. var DDSTools = /** @class */ (function () {
  97568. function DDSTools() {
  97569. }
  97570. /**
  97571. * Gets DDS information from an array buffer
  97572. * @param arrayBuffer defines the array buffer to read data from
  97573. * @returns the DDS information
  97574. */
  97575. DDSTools.GetDDSInfo = function (arrayBuffer) {
  97576. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97577. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  97578. var mipmapCount = 1;
  97579. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  97580. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97581. }
  97582. var fourCC = header[off_pfFourCC];
  97583. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  97584. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97585. switch (fourCC) {
  97586. case FOURCC_D3DFMT_R16G16B16A16F:
  97587. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97588. break;
  97589. case FOURCC_D3DFMT_R32G32B32A32F:
  97590. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97591. break;
  97592. case FOURCC_DX10:
  97593. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  97594. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97595. break;
  97596. }
  97597. }
  97598. return {
  97599. width: header[off_width],
  97600. height: header[off_height],
  97601. mipmapCount: mipmapCount,
  97602. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  97603. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  97604. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  97605. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  97606. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  97607. dxgiFormat: dxgiFormat,
  97608. textureType: textureType
  97609. };
  97610. };
  97611. DDSTools._ToHalfFloat = function (value) {
  97612. if (!DDSTools._FloatView) {
  97613. DDSTools._FloatView = new Float32Array(1);
  97614. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  97615. }
  97616. DDSTools._FloatView[0] = value;
  97617. var x = DDSTools._Int32View[0];
  97618. var bits = (x >> 16) & 0x8000; /* Get the sign */
  97619. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  97620. var e = (x >> 23) & 0xff; /* Using int is faster here */
  97621. /* If zero, or denormal, or exponent underflows too much for a denormal
  97622. * half, return signed zero. */
  97623. if (e < 103) {
  97624. return bits;
  97625. }
  97626. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  97627. if (e > 142) {
  97628. bits |= 0x7c00;
  97629. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  97630. * not Inf, so make sure we set one mantissa bit too. */
  97631. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  97632. return bits;
  97633. }
  97634. /* If exponent underflows but not too much, return a denormal */
  97635. if (e < 113) {
  97636. m |= 0x0800;
  97637. /* Extra rounding may overflow and set mantissa to 0 and exponent
  97638. * to 1, which is OK. */
  97639. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  97640. return bits;
  97641. }
  97642. bits |= ((e - 112) << 10) | (m >> 1);
  97643. bits += m & 1;
  97644. return bits;
  97645. };
  97646. DDSTools._FromHalfFloat = function (value) {
  97647. var s = (value & 0x8000) >> 15;
  97648. var e = (value & 0x7C00) >> 10;
  97649. var f = value & 0x03FF;
  97650. if (e === 0) {
  97651. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  97652. }
  97653. else if (e == 0x1F) {
  97654. return f ? NaN : ((s ? -1 : 1) * Infinity);
  97655. }
  97656. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  97657. };
  97658. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97659. var destArray = new Float32Array(dataLength);
  97660. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97661. var index = 0;
  97662. for (var y = 0; y < height; y++) {
  97663. for (var x = 0; x < width; x++) {
  97664. var srcPos = (x + y * width) * 4;
  97665. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  97666. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  97667. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  97668. if (DDSTools.StoreLODInAlphaChannel) {
  97669. destArray[index + 3] = lod;
  97670. }
  97671. else {
  97672. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  97673. }
  97674. index += 4;
  97675. }
  97676. }
  97677. return destArray;
  97678. };
  97679. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97680. if (DDSTools.StoreLODInAlphaChannel) {
  97681. var destArray = new Uint16Array(dataLength);
  97682. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97683. var index = 0;
  97684. for (var y = 0; y < height; y++) {
  97685. for (var x = 0; x < width; x++) {
  97686. var srcPos = (x + y * width) * 4;
  97687. destArray[index] = srcData[srcPos];
  97688. destArray[index + 1] = srcData[srcPos + 1];
  97689. destArray[index + 2] = srcData[srcPos + 2];
  97690. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  97691. index += 4;
  97692. }
  97693. }
  97694. return destArray;
  97695. }
  97696. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  97697. };
  97698. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97699. if (DDSTools.StoreLODInAlphaChannel) {
  97700. var destArray = new Float32Array(dataLength);
  97701. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97702. var index = 0;
  97703. for (var y = 0; y < height; y++) {
  97704. for (var x = 0; x < width; x++) {
  97705. var srcPos = (x + y * width) * 4;
  97706. destArray[index] = srcData[srcPos];
  97707. destArray[index + 1] = srcData[srcPos + 1];
  97708. destArray[index + 2] = srcData[srcPos + 2];
  97709. destArray[index + 3] = lod;
  97710. index += 4;
  97711. }
  97712. }
  97713. return destArray;
  97714. }
  97715. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  97716. };
  97717. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97718. var destArray = new Uint8Array(dataLength);
  97719. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97720. var index = 0;
  97721. for (var y = 0; y < height; y++) {
  97722. for (var x = 0; x < width; x++) {
  97723. var srcPos = (x + y * width) * 4;
  97724. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  97725. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  97726. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  97727. if (DDSTools.StoreLODInAlphaChannel) {
  97728. destArray[index + 3] = lod;
  97729. }
  97730. else {
  97731. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  97732. }
  97733. index += 4;
  97734. }
  97735. }
  97736. return destArray;
  97737. };
  97738. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97739. var destArray = new Uint8Array(dataLength);
  97740. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97741. var index = 0;
  97742. for (var y = 0; y < height; y++) {
  97743. for (var x = 0; x < width; x++) {
  97744. var srcPos = (x + y * width) * 4;
  97745. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  97746. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  97747. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  97748. if (DDSTools.StoreLODInAlphaChannel) {
  97749. destArray[index + 3] = lod;
  97750. }
  97751. else {
  97752. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  97753. }
  97754. index += 4;
  97755. }
  97756. }
  97757. return destArray;
  97758. };
  97759. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  97760. var byteArray = new Uint8Array(dataLength);
  97761. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97762. var index = 0;
  97763. for (var y = 0; y < height; y++) {
  97764. for (var x = 0; x < width; x++) {
  97765. var srcPos = (x + y * width) * 4;
  97766. byteArray[index] = srcData[srcPos + rOffset];
  97767. byteArray[index + 1] = srcData[srcPos + gOffset];
  97768. byteArray[index + 2] = srcData[srcPos + bOffset];
  97769. byteArray[index + 3] = srcData[srcPos + aOffset];
  97770. index += 4;
  97771. }
  97772. }
  97773. return byteArray;
  97774. };
  97775. DDSTools._ExtractLongWordOrder = function (value) {
  97776. if (value === 0 || value === 255 || value === -16777216) {
  97777. return 0;
  97778. }
  97779. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  97780. };
  97781. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  97782. var byteArray = new Uint8Array(dataLength);
  97783. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97784. var index = 0;
  97785. for (var y = 0; y < height; y++) {
  97786. for (var x = 0; x < width; x++) {
  97787. var srcPos = (x + y * width) * 3;
  97788. byteArray[index] = srcData[srcPos + rOffset];
  97789. byteArray[index + 1] = srcData[srcPos + gOffset];
  97790. byteArray[index + 2] = srcData[srcPos + bOffset];
  97791. index += 3;
  97792. }
  97793. }
  97794. return byteArray;
  97795. };
  97796. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  97797. var byteArray = new Uint8Array(dataLength);
  97798. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97799. var index = 0;
  97800. for (var y = 0; y < height; y++) {
  97801. for (var x = 0; x < width; x++) {
  97802. var srcPos = (x + y * width);
  97803. byteArray[index] = srcData[srcPos];
  97804. index++;
  97805. }
  97806. }
  97807. return byteArray;
  97808. };
  97809. /**
  97810. * Uploads DDS Levels to a Babylon Texture
  97811. * @hidden
  97812. */
  97813. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  97814. if (lodIndex === void 0) { lodIndex = -1; }
  97815. var sphericalPolynomialFaces = null;
  97816. if (info.sphericalPolynomial) {
  97817. sphericalPolynomialFaces = new Array();
  97818. }
  97819. var ext = engine.getCaps().s3tc;
  97820. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97821. var fourCC, width, height, dataLength = 0, dataOffset;
  97822. var byteArray, mipmapCount, mip;
  97823. var internalCompressedFormat = 0;
  97824. var blockBytes = 1;
  97825. if (header[off_magic] !== DDS_MAGIC) {
  97826. BABYLON.Tools.Error("Invalid magic number in DDS header");
  97827. return;
  97828. }
  97829. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  97830. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  97831. return;
  97832. }
  97833. if (info.isCompressed && !ext) {
  97834. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  97835. return;
  97836. }
  97837. var bpp = header[off_RGBbpp];
  97838. dataOffset = header[off_size] + 4;
  97839. var computeFormats = false;
  97840. if (info.isFourCC) {
  97841. fourCC = header[off_pfFourCC];
  97842. switch (fourCC) {
  97843. case FOURCC_DXT1:
  97844. blockBytes = 8;
  97845. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  97846. break;
  97847. case FOURCC_DXT3:
  97848. blockBytes = 16;
  97849. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  97850. break;
  97851. case FOURCC_DXT5:
  97852. blockBytes = 16;
  97853. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  97854. break;
  97855. case FOURCC_D3DFMT_R16G16B16A16F:
  97856. computeFormats = true;
  97857. break;
  97858. case FOURCC_D3DFMT_R32G32B32A32F:
  97859. computeFormats = true;
  97860. break;
  97861. case FOURCC_DX10:
  97862. // There is an additionnal header so dataOffset need to be changed
  97863. dataOffset += 5 * 4; // 5 uints
  97864. var supported = false;
  97865. switch (info.dxgiFormat) {
  97866. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  97867. computeFormats = true;
  97868. supported = true;
  97869. break;
  97870. case DXGI_FORMAT_B8G8R8X8_UNORM:
  97871. info.isRGB = true;
  97872. info.isFourCC = false;
  97873. bpp = 32;
  97874. supported = true;
  97875. break;
  97876. }
  97877. if (supported) {
  97878. break;
  97879. }
  97880. default:
  97881. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  97882. return;
  97883. }
  97884. }
  97885. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  97886. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  97887. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  97888. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  97889. if (computeFormats) {
  97890. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  97891. }
  97892. mipmapCount = 1;
  97893. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  97894. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97895. }
  97896. for (var face = 0; face < faces; face++) {
  97897. width = header[off_width];
  97898. height = header[off_height];
  97899. for (mip = 0; mip < mipmapCount; ++mip) {
  97900. if (lodIndex === -1 || lodIndex === mip) {
  97901. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  97902. var i = (lodIndex === -1) ? mip : 0;
  97903. if (!info.isCompressed && info.isFourCC) {
  97904. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97905. dataLength = width * height * 4;
  97906. var floatArray = null;
  97907. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  97908. if (bpp === 128) {
  97909. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97910. if (sphericalPolynomialFaces && i == 0) {
  97911. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97912. }
  97913. }
  97914. else if (bpp === 64) {
  97915. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97916. if (sphericalPolynomialFaces && i == 0) {
  97917. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97918. }
  97919. }
  97920. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97921. }
  97922. else {
  97923. if (bpp === 128) {
  97924. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97925. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97926. if (sphericalPolynomialFaces && i == 0) {
  97927. sphericalPolynomialFaces.push(floatArray);
  97928. }
  97929. }
  97930. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  97931. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97932. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97933. if (sphericalPolynomialFaces && i == 0) {
  97934. sphericalPolynomialFaces.push(floatArray);
  97935. }
  97936. }
  97937. else { // 64
  97938. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97939. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97940. if (sphericalPolynomialFaces && i == 0) {
  97941. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97942. }
  97943. }
  97944. }
  97945. if (floatArray) {
  97946. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  97947. }
  97948. }
  97949. else if (info.isRGB) {
  97950. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97951. if (bpp === 24) {
  97952. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  97953. dataLength = width * height * 3;
  97954. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  97955. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97956. }
  97957. else { // 32
  97958. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97959. dataLength = width * height * 4;
  97960. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  97961. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97962. }
  97963. }
  97964. else if (info.isLuminance) {
  97965. var unpackAlignment = engine._getUnpackAlignement();
  97966. var unpaddedRowSize = width;
  97967. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  97968. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  97969. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  97970. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  97971. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97972. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97973. }
  97974. else {
  97975. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  97976. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  97977. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97978. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  97979. }
  97980. }
  97981. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  97982. width *= 0.5;
  97983. height *= 0.5;
  97984. width = Math.max(1.0, width);
  97985. height = Math.max(1.0, height);
  97986. }
  97987. if (currentFace !== undefined) {
  97988. // Loading a single face
  97989. break;
  97990. }
  97991. }
  97992. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  97993. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  97994. size: header[off_width],
  97995. right: sphericalPolynomialFaces[0],
  97996. left: sphericalPolynomialFaces[1],
  97997. up: sphericalPolynomialFaces[2],
  97998. down: sphericalPolynomialFaces[3],
  97999. front: sphericalPolynomialFaces[4],
  98000. back: sphericalPolynomialFaces[5],
  98001. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  98002. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  98003. gammaSpace: false,
  98004. });
  98005. }
  98006. else {
  98007. info.sphericalPolynomial = undefined;
  98008. }
  98009. };
  98010. /**
  98011. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  98012. */
  98013. DDSTools.StoreLODInAlphaChannel = false;
  98014. return DDSTools;
  98015. }());
  98016. BABYLON.DDSTools = DDSTools;
  98017. })(BABYLON || (BABYLON = {}));
  98018. //# sourceMappingURL=babylon.dds.js.map
  98019. var BABYLON;
  98020. (function (BABYLON) {
  98021. /**
  98022. * Implementation of the DDS Texture Loader.
  98023. */
  98024. var DDSTextureLoader = /** @class */ (function () {
  98025. function DDSTextureLoader() {
  98026. /**
  98027. * Defines wether the loader supports cascade loading the different faces.
  98028. */
  98029. this.supportCascades = true;
  98030. }
  98031. /**
  98032. * This returns if the loader support the current file information.
  98033. * @param extension defines the file extension of the file being loaded
  98034. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98035. * @param fallback defines the fallback internal texture if any
  98036. * @param isBase64 defines whether the texture is encoded as a base64
  98037. * @param isBuffer defines whether the texture data are stored as a buffer
  98038. * @returns true if the loader can load the specified file
  98039. */
  98040. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98041. return extension.indexOf(".dds") === 0;
  98042. };
  98043. /**
  98044. * Transform the url before loading if required.
  98045. * @param rootUrl the url of the texture
  98046. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98047. * @returns the transformed texture
  98048. */
  98049. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98050. return rootUrl;
  98051. };
  98052. /**
  98053. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98054. * @param rootUrl the url of the texture
  98055. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98056. * @returns the fallback texture
  98057. */
  98058. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98059. return null;
  98060. };
  98061. /**
  98062. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98063. * @param data contains the texture data
  98064. * @param texture defines the BabylonJS internal texture
  98065. * @param createPolynomials will be true if polynomials have been requested
  98066. * @param onLoad defines the callback to trigger once the texture is ready
  98067. * @param onError defines the callback to trigger in case of error
  98068. */
  98069. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  98070. var engine = texture.getEngine();
  98071. var info;
  98072. var loadMipmap = false;
  98073. if (Array.isArray(imgs)) {
  98074. for (var index = 0; index < imgs.length; index++) {
  98075. var data_1 = imgs[index];
  98076. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  98077. texture.width = info.width;
  98078. texture.height = info.height;
  98079. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  98080. engine._unpackFlipY(info.isCompressed);
  98081. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  98082. if (!info.isFourCC && info.mipmapCount === 1) {
  98083. engine.generateMipMapsForCubemap(texture);
  98084. }
  98085. }
  98086. }
  98087. else {
  98088. var data = imgs;
  98089. info = BABYLON.DDSTools.GetDDSInfo(data);
  98090. texture.width = info.width;
  98091. texture.height = info.height;
  98092. if (createPolynomials) {
  98093. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  98094. }
  98095. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  98096. engine._unpackFlipY(info.isCompressed);
  98097. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  98098. if (!info.isFourCC && info.mipmapCount === 1) {
  98099. engine.generateMipMapsForCubemap(texture);
  98100. }
  98101. }
  98102. engine._setCubeMapTextureParams(loadMipmap);
  98103. texture.isReady = true;
  98104. if (onLoad) {
  98105. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  98106. }
  98107. };
  98108. /**
  98109. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98110. * @param data contains the texture data
  98111. * @param texture defines the BabylonJS internal texture
  98112. * @param callback defines the method to call once ready to upload
  98113. */
  98114. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  98115. var info = BABYLON.DDSTools.GetDDSInfo(data);
  98116. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  98117. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  98118. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  98119. });
  98120. };
  98121. return DDSTextureLoader;
  98122. }());
  98123. // Register the loader.
  98124. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  98125. })(BABYLON || (BABYLON = {}));
  98126. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  98127. var BABYLON;
  98128. (function (BABYLON) {
  98129. /**
  98130. * Based on jsTGALoader - Javascript loader for TGA file
  98131. * By Vincent Thibault
  98132. * @see http://blog.robrowser.com/javascript-tga-loader.html
  98133. */
  98134. var TGATools = /** @class */ (function () {
  98135. function TGATools() {
  98136. }
  98137. /**
  98138. * Gets the header of a TGA file
  98139. * @param data defines the TGA data
  98140. * @returns the header
  98141. */
  98142. TGATools.GetTGAHeader = function (data) {
  98143. var offset = 0;
  98144. var header = {
  98145. id_length: data[offset++],
  98146. colormap_type: data[offset++],
  98147. image_type: data[offset++],
  98148. colormap_index: data[offset++] | data[offset++] << 8,
  98149. colormap_length: data[offset++] | data[offset++] << 8,
  98150. colormap_size: data[offset++],
  98151. origin: [
  98152. data[offset++] | data[offset++] << 8,
  98153. data[offset++] | data[offset++] << 8
  98154. ],
  98155. width: data[offset++] | data[offset++] << 8,
  98156. height: data[offset++] | data[offset++] << 8,
  98157. pixel_size: data[offset++],
  98158. flags: data[offset++]
  98159. };
  98160. return header;
  98161. };
  98162. /**
  98163. * Uploads TGA content to a Babylon Texture
  98164. * @hidden
  98165. */
  98166. TGATools.UploadContent = function (texture, data) {
  98167. // Not enough data to contain header ?
  98168. if (data.length < 19) {
  98169. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  98170. return;
  98171. }
  98172. // Read Header
  98173. var offset = 18;
  98174. var header = TGATools.GetTGAHeader(data);
  98175. // Assume it's a valid Targa file.
  98176. if (header.id_length + offset > data.length) {
  98177. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  98178. return;
  98179. }
  98180. // Skip not needed data
  98181. offset += header.id_length;
  98182. var use_rle = false;
  98183. var use_pal = false;
  98184. var use_grey = false;
  98185. // Get some informations.
  98186. switch (header.image_type) {
  98187. case TGATools._TYPE_RLE_INDEXED:
  98188. use_rle = true;
  98189. case TGATools._TYPE_INDEXED:
  98190. use_pal = true;
  98191. break;
  98192. case TGATools._TYPE_RLE_RGB:
  98193. use_rle = true;
  98194. case TGATools._TYPE_RGB:
  98195. // use_rgb = true;
  98196. break;
  98197. case TGATools._TYPE_RLE_GREY:
  98198. use_rle = true;
  98199. case TGATools._TYPE_GREY:
  98200. use_grey = true;
  98201. break;
  98202. }
  98203. var pixel_data;
  98204. // var numAlphaBits = header.flags & 0xf;
  98205. var pixel_size = header.pixel_size >> 3;
  98206. var pixel_total = header.width * header.height * pixel_size;
  98207. // Read palettes
  98208. var palettes;
  98209. if (use_pal) {
  98210. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  98211. }
  98212. // Read LRE
  98213. if (use_rle) {
  98214. pixel_data = new Uint8Array(pixel_total);
  98215. var c, count, i;
  98216. var localOffset = 0;
  98217. var pixels = new Uint8Array(pixel_size);
  98218. while (offset < pixel_total && localOffset < pixel_total) {
  98219. c = data[offset++];
  98220. count = (c & 0x7f) + 1;
  98221. // RLE pixels
  98222. if (c & 0x80) {
  98223. // Bind pixel tmp array
  98224. for (i = 0; i < pixel_size; ++i) {
  98225. pixels[i] = data[offset++];
  98226. }
  98227. // Copy pixel array
  98228. for (i = 0; i < count; ++i) {
  98229. pixel_data.set(pixels, localOffset + i * pixel_size);
  98230. }
  98231. localOffset += pixel_size * count;
  98232. }
  98233. // Raw pixels
  98234. else {
  98235. count *= pixel_size;
  98236. for (i = 0; i < count; ++i) {
  98237. pixel_data[localOffset + i] = data[offset++];
  98238. }
  98239. localOffset += count;
  98240. }
  98241. }
  98242. }
  98243. // RAW Pixels
  98244. else {
  98245. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  98246. }
  98247. // Load to texture
  98248. var x_start, y_start, x_step, y_step, y_end, x_end;
  98249. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  98250. default:
  98251. case TGATools._ORIGIN_UL:
  98252. x_start = 0;
  98253. x_step = 1;
  98254. x_end = header.width;
  98255. y_start = 0;
  98256. y_step = 1;
  98257. y_end = header.height;
  98258. break;
  98259. case TGATools._ORIGIN_BL:
  98260. x_start = 0;
  98261. x_step = 1;
  98262. x_end = header.width;
  98263. y_start = header.height - 1;
  98264. y_step = -1;
  98265. y_end = -1;
  98266. break;
  98267. case TGATools._ORIGIN_UR:
  98268. x_start = header.width - 1;
  98269. x_step = -1;
  98270. x_end = -1;
  98271. y_start = 0;
  98272. y_step = 1;
  98273. y_end = header.height;
  98274. break;
  98275. case TGATools._ORIGIN_BR:
  98276. x_start = header.width - 1;
  98277. x_step = -1;
  98278. x_end = -1;
  98279. y_start = header.height - 1;
  98280. y_step = -1;
  98281. y_end = -1;
  98282. break;
  98283. }
  98284. // Load the specify method
  98285. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  98286. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  98287. var engine = texture.getEngine();
  98288. engine._uploadDataToTextureDirectly(texture, imageData);
  98289. };
  98290. /** @hidden */
  98291. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98292. var image = pixel_data, colormap = palettes;
  98293. var width = header.width, height = header.height;
  98294. var color, i = 0, x, y;
  98295. var imageData = new Uint8Array(width * height * 4);
  98296. for (y = y_start; y !== y_end; y += y_step) {
  98297. for (x = x_start; x !== x_end; x += x_step, i++) {
  98298. color = image[i];
  98299. imageData[(x + width * y) * 4 + 3] = 255;
  98300. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  98301. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  98302. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  98303. }
  98304. }
  98305. return imageData;
  98306. };
  98307. /** @hidden */
  98308. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98309. var image = pixel_data;
  98310. var width = header.width, height = header.height;
  98311. var color, i = 0, x, y;
  98312. var imageData = new Uint8Array(width * height * 4);
  98313. for (y = y_start; y !== y_end; y += y_step) {
  98314. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98315. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  98316. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  98317. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  98318. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  98319. imageData[(x + width * y) * 4 + 0] = r;
  98320. imageData[(x + width * y) * 4 + 1] = g;
  98321. imageData[(x + width * y) * 4 + 2] = b;
  98322. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  98323. }
  98324. }
  98325. return imageData;
  98326. };
  98327. /** @hidden */
  98328. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98329. var image = pixel_data;
  98330. var width = header.width, height = header.height;
  98331. var i = 0, x, y;
  98332. var imageData = new Uint8Array(width * height * 4);
  98333. for (y = y_start; y !== y_end; y += y_step) {
  98334. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  98335. imageData[(x + width * y) * 4 + 3] = 255;
  98336. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98337. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98338. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98339. }
  98340. }
  98341. return imageData;
  98342. };
  98343. /** @hidden */
  98344. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98345. var image = pixel_data;
  98346. var width = header.width, height = header.height;
  98347. var i = 0, x, y;
  98348. var imageData = new Uint8Array(width * height * 4);
  98349. for (y = y_start; y !== y_end; y += y_step) {
  98350. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  98351. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98352. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98353. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98354. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  98355. }
  98356. }
  98357. return imageData;
  98358. };
  98359. /** @hidden */
  98360. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98361. var image = pixel_data;
  98362. var width = header.width, height = header.height;
  98363. var color, i = 0, x, y;
  98364. var imageData = new Uint8Array(width * height * 4);
  98365. for (y = y_start; y !== y_end; y += y_step) {
  98366. for (x = x_start; x !== x_end; x += x_step, i++) {
  98367. color = image[i];
  98368. imageData[(x + width * y) * 4 + 0] = color;
  98369. imageData[(x + width * y) * 4 + 1] = color;
  98370. imageData[(x + width * y) * 4 + 2] = color;
  98371. imageData[(x + width * y) * 4 + 3] = 255;
  98372. }
  98373. }
  98374. return imageData;
  98375. };
  98376. /** @hidden */
  98377. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98378. var image = pixel_data;
  98379. var width = header.width, height = header.height;
  98380. var i = 0, x, y;
  98381. var imageData = new Uint8Array(width * height * 4);
  98382. for (y = y_start; y !== y_end; y += y_step) {
  98383. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98384. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  98385. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  98386. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98387. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  98388. }
  98389. }
  98390. return imageData;
  98391. };
  98392. //private static _TYPE_NO_DATA = 0;
  98393. TGATools._TYPE_INDEXED = 1;
  98394. TGATools._TYPE_RGB = 2;
  98395. TGATools._TYPE_GREY = 3;
  98396. TGATools._TYPE_RLE_INDEXED = 9;
  98397. TGATools._TYPE_RLE_RGB = 10;
  98398. TGATools._TYPE_RLE_GREY = 11;
  98399. TGATools._ORIGIN_MASK = 0x30;
  98400. TGATools._ORIGIN_SHIFT = 0x04;
  98401. TGATools._ORIGIN_BL = 0x00;
  98402. TGATools._ORIGIN_BR = 0x01;
  98403. TGATools._ORIGIN_UL = 0x02;
  98404. TGATools._ORIGIN_UR = 0x03;
  98405. return TGATools;
  98406. }());
  98407. BABYLON.TGATools = TGATools;
  98408. })(BABYLON || (BABYLON = {}));
  98409. //# sourceMappingURL=babylon.tga.js.map
  98410. var BABYLON;
  98411. (function (BABYLON) {
  98412. /**
  98413. * Implementation of the TGA Texture Loader.
  98414. */
  98415. var TGATextureLoader = /** @class */ (function () {
  98416. function TGATextureLoader() {
  98417. /**
  98418. * Defines wether the loader supports cascade loading the different faces.
  98419. */
  98420. this.supportCascades = false;
  98421. }
  98422. /**
  98423. * This returns if the loader support the current file information.
  98424. * @param extension defines the file extension of the file being loaded
  98425. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98426. * @param fallback defines the fallback internal texture if any
  98427. * @param isBase64 defines whether the texture is encoded as a base64
  98428. * @param isBuffer defines whether the texture data are stored as a buffer
  98429. * @returns true if the loader can load the specified file
  98430. */
  98431. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98432. return extension.indexOf(".tga") === 0;
  98433. };
  98434. /**
  98435. * Transform the url before loading if required.
  98436. * @param rootUrl the url of the texture
  98437. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98438. * @returns the transformed texture
  98439. */
  98440. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98441. return rootUrl;
  98442. };
  98443. /**
  98444. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98445. * @param rootUrl the url of the texture
  98446. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98447. * @returns the fallback texture
  98448. */
  98449. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98450. return null;
  98451. };
  98452. /**
  98453. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98454. * @param data contains the texture data
  98455. * @param texture defines the BabylonJS internal texture
  98456. * @param createPolynomials will be true if polynomials have been requested
  98457. * @param onLoad defines the callback to trigger once the texture is ready
  98458. * @param onError defines the callback to trigger in case of error
  98459. */
  98460. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98461. throw ".env not supported in Cube.";
  98462. };
  98463. /**
  98464. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98465. * @param data contains the texture data
  98466. * @param texture defines the BabylonJS internal texture
  98467. * @param callback defines the method to call once ready to upload
  98468. */
  98469. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  98470. var uintData = new Uint8Array(data);
  98471. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  98472. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  98473. BABYLON.TGATools.UploadContent(texture, uintData);
  98474. });
  98475. };
  98476. return TGATextureLoader;
  98477. }());
  98478. // Register the loader.
  98479. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  98480. })(BABYLON || (BABYLON = {}));
  98481. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  98482. var BABYLON;
  98483. (function (BABYLON) {
  98484. /**
  98485. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  98486. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  98487. */
  98488. var KhronosTextureContainer = /** @class */ (function () {
  98489. /**
  98490. * Creates a new KhronosTextureContainer
  98491. * @param arrayBuffer contents of the KTX container file
  98492. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  98493. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  98494. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  98495. */
  98496. function KhronosTextureContainer(
  98497. /** contents of the KTX container file */
  98498. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  98499. this.arrayBuffer = arrayBuffer;
  98500. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  98501. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  98502. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  98503. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  98504. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  98505. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  98506. BABYLON.Tools.Error("texture missing KTX identifier");
  98507. return;
  98508. }
  98509. // load the reset of the header in native 32 bit int
  98510. var header = new Int32Array(this.arrayBuffer, 12, 13);
  98511. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  98512. var oppositeEndianess = header[0] === 0x01020304;
  98513. // read all the header elements in order they exist in the file, without modification (sans endainness)
  98514. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  98515. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  98516. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  98517. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  98518. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  98519. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  98520. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  98521. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  98522. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  98523. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  98524. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  98525. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  98526. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  98527. if (this.glType !== 0) {
  98528. BABYLON.Tools.Error("only compressed formats currently supported");
  98529. return;
  98530. }
  98531. else {
  98532. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  98533. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  98534. }
  98535. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  98536. BABYLON.Tools.Error("only 2D textures currently supported");
  98537. return;
  98538. }
  98539. if (this.numberOfArrayElements !== 0) {
  98540. BABYLON.Tools.Error("texture arrays not currently supported");
  98541. return;
  98542. }
  98543. if (this.numberOfFaces !== facesExpected) {
  98544. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  98545. return;
  98546. }
  98547. // we now have a completely validated file, so could use existence of loadType as success
  98548. // would need to make this more elaborate & adjust checks above to support more than one load type
  98549. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  98550. }
  98551. //
  98552. /**
  98553. * Revert the endianness of a value.
  98554. * Not as fast hardware based, but will probably never need to use
  98555. * @param val defines the value to convert
  98556. * @returns the new value
  98557. */
  98558. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  98559. return ((val & 0xFF) << 24)
  98560. | ((val & 0xFF00) << 8)
  98561. | ((val >> 8) & 0xFF00)
  98562. | ((val >> 24) & 0xFF);
  98563. };
  98564. /**
  98565. * Uploads KTX content to a Babylon Texture.
  98566. * It is assumed that the texture has already been created & is currently bound
  98567. * @hidden
  98568. */
  98569. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  98570. switch (this.loadType) {
  98571. case KhronosTextureContainer.COMPRESSED_2D:
  98572. this._upload2DCompressedLevels(texture, loadMipmaps);
  98573. break;
  98574. case KhronosTextureContainer.TEX_2D:
  98575. case KhronosTextureContainer.COMPRESSED_3D:
  98576. case KhronosTextureContainer.TEX_3D:
  98577. }
  98578. };
  98579. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  98580. // initialize width & height for level 1
  98581. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  98582. var width = this.pixelWidth;
  98583. var height = this.pixelHeight;
  98584. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  98585. for (var level = 0; level < mipmapCount; level++) {
  98586. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  98587. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  98588. for (var face = 0; face < this.numberOfFaces; face++) {
  98589. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  98590. var engine = texture.getEngine();
  98591. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  98592. dataOffset += imageSize; // add size of the image for the next face/mipmap
  98593. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  98594. }
  98595. width = Math.max(1.0, width * 0.5);
  98596. height = Math.max(1.0, height * 0.5);
  98597. }
  98598. };
  98599. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  98600. // load types
  98601. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  98602. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  98603. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  98604. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  98605. return KhronosTextureContainer;
  98606. }());
  98607. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  98608. })(BABYLON || (BABYLON = {}));
  98609. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  98610. var BABYLON;
  98611. (function (BABYLON) {
  98612. /**
  98613. * Implementation of the KTX Texture Loader.
  98614. */
  98615. var KTXTextureLoader = /** @class */ (function () {
  98616. function KTXTextureLoader() {
  98617. /**
  98618. * Defines wether the loader supports cascade loading the different faces.
  98619. */
  98620. this.supportCascades = false;
  98621. }
  98622. /**
  98623. * This returns if the loader support the current file information.
  98624. * @param extension defines the file extension of the file being loaded
  98625. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98626. * @param fallback defines the fallback internal texture if any
  98627. * @param isBase64 defines whether the texture is encoded as a base64
  98628. * @param isBuffer defines whether the texture data are stored as a buffer
  98629. * @returns true if the loader can load the specified file
  98630. */
  98631. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98632. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  98633. return true;
  98634. }
  98635. return false;
  98636. };
  98637. /**
  98638. * Transform the url before loading if required.
  98639. * @param rootUrl the url of the texture
  98640. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98641. * @returns the transformed texture
  98642. */
  98643. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98644. var lastDot = rootUrl.lastIndexOf('.');
  98645. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  98646. };
  98647. /**
  98648. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98649. * @param rootUrl the url of the texture
  98650. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98651. * @returns the fallback texture
  98652. */
  98653. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98654. // remove the format appended to the rootUrl in the original createCubeTexture call.
  98655. var exp = new RegExp("" + textureFormatInUse + "$");
  98656. return rootUrl.replace(exp, "");
  98657. };
  98658. /**
  98659. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98660. * @param data contains the texture data
  98661. * @param texture defines the BabylonJS internal texture
  98662. * @param createPolynomials will be true if polynomials have been requested
  98663. * @param onLoad defines the callback to trigger once the texture is ready
  98664. * @param onError defines the callback to trigger in case of error
  98665. */
  98666. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98667. if (Array.isArray(data)) {
  98668. return;
  98669. }
  98670. var engine = texture.getEngine();
  98671. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  98672. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  98673. engine._unpackFlipY(true);
  98674. ktx.uploadLevels(texture, texture.generateMipMaps);
  98675. texture.width = ktx.pixelWidth;
  98676. texture.height = ktx.pixelHeight;
  98677. engine._setCubeMapTextureParams(loadMipmap);
  98678. texture.isReady = true;
  98679. };
  98680. /**
  98681. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98682. * @param data contains the texture data
  98683. * @param texture defines the BabylonJS internal texture
  98684. * @param callback defines the method to call once ready to upload
  98685. */
  98686. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  98687. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  98688. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  98689. ktx.uploadLevels(texture, texture.generateMipMaps);
  98690. });
  98691. };
  98692. return KTXTextureLoader;
  98693. }());
  98694. // Register the loader.
  98695. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  98696. })(BABYLON || (BABYLON = {}));
  98697. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  98698. var BABYLON;
  98699. (function (BABYLON) {
  98700. /**
  98701. * Sets of helpers addressing the serialization and deserialization of environment texture
  98702. * stored in a BabylonJS env file.
  98703. * Those files are usually stored as .env files.
  98704. */
  98705. var EnvironmentTextureTools = /** @class */ (function () {
  98706. function EnvironmentTextureTools() {
  98707. }
  98708. /**
  98709. * Gets the environment info from an env file.
  98710. * @param data The array buffer containing the .env bytes.
  98711. * @returns the environment file info (the json header) if successfully parsed.
  98712. */
  98713. EnvironmentTextureTools.GetEnvInfo = function (data) {
  98714. var dataView = new DataView(data);
  98715. var pos = 0;
  98716. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98717. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  98718. BABYLON.Tools.Error('Not a babylon environment map');
  98719. return null;
  98720. }
  98721. }
  98722. // Read json manifest - collect characters up to null terminator
  98723. var manifestString = '';
  98724. var charCode = 0x00;
  98725. while ((charCode = dataView.getUint8(pos++))) {
  98726. manifestString += String.fromCharCode(charCode);
  98727. }
  98728. var manifest = JSON.parse(manifestString);
  98729. if (manifest.specular) {
  98730. // Extend the header with the position of the payload.
  98731. manifest.specular.specularDataPosition = pos;
  98732. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  98733. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  98734. }
  98735. return manifest;
  98736. };
  98737. /**
  98738. * Creates an environment texture from a loaded cube texture.
  98739. * @param texture defines the cube texture to convert in env file
  98740. * @return a promise containing the environment data if succesfull.
  98741. */
  98742. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  98743. var _this = this;
  98744. var internalTexture = texture.getInternalTexture();
  98745. if (!internalTexture) {
  98746. return Promise.reject("The cube texture is invalid.");
  98747. }
  98748. if (!texture._prefiltered) {
  98749. return Promise.reject("The cube texture is invalid (not prefiltered).");
  98750. }
  98751. var engine = internalTexture.getEngine();
  98752. if (engine && engine.premultipliedAlpha) {
  98753. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  98754. }
  98755. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  98756. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  98757. }
  98758. var canvas = engine.getRenderingCanvas();
  98759. if (!canvas) {
  98760. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  98761. }
  98762. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98763. if (!engine.getCaps().textureFloatRender) {
  98764. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98765. if (!engine.getCaps().textureHalfFloatRender) {
  98766. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  98767. }
  98768. }
  98769. var cubeWidth = internalTexture.width;
  98770. var hostingScene = new BABYLON.Scene(engine);
  98771. var specularTextures = {};
  98772. var promises = [];
  98773. // Read and collect all mipmaps data from the cube.
  98774. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  98775. mipmapsCount = Math.round(mipmapsCount);
  98776. var _loop_1 = function (i) {
  98777. var faceWidth = Math.pow(2, mipmapsCount - i);
  98778. var _loop_2 = function (face) {
  98779. var data = texture.readPixels(face, i);
  98780. // Creates a temp texture with the face data.
  98781. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  98782. // And rgbdEncode them.
  98783. var promise = new Promise(function (resolve, reject) {
  98784. 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);
  98785. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98786. rgbdPostProcess.onApply = function (effect) {
  98787. effect._bindTexture("textureSampler", tempTexture);
  98788. };
  98789. // As the process needs to happen on the main canvas, keep track of the current size
  98790. var currentW = engine.getRenderWidth();
  98791. var currentH = engine.getRenderHeight();
  98792. // Set the desired size for the texture
  98793. engine.setSize(faceWidth, faceWidth);
  98794. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  98795. // Reading datas from WebGL
  98796. BABYLON.Tools.ToBlob(canvas, function (blob) {
  98797. var fileReader = new FileReader();
  98798. fileReader.onload = function (event) {
  98799. var arrayBuffer = event.target.result;
  98800. specularTextures[i * 6 + face] = arrayBuffer;
  98801. resolve();
  98802. };
  98803. fileReader.readAsArrayBuffer(blob);
  98804. });
  98805. // Reapply the previous canvas size
  98806. engine.setSize(currentW, currentH);
  98807. });
  98808. });
  98809. promises.push(promise);
  98810. };
  98811. // All faces of the cube.
  98812. for (var face = 0; face < 6; face++) {
  98813. _loop_2(face);
  98814. }
  98815. };
  98816. for (var i = 0; i <= mipmapsCount; i++) {
  98817. _loop_1(i);
  98818. }
  98819. // Once all the textures haves been collected as RGBD stored in PNGs
  98820. return Promise.all(promises).then(function () {
  98821. // We can delete the hosting scene keeping track of all the creation objects
  98822. hostingScene.dispose();
  98823. // Creates the json header for the env texture
  98824. var info = {
  98825. version: 1,
  98826. width: cubeWidth,
  98827. irradiance: _this._CreateEnvTextureIrradiance(texture),
  98828. specular: {
  98829. mipmaps: [],
  98830. lodGenerationScale: texture.lodGenerationScale
  98831. }
  98832. };
  98833. // Sets the specular image data information
  98834. var position = 0;
  98835. for (var i = 0; i <= mipmapsCount; i++) {
  98836. for (var face = 0; face < 6; face++) {
  98837. var byteLength = specularTextures[i * 6 + face].byteLength;
  98838. info.specular.mipmaps.push({
  98839. length: byteLength,
  98840. position: position
  98841. });
  98842. position += byteLength;
  98843. }
  98844. }
  98845. // Encode the JSON as an array buffer
  98846. var infoString = JSON.stringify(info);
  98847. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  98848. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  98849. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  98850. infoView[i] = infoString.charCodeAt(i);
  98851. }
  98852. // Ends up with a null terminator for easier parsing
  98853. infoView[infoString.length] = 0x00;
  98854. // Computes the final required size and creates the storage
  98855. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  98856. var finalBuffer = new ArrayBuffer(totalSize);
  98857. var finalBufferView = new Uint8Array(finalBuffer);
  98858. var dataView = new DataView(finalBuffer);
  98859. // Copy the magic bytes identifying the file in
  98860. var pos = 0;
  98861. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98862. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  98863. }
  98864. // Add the json info
  98865. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  98866. pos += infoBuffer.byteLength;
  98867. // Finally inserts the texture data
  98868. for (var i = 0; i <= mipmapsCount; i++) {
  98869. for (var face = 0; face < 6; face++) {
  98870. var dataBuffer = specularTextures[i * 6 + face];
  98871. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  98872. pos += dataBuffer.byteLength;
  98873. }
  98874. }
  98875. // Voila
  98876. return finalBuffer;
  98877. });
  98878. };
  98879. /**
  98880. * Creates a JSON representation of the spherical data.
  98881. * @param texture defines the texture containing the polynomials
  98882. * @return the JSON representation of the spherical info
  98883. */
  98884. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  98885. var polynmials = texture.sphericalPolynomial;
  98886. if (polynmials == null) {
  98887. return null;
  98888. }
  98889. return {
  98890. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  98891. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  98892. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  98893. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  98894. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  98895. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  98896. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  98897. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  98898. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  98899. };
  98900. };
  98901. /**
  98902. * Uploads the texture info contained in the env file to the GPU.
  98903. * @param texture defines the internal texture to upload to
  98904. * @param arrayBuffer defines the buffer cotaining the data to load
  98905. * @param info defines the texture info retrieved through the GetEnvInfo method
  98906. * @returns a promise
  98907. */
  98908. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  98909. if (info.version !== 1) {
  98910. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  98911. }
  98912. var specularInfo = info.specular;
  98913. if (!specularInfo) {
  98914. // Nothing else parsed so far
  98915. return Promise.resolve();
  98916. }
  98917. // Double checks the enclosed info
  98918. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  98919. mipmapsCount = Math.round(mipmapsCount) + 1;
  98920. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  98921. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  98922. }
  98923. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  98924. var imageData = new Array(mipmapsCount);
  98925. for (var i = 0; i < mipmapsCount; i++) {
  98926. imageData[i] = new Array(6);
  98927. for (var face = 0; face < 6; face++) {
  98928. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  98929. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  98930. }
  98931. }
  98932. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  98933. };
  98934. /**
  98935. * Uploads the levels of image data to the GPU.
  98936. * @param texture defines the internal texture to upload to
  98937. * @param imageData defines the array buffer views of image data [mipmap][face]
  98938. * @returns a promise
  98939. */
  98940. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  98941. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  98942. throw new Error("Texture size must be a power of two");
  98943. }
  98944. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  98945. // Gets everything ready.
  98946. var engine = texture.getEngine();
  98947. var expandTexture = false;
  98948. var generateNonLODTextures = false;
  98949. var rgbdPostProcess = null;
  98950. var cubeRtt = null;
  98951. var lodTextures = null;
  98952. var caps = engine.getCaps();
  98953. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  98954. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98955. texture.generateMipMaps = true;
  98956. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  98957. // Add extra process if texture lod is not supported
  98958. if (!caps.textureLOD) {
  98959. expandTexture = false;
  98960. generateNonLODTextures = true;
  98961. lodTextures = {};
  98962. }
  98963. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  98964. else if (engine.webGLVersion < 2) {
  98965. expandTexture = false;
  98966. }
  98967. // If half float available we can uncompress the texture
  98968. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  98969. expandTexture = true;
  98970. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98971. }
  98972. // If full float available we can uncompress the texture
  98973. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  98974. expandTexture = true;
  98975. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98976. }
  98977. // Expand the texture if possible
  98978. if (expandTexture) {
  98979. // Simply run through the decode PP
  98980. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  98981. texture._isRGBD = false;
  98982. texture.invertY = false;
  98983. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  98984. generateDepthBuffer: false,
  98985. generateMipMaps: true,
  98986. generateStencilBuffer: false,
  98987. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  98988. type: texture.type,
  98989. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  98990. });
  98991. }
  98992. else {
  98993. texture._isRGBD = true;
  98994. texture.invertY = true;
  98995. // In case of missing support, applies the same patch than DDS files.
  98996. if (generateNonLODTextures) {
  98997. var mipSlices = 3;
  98998. var scale = texture._lodGenerationScale;
  98999. var offset = texture._lodGenerationOffset;
  99000. for (var i = 0; i < mipSlices; i++) {
  99001. //compute LOD from even spacing in smoothness (matching shader calculation)
  99002. var smoothness = i / (mipSlices - 1);
  99003. var roughness = 1 - smoothness;
  99004. var minLODIndex = offset; // roughness = 0
  99005. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  99006. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  99007. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  99008. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  99009. glTextureFromLod.isCube = true;
  99010. glTextureFromLod.invertY = true;
  99011. glTextureFromLod.generateMipMaps = false;
  99012. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  99013. // Wrap in a base texture for easy binding.
  99014. var lodTexture = new BABYLON.BaseTexture(null);
  99015. lodTexture.isCube = true;
  99016. lodTexture._texture = glTextureFromLod;
  99017. lodTextures[mipmapIndex] = lodTexture;
  99018. switch (i) {
  99019. case 0:
  99020. texture._lodTextureLow = lodTexture;
  99021. break;
  99022. case 1:
  99023. texture._lodTextureMid = lodTexture;
  99024. break;
  99025. case 2:
  99026. texture._lodTextureHigh = lodTexture;
  99027. break;
  99028. }
  99029. }
  99030. }
  99031. }
  99032. var promises = [];
  99033. var _loop_3 = function (i) {
  99034. var _loop_4 = function (face) {
  99035. // Constructs an image element from image data
  99036. var bytes = imageData[i][face];
  99037. var blob = new Blob([bytes], { type: 'image/png' });
  99038. var url = URL.createObjectURL(blob);
  99039. var image = new Image();
  99040. image.src = url;
  99041. // Enqueue promise to upload to the texture.
  99042. var promise = new Promise(function (resolve, reject) {
  99043. image.onload = function () {
  99044. if (expandTexture) {
  99045. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  99046. reject(message);
  99047. }, image);
  99048. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  99049. // Uncompress the data to a RTT
  99050. rgbdPostProcess.onApply = function (effect) {
  99051. effect._bindTexture("textureSampler", tempTexture_1);
  99052. effect.setFloat2("scale", 1, 1);
  99053. };
  99054. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  99055. // Cleanup
  99056. engine.restoreDefaultFramebuffer();
  99057. tempTexture_1.dispose();
  99058. window.URL.revokeObjectURL(url);
  99059. resolve();
  99060. });
  99061. }
  99062. else {
  99063. engine._uploadImageToTexture(texture, image, face, i);
  99064. // Upload the face to the non lod texture support
  99065. if (generateNonLODTextures) {
  99066. var lodTexture = lodTextures[i];
  99067. if (lodTexture) {
  99068. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  99069. }
  99070. }
  99071. resolve();
  99072. }
  99073. };
  99074. image.onerror = function (error) {
  99075. reject(error);
  99076. };
  99077. });
  99078. promises.push(promise);
  99079. };
  99080. // All faces
  99081. for (var face = 0; face < 6; face++) {
  99082. _loop_4(face);
  99083. }
  99084. };
  99085. // All mipmaps up to provided number of images
  99086. for (var i = 0; i < imageData.length; i++) {
  99087. _loop_3(i);
  99088. }
  99089. // Fill remaining mipmaps with black textures.
  99090. if (imageData.length < mipmapsCount) {
  99091. var data = void 0;
  99092. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  99093. var dataLength = size * size * 4;
  99094. switch (texture.type) {
  99095. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  99096. data = new Uint8Array(dataLength);
  99097. break;
  99098. }
  99099. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  99100. data = new Uint16Array(dataLength);
  99101. break;
  99102. }
  99103. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  99104. data = new Float32Array(dataLength);
  99105. break;
  99106. }
  99107. }
  99108. for (var i = imageData.length; i < mipmapsCount; i++) {
  99109. for (var face = 0; face < 6; face++) {
  99110. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  99111. }
  99112. }
  99113. }
  99114. // Once all done, finishes the cleanup and return
  99115. return Promise.all(promises).then(function () {
  99116. // Release temp RTT.
  99117. if (cubeRtt) {
  99118. engine._releaseFramebufferObjects(cubeRtt);
  99119. cubeRtt._swapAndDie(texture);
  99120. }
  99121. // Release temp Post Process.
  99122. if (rgbdPostProcess) {
  99123. rgbdPostProcess.dispose();
  99124. }
  99125. // Flag internal texture as ready in case they are in use.
  99126. if (generateNonLODTextures) {
  99127. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  99128. texture._lodTextureHigh._texture.isReady = true;
  99129. }
  99130. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  99131. texture._lodTextureMid._texture.isReady = true;
  99132. }
  99133. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  99134. texture._lodTextureLow._texture.isReady = true;
  99135. }
  99136. }
  99137. });
  99138. };
  99139. /**
  99140. * Uploads spherical polynomials information to the texture.
  99141. * @param texture defines the texture we are trying to upload the information to
  99142. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  99143. */
  99144. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  99145. if (info.version !== 1) {
  99146. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  99147. }
  99148. var irradianceInfo = info.irradiance;
  99149. if (!irradianceInfo) {
  99150. return;
  99151. }
  99152. var sp = new BABYLON.SphericalPolynomial();
  99153. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  99154. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  99155. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  99156. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  99157. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  99158. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  99159. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  99160. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  99161. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  99162. texture._sphericalPolynomial = sp;
  99163. };
  99164. /**
  99165. * Magic number identifying the env file.
  99166. */
  99167. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  99168. return EnvironmentTextureTools;
  99169. }());
  99170. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  99171. })(BABYLON || (BABYLON = {}));
  99172. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  99173. var BABYLON;
  99174. (function (BABYLON) {
  99175. /**
  99176. * Implementation of the ENV Texture Loader.
  99177. */
  99178. var ENVTextureLoader = /** @class */ (function () {
  99179. function ENVTextureLoader() {
  99180. /**
  99181. * Defines wether the loader supports cascade loading the different faces.
  99182. */
  99183. this.supportCascades = false;
  99184. }
  99185. /**
  99186. * This returns if the loader support the current file information.
  99187. * @param extension defines the file extension of the file being loaded
  99188. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99189. * @param fallback defines the fallback internal texture if any
  99190. * @param isBase64 defines whether the texture is encoded as a base64
  99191. * @param isBuffer defines whether the texture data are stored as a buffer
  99192. * @returns true if the loader can load the specified file
  99193. */
  99194. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99195. return extension.indexOf(".env") === 0;
  99196. };
  99197. /**
  99198. * Transform the url before loading if required.
  99199. * @param rootUrl the url of the texture
  99200. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99201. * @returns the transformed texture
  99202. */
  99203. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99204. return rootUrl;
  99205. };
  99206. /**
  99207. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99208. * @param rootUrl the url of the texture
  99209. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99210. * @returns the fallback texture
  99211. */
  99212. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99213. return null;
  99214. };
  99215. /**
  99216. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99217. * @param data contains the texture data
  99218. * @param texture defines the BabylonJS internal texture
  99219. * @param createPolynomials will be true if polynomials have been requested
  99220. * @param onLoad defines the callback to trigger once the texture is ready
  99221. * @param onError defines the callback to trigger in case of error
  99222. */
  99223. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99224. if (Array.isArray(data)) {
  99225. return;
  99226. }
  99227. data = data;
  99228. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  99229. if (info) {
  99230. texture.width = info.width;
  99231. texture.height = info.width;
  99232. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  99233. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  99234. texture.isReady = true;
  99235. if (onLoad) {
  99236. onLoad();
  99237. }
  99238. });
  99239. }
  99240. else if (onError) {
  99241. onError("Can not parse the environment file", null);
  99242. }
  99243. };
  99244. /**
  99245. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99246. * @param data contains the texture data
  99247. * @param texture defines the BabylonJS internal texture
  99248. * @param callback defines the method to call once ready to upload
  99249. */
  99250. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  99251. throw ".env not supported in 2d.";
  99252. };
  99253. return ENVTextureLoader;
  99254. }());
  99255. // Register the loader.
  99256. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  99257. })(BABYLON || (BABYLON = {}));
  99258. //# sourceMappingURL=babylon.envTextureLoader.js.map
  99259. var BABYLON;
  99260. (function (BABYLON) {
  99261. /**
  99262. * Renders a layer on top of an existing scene
  99263. */
  99264. var UtilityLayerRenderer = /** @class */ (function () {
  99265. /**
  99266. * Instantiates a UtilityLayerRenderer
  99267. * @param originalScene the original scene that will be rendered on top of
  99268. */
  99269. function UtilityLayerRenderer(
  99270. /** the original scene that will be rendered on top of */
  99271. originalScene) {
  99272. var _this = this;
  99273. this.originalScene = originalScene;
  99274. this._pointerCaptures = {};
  99275. this._lastPointerEvents = {};
  99276. /**
  99277. * If the utility layer should automatically be rendered on top of existing scene
  99278. */
  99279. this.shouldRender = true;
  99280. /**
  99281. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  99282. */
  99283. this.onlyCheckPointerDownEvents = true;
  99284. /**
  99285. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  99286. */
  99287. this.processAllEvents = false;
  99288. /**
  99289. * Observable raised when the pointer move from the utility layer scene to the main scene
  99290. */
  99291. this.onPointerOutObservable = new BABYLON.Observable();
  99292. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  99293. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  99294. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  99295. this.utilityLayerScene._allowPostProcessClearColor = false;
  99296. originalScene.getEngine().scenes.pop();
  99297. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  99298. this.utilityLayerScene.detachControl();
  99299. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  99300. if (!_this.processAllEvents) {
  99301. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  99302. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  99303. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  99304. return;
  99305. }
  99306. }
  99307. var pointerEvent = (prePointerInfo.event);
  99308. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  99309. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99310. return;
  99311. }
  99312. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  99313. if (!prePointerInfo.ray && utilityScenePick) {
  99314. prePointerInfo.ray = utilityScenePick.ray;
  99315. }
  99316. // always fire the prepointer oversvable
  99317. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  99318. // allow every non pointer down event to flow to the utility layer
  99319. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  99320. if (!prePointerInfo.skipOnPointerObservable) {
  99321. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99322. }
  99323. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  99324. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99325. }
  99326. return;
  99327. }
  99328. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  99329. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  99330. if (utilityScenePick && utilityScenePick.hit) {
  99331. if (!prePointerInfo.skipOnPointerObservable) {
  99332. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99333. }
  99334. prePointerInfo.skipOnPointerObservable = true;
  99335. }
  99336. }
  99337. else {
  99338. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  99339. var pointerEvent_1 = (prePointerInfo.event);
  99340. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  99341. if (originalScenePick && utilityScenePick) {
  99342. // No pick in utility scene
  99343. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  99344. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99345. // We touched an utility mesh present in the main scene
  99346. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99347. prePointerInfo.skipOnPointerObservable = true;
  99348. }
  99349. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99350. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  99351. }
  99352. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99353. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99354. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99355. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99356. }
  99357. }
  99358. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  99359. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  99360. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  99361. // If a previous utility layer set this, do not unset this
  99362. if (!prePointerInfo.skipOnPointerObservable) {
  99363. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  99364. }
  99365. }
  99366. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  99367. // We have a pick in both scenes but main is closer than utility
  99368. // We touched an utility mesh present in the main scene
  99369. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99370. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99371. prePointerInfo.skipOnPointerObservable = true;
  99372. }
  99373. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99374. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99375. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99376. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99377. }
  99378. }
  99379. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  99380. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  99381. }
  99382. }
  99383. }
  99384. });
  99385. // Render directly on top of existing scene without clearing
  99386. this.utilityLayerScene.autoClear = false;
  99387. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  99388. if (_this.shouldRender) {
  99389. _this.render();
  99390. }
  99391. });
  99392. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  99393. _this.dispose();
  99394. });
  99395. this._updateCamera();
  99396. }
  99397. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  99398. /**
  99399. * 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)
  99400. */
  99401. get: function () {
  99402. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  99403. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99404. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99405. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99406. });
  99407. }
  99408. return UtilityLayerRenderer._DefaultUtilityLayer;
  99409. },
  99410. enumerable: true,
  99411. configurable: true
  99412. });
  99413. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  99414. /**
  99415. * 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)
  99416. */
  99417. get: function () {
  99418. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  99419. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99420. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  99421. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99422. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99423. });
  99424. }
  99425. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  99426. },
  99427. enumerable: true,
  99428. configurable: true
  99429. });
  99430. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  99431. if (!prePointerInfo.skipOnPointerObservable) {
  99432. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  99433. this._lastPointerEvents[pointerEvent.pointerId] = true;
  99434. }
  99435. };
  99436. /**
  99437. * Renders the utility layers scene on top of the original scene
  99438. */
  99439. UtilityLayerRenderer.prototype.render = function () {
  99440. this._updateCamera();
  99441. if (this.utilityLayerScene.activeCamera) {
  99442. // Set the camera's scene to utility layers scene
  99443. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  99444. var camera = this.utilityLayerScene.activeCamera;
  99445. camera._scene = this.utilityLayerScene;
  99446. if (camera.leftCamera) {
  99447. camera.leftCamera._scene = this.utilityLayerScene;
  99448. }
  99449. if (camera.rightCamera) {
  99450. camera.rightCamera._scene = this.utilityLayerScene;
  99451. }
  99452. this.utilityLayerScene.render(false);
  99453. // Reset camera's scene back to original
  99454. camera._scene = oldScene;
  99455. if (camera.leftCamera) {
  99456. camera.leftCamera._scene = oldScene;
  99457. }
  99458. if (camera.rightCamera) {
  99459. camera.rightCamera._scene = oldScene;
  99460. }
  99461. }
  99462. };
  99463. /**
  99464. * Disposes of the renderer
  99465. */
  99466. UtilityLayerRenderer.prototype.dispose = function () {
  99467. this.onPointerOutObservable.clear();
  99468. if (this._afterRenderObserver) {
  99469. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  99470. }
  99471. if (this._sceneDisposeObserver) {
  99472. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99473. }
  99474. if (this._originalPointerObserver) {
  99475. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  99476. }
  99477. this.utilityLayerScene.dispose();
  99478. };
  99479. UtilityLayerRenderer.prototype._updateCamera = function () {
  99480. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  99481. };
  99482. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99483. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99484. return UtilityLayerRenderer;
  99485. }());
  99486. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  99487. })(BABYLON || (BABYLON = {}));
  99488. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  99489. //# sourceMappingURL=babylon.behavior.js.map
  99490. var BABYLON;
  99491. (function (BABYLON) {
  99492. /**
  99493. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  99494. */
  99495. var PointerDragBehavior = /** @class */ (function () {
  99496. /**
  99497. * Creates a pointer drag behavior that can be attached to a mesh
  99498. * @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)
  99499. */
  99500. function PointerDragBehavior(options) {
  99501. /**
  99502. * 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)
  99503. */
  99504. this.maxDragAngle = 0;
  99505. /**
  99506. * @hidden
  99507. */
  99508. this._useAlternatePickedPointAboveMaxDragAngle = false;
  99509. /**
  99510. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99511. */
  99512. this.currentDraggingPointerID = -1;
  99513. /**
  99514. * If the behavior is currently in a dragging state
  99515. */
  99516. this.dragging = false;
  99517. /**
  99518. * 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)
  99519. */
  99520. this.dragDeltaRatio = 0.2;
  99521. /**
  99522. * If the drag plane orientation should be updated during the dragging (Default: true)
  99523. */
  99524. this.updateDragPlane = true;
  99525. // Debug mode will display drag planes to help visualize behavior
  99526. this._debugMode = false;
  99527. this._moving = false;
  99528. /**
  99529. * Fires each time the attached mesh is dragged with the pointer
  99530. * * delta between last drag position and current drag position in world space
  99531. * * dragDistance along the drag axis
  99532. * * dragPlaneNormal normal of the current drag plane used during the drag
  99533. * * dragPlanePoint in world space where the drag intersects the drag plane
  99534. */
  99535. this.onDragObservable = new BABYLON.Observable();
  99536. /**
  99537. * Fires each time a drag begins (eg. mouse down on mesh)
  99538. */
  99539. this.onDragStartObservable = new BABYLON.Observable();
  99540. /**
  99541. * Fires each time a drag ends (eg. mouse release after drag)
  99542. */
  99543. this.onDragEndObservable = new BABYLON.Observable();
  99544. /**
  99545. * If the attached mesh should be moved when dragged
  99546. */
  99547. this.moveAttached = true;
  99548. /**
  99549. * If the drag behavior will react to drag events (Default: true)
  99550. */
  99551. this.enabled = true;
  99552. /**
  99553. * If camera controls should be detached during the drag
  99554. */
  99555. this.detachCameraControls = true;
  99556. /**
  99557. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  99558. */
  99559. this.useObjectOrienationForDragging = true;
  99560. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99561. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  99562. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  99563. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99564. this._attachedElement = null;
  99565. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99566. this._lastPointerRay = {};
  99567. this._dragDelta = new BABYLON.Vector3();
  99568. // Variables to avoid instantiation in the below method
  99569. this._pointA = new BABYLON.Vector3(0, 0, 0);
  99570. this._pointB = new BABYLON.Vector3(0, 0, 0);
  99571. this._pointC = new BABYLON.Vector3(0, 0, 0);
  99572. this._lineA = new BABYLON.Vector3(0, 0, 0);
  99573. this._lineB = new BABYLON.Vector3(0, 0, 0);
  99574. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  99575. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  99576. this._options = options ? options : {};
  99577. var optionCount = 0;
  99578. if (this._options.dragAxis) {
  99579. optionCount++;
  99580. }
  99581. if (this._options.dragPlaneNormal) {
  99582. optionCount++;
  99583. }
  99584. if (optionCount > 1) {
  99585. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  99586. }
  99587. }
  99588. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  99589. /**
  99590. * The name of the behavior
  99591. */
  99592. get: function () {
  99593. return "PointerDrag";
  99594. },
  99595. enumerable: true,
  99596. configurable: true
  99597. });
  99598. /**
  99599. * Initializes the behavior
  99600. */
  99601. PointerDragBehavior.prototype.init = function () { };
  99602. /**
  99603. * Attaches the drag behavior the passed in mesh
  99604. * @param ownerNode The mesh that will be dragged around once attached
  99605. */
  99606. PointerDragBehavior.prototype.attach = function (ownerNode) {
  99607. var _this = this;
  99608. this._scene = ownerNode.getScene();
  99609. this._attachedNode = ownerNode;
  99610. // Initialize drag plane to not interfere with existing scene
  99611. if (!PointerDragBehavior._planeScene) {
  99612. if (this._debugMode) {
  99613. PointerDragBehavior._planeScene = this._scene;
  99614. }
  99615. else {
  99616. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  99617. PointerDragBehavior._planeScene.detachControl();
  99618. this._scene.getEngine().scenes.pop();
  99619. this._scene.onDisposeObservable.addOnce(function () {
  99620. PointerDragBehavior._planeScene.dispose();
  99621. PointerDragBehavior._planeScene = null;
  99622. });
  99623. }
  99624. }
  99625. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  99626. // State of the drag
  99627. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  99628. var pickPredicate = function (m) {
  99629. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  99630. };
  99631. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99632. if (!_this.enabled) {
  99633. return;
  99634. }
  99635. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99636. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99637. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  99638. }
  99639. }
  99640. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99641. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99642. _this.releaseDrag();
  99643. }
  99644. }
  99645. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99646. var pointerId = pointerInfo.event.pointerId;
  99647. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  99648. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  99649. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  99650. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  99651. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  99652. }
  99653. _this.currentDraggingPointerID = pointerId;
  99654. }
  99655. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  99656. if (!_this._lastPointerRay[pointerId]) {
  99657. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99658. }
  99659. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  99660. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  99661. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  99662. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  99663. _this._moveDrag(pointerInfo.pickInfo.ray);
  99664. }
  99665. }
  99666. }
  99667. });
  99668. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99669. if (_this._moving && _this.moveAttached) {
  99670. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  99671. // Slowly move mesh to avoid jitter
  99672. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  99673. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  99674. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  99675. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  99676. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  99677. }
  99678. });
  99679. };
  99680. /**
  99681. * Force relase the drag action by code.
  99682. */
  99683. PointerDragBehavior.prototype.releaseDrag = function () {
  99684. this.dragging = false;
  99685. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  99686. this.currentDraggingPointerID = -1;
  99687. this._moving = false;
  99688. // Reattach camera controls
  99689. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99690. this._scene.activeCamera.attachControl(this._attachedElement, true);
  99691. }
  99692. };
  99693. /**
  99694. * Simulates the start of a pointer drag event on the behavior
  99695. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  99696. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  99697. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  99698. */
  99699. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  99700. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  99701. this._startDrag(pointerId, fromRay, startPickedPoint);
  99702. var lastRay = this._lastPointerRay[pointerId];
  99703. if (pointerId === PointerDragBehavior._AnyMouseID) {
  99704. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  99705. }
  99706. if (lastRay) {
  99707. // if there was a last pointer ray drag the object there
  99708. this._moveDrag(lastRay);
  99709. }
  99710. };
  99711. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  99712. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  99713. return;
  99714. }
  99715. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  99716. // Create start ray from the camera to the object
  99717. if (fromRay) {
  99718. this._startDragRay.direction.copyFrom(fromRay.direction);
  99719. this._startDragRay.origin.copyFrom(fromRay.origin);
  99720. }
  99721. else {
  99722. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  99723. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  99724. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  99725. }
  99726. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  99727. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  99728. if (pickedPoint) {
  99729. this.dragging = true;
  99730. this.currentDraggingPointerID = pointerId;
  99731. this.lastDragPosition.copyFrom(pickedPoint);
  99732. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  99733. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  99734. // Detatch camera controls
  99735. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99736. if (this._scene.activeCamera.inputs.attachedElement) {
  99737. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  99738. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  99739. }
  99740. else {
  99741. this._attachedElement = null;
  99742. }
  99743. }
  99744. }
  99745. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  99746. };
  99747. PointerDragBehavior.prototype._moveDrag = function (ray) {
  99748. this._moving = true;
  99749. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  99750. if (pickedPoint) {
  99751. if (this.updateDragPlane) {
  99752. this._updateDragPlanePosition(ray, pickedPoint);
  99753. }
  99754. var dragLength = 0;
  99755. // depending on the drag mode option drag accordingly
  99756. if (this._options.dragAxis) {
  99757. // Convert local drag axis to world
  99758. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  99759. // Project delta drag from the drag plane onto the drag axis
  99760. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  99761. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  99762. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  99763. }
  99764. else {
  99765. dragLength = this._dragDelta.length();
  99766. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  99767. }
  99768. this._targetPosition.addInPlace(this._dragDelta);
  99769. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  99770. this.lastDragPosition.copyFrom(pickedPoint);
  99771. }
  99772. };
  99773. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  99774. var _this = this;
  99775. if (!ray) {
  99776. return null;
  99777. }
  99778. // Calculate angle between plane normal and ray
  99779. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  99780. // Correct if ray is casted from oposite side
  99781. if (angle > Math.PI / 2) {
  99782. angle = Math.PI - angle;
  99783. }
  99784. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  99785. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  99786. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  99787. // Invert ray direction along the towards object axis
  99788. this._tmpVector.copyFrom(ray.direction);
  99789. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  99790. this._alternatePickedPoint.normalize();
  99791. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  99792. this._tmpVector.addInPlace(this._alternatePickedPoint);
  99793. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  99794. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  99795. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  99796. this._alternatePickedPoint.addInPlace(this._tmpVector);
  99797. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  99798. return this._alternatePickedPoint;
  99799. }
  99800. else {
  99801. return null;
  99802. }
  99803. }
  99804. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  99805. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  99806. return pickResult.pickedPoint;
  99807. }
  99808. else {
  99809. return null;
  99810. }
  99811. };
  99812. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  99813. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  99814. this._pointA.copyFrom(dragPlanePosition);
  99815. if (this._options.dragAxis) {
  99816. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  99817. // Calculate plane normal in direction of camera but perpendicular to drag axis
  99818. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  99819. ray.origin.subtractToRef(this._pointA, this._pointC);
  99820. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  99821. // Get perpendicular line from direction to camera and drag axis
  99822. this._pointB.subtractToRef(this._pointA, this._lineA);
  99823. this._pointC.subtractToRef(this._pointA, this._lineB);
  99824. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  99825. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  99826. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  99827. this._lookAt.normalize();
  99828. this._dragPlane.position.copyFrom(this._pointA);
  99829. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  99830. this._dragPlane.lookAt(this._lookAt);
  99831. }
  99832. else if (this._options.dragPlaneNormal) {
  99833. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  99834. this._dragPlane.position.copyFrom(this._pointA);
  99835. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  99836. this._dragPlane.lookAt(this._lookAt);
  99837. }
  99838. else {
  99839. this._dragPlane.position.copyFrom(this._pointA);
  99840. this._dragPlane.lookAt(ray.origin);
  99841. }
  99842. this._dragPlane.computeWorldMatrix(true);
  99843. };
  99844. /**
  99845. * Detaches the behavior from the mesh
  99846. */
  99847. PointerDragBehavior.prototype.detach = function () {
  99848. if (this._pointerObserver) {
  99849. this._scene.onPointerObservable.remove(this._pointerObserver);
  99850. }
  99851. if (this._beforeRenderObserver) {
  99852. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  99853. }
  99854. };
  99855. PointerDragBehavior._AnyMouseID = -2;
  99856. return PointerDragBehavior;
  99857. }());
  99858. BABYLON.PointerDragBehavior = PointerDragBehavior;
  99859. })(BABYLON || (BABYLON = {}));
  99860. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  99861. var BABYLON;
  99862. (function (BABYLON) {
  99863. /**
  99864. * A behavior that when attached to a mesh will allow the mesh to be scaled
  99865. */
  99866. var MultiPointerScaleBehavior = /** @class */ (function () {
  99867. /**
  99868. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  99869. */
  99870. function MultiPointerScaleBehavior() {
  99871. this._startDistance = 0;
  99872. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  99873. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  99874. this._sceneRenderObserver = null;
  99875. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  99876. this._dragBehaviorA.moveAttached = false;
  99877. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  99878. this._dragBehaviorB.moveAttached = false;
  99879. }
  99880. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  99881. /**
  99882. * The name of the behavior
  99883. */
  99884. get: function () {
  99885. return "MultiPointerScale";
  99886. },
  99887. enumerable: true,
  99888. configurable: true
  99889. });
  99890. /**
  99891. * Initializes the behavior
  99892. */
  99893. MultiPointerScaleBehavior.prototype.init = function () { };
  99894. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  99895. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  99896. };
  99897. /**
  99898. * Attaches the scale behavior the passed in mesh
  99899. * @param ownerNode The mesh that will be scaled around once attached
  99900. */
  99901. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  99902. var _this = this;
  99903. this._ownerNode = ownerNode;
  99904. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  99905. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  99906. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99907. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99908. _this._dragBehaviorA.releaseDrag();
  99909. }
  99910. else {
  99911. _this._initialScale.copyFrom(ownerNode.scaling);
  99912. _this._startDistance = _this._getCurrentDistance();
  99913. }
  99914. }
  99915. });
  99916. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  99917. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99918. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99919. _this._dragBehaviorB.releaseDrag();
  99920. }
  99921. else {
  99922. _this._initialScale.copyFrom(ownerNode.scaling);
  99923. _this._startDistance = _this._getCurrentDistance();
  99924. }
  99925. }
  99926. });
  99927. // Once both drag behaviors are active scale based on the distance between the two pointers
  99928. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99929. behavior.onDragObservable.add(function () {
  99930. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99931. var ratio = _this._getCurrentDistance() / _this._startDistance;
  99932. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  99933. }
  99934. });
  99935. });
  99936. ownerNode.addBehavior(this._dragBehaviorA);
  99937. ownerNode.addBehavior(this._dragBehaviorB);
  99938. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99939. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99940. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99941. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  99942. if (change.length() > 0.01) {
  99943. ownerNode.scaling.addInPlace(change);
  99944. }
  99945. }
  99946. });
  99947. };
  99948. /**
  99949. * Detaches the behavior from the mesh
  99950. */
  99951. MultiPointerScaleBehavior.prototype.detach = function () {
  99952. var _this = this;
  99953. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99954. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99955. behavior.onDragStartObservable.clear();
  99956. behavior.onDragObservable.clear();
  99957. _this._ownerNode.removeBehavior(behavior);
  99958. });
  99959. };
  99960. return MultiPointerScaleBehavior;
  99961. }());
  99962. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  99963. })(BABYLON || (BABYLON = {}));
  99964. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  99965. var BABYLON;
  99966. (function (BABYLON) {
  99967. /**
  99968. * 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
  99969. */
  99970. var SixDofDragBehavior = /** @class */ (function () {
  99971. /**
  99972. * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  99973. */
  99974. function SixDofDragBehavior() {
  99975. this._sceneRenderObserver = null;
  99976. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99977. this._moving = false;
  99978. this._startingOrientation = new BABYLON.Quaternion();
  99979. /**
  99980. * 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)
  99981. */
  99982. this.zDragFactor = 3;
  99983. /**
  99984. * If the behavior is currently in a dragging state
  99985. */
  99986. this.dragging = false;
  99987. /**
  99988. * 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)
  99989. */
  99990. this.dragDeltaRatio = 0.2;
  99991. /**
  99992. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99993. */
  99994. this.currentDraggingPointerID = -1;
  99995. /**
  99996. * If camera controls should be detached during the drag
  99997. */
  99998. this.detachCameraControls = true;
  99999. /**
  100000. * Fires each time a drag starts
  100001. */
  100002. this.onDragStartObservable = new BABYLON.Observable();
  100003. /**
  100004. * Fires each time a drag ends (eg. mouse release after drag)
  100005. */
  100006. this.onDragEndObservable = new BABYLON.Observable();
  100007. }
  100008. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  100009. /**
  100010. * The name of the behavior
  100011. */
  100012. get: function () {
  100013. return "SixDofDrag";
  100014. },
  100015. enumerable: true,
  100016. configurable: true
  100017. });
  100018. /**
  100019. * Initializes the behavior
  100020. */
  100021. SixDofDragBehavior.prototype.init = function () { };
  100022. /**
  100023. * Attaches the scale behavior the passed in mesh
  100024. * @param ownerNode The mesh that will be scaled around once attached
  100025. */
  100026. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  100027. var _this = this;
  100028. this._ownerNode = ownerNode;
  100029. this._scene = this._ownerNode.getScene();
  100030. if (!SixDofDragBehavior._virtualScene) {
  100031. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  100032. this._scene.getEngine().scenes.pop();
  100033. }
  100034. var pickedMesh = null;
  100035. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  100036. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  100037. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  100038. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  100039. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  100040. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  100041. var pickPredicate = function (m) {
  100042. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  100043. };
  100044. var attachedElement = null;
  100045. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  100046. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100047. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  100048. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  100049. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  100050. }
  100051. pickedMesh = _this._ownerNode;
  100052. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  100053. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  100054. // Set position and orientation of the controller
  100055. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  100056. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  100057. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  100058. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100059. pickedMesh.computeWorldMatrix();
  100060. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  100061. if (!pickedMesh.rotationQuaternion) {
  100062. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  100063. }
  100064. var oldParent = pickedMesh.parent;
  100065. pickedMesh.setParent(null);
  100066. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  100067. pickedMesh.setParent(oldParent);
  100068. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  100069. // Update state
  100070. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  100071. _this.dragging = true;
  100072. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  100073. // Detatch camera controls
  100074. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  100075. if (_this._scene.activeCamera.inputs.attachedElement) {
  100076. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  100077. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  100078. }
  100079. else {
  100080. attachedElement = null;
  100081. }
  100082. }
  100083. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  100084. _this.onDragStartObservable.notifyObservers({});
  100085. }
  100086. }
  100087. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  100088. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  100089. _this.dragging = false;
  100090. _this._moving = false;
  100091. _this.currentDraggingPointerID = -1;
  100092. pickedMesh = null;
  100093. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100094. // Reattach camera controls
  100095. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  100096. _this._scene.activeCamera.attachControl(attachedElement, true);
  100097. }
  100098. _this.onDragEndObservable.notifyObservers({});
  100099. }
  100100. }
  100101. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  100102. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  100103. var zDragFactor = _this.zDragFactor;
  100104. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  100105. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  100106. zDragFactor = 0;
  100107. }
  100108. // Calculate controller drag distance in controller space
  100109. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  100110. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  100111. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  100112. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  100113. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  100114. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  100115. if (_this._virtualDragMesh.position.z < 0) {
  100116. _this._virtualDragMesh.position.z = 0;
  100117. }
  100118. // Update the controller position
  100119. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  100120. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  100121. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  100122. // Move the virtualObjectsPosition into the picked mesh's space if needed
  100123. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  100124. if (pickedMesh.parent) {
  100125. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  100126. }
  100127. if (!_this._moving) {
  100128. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  100129. }
  100130. _this._moving = true;
  100131. }
  100132. }
  100133. });
  100134. var tmpQuaternion = new BABYLON.Quaternion();
  100135. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  100136. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  100137. if (_this.dragging && _this._moving && pickedMesh) {
  100138. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  100139. // Slowly move mesh to avoid jitter
  100140. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  100141. // Get change in rotation
  100142. tmpQuaternion.copyFrom(_this._startingOrientation);
  100143. tmpQuaternion.x = -tmpQuaternion.x;
  100144. tmpQuaternion.y = -tmpQuaternion.y;
  100145. tmpQuaternion.z = -tmpQuaternion.z;
  100146. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  100147. // Convert change in rotation to only y axis rotation
  100148. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  100149. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  100150. // Slowly move mesh to avoid jitter
  100151. var oldParent = pickedMesh.parent;
  100152. pickedMesh.setParent(null);
  100153. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  100154. pickedMesh.setParent(oldParent);
  100155. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  100156. }
  100157. });
  100158. };
  100159. /**
  100160. * Detaches the behavior from the mesh
  100161. */
  100162. SixDofDragBehavior.prototype.detach = function () {
  100163. if (this._scene) {
  100164. this._scene.onPointerObservable.remove(this._pointerObserver);
  100165. }
  100166. if (this._ownerNode) {
  100167. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  100168. }
  100169. if (this._virtualOriginMesh) {
  100170. this._virtualOriginMesh.dispose();
  100171. }
  100172. if (this._virtualDragMesh) {
  100173. this._virtualDragMesh.dispose();
  100174. }
  100175. this.onDragEndObservable.clear();
  100176. this.onDragStartObservable.clear();
  100177. };
  100178. return SixDofDragBehavior;
  100179. }());
  100180. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  100181. })(BABYLON || (BABYLON = {}));
  100182. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  100183. var BABYLON;
  100184. (function (BABYLON) {
  100185. /**
  100186. * @hidden
  100187. */
  100188. var FaceDirectionInfo = /** @class */ (function () {
  100189. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  100190. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  100191. if (diff === void 0) { diff = 0; }
  100192. if (ignore === void 0) { ignore = false; }
  100193. this.direction = direction;
  100194. this.rotatedDirection = rotatedDirection;
  100195. this.diff = diff;
  100196. this.ignore = ignore;
  100197. }
  100198. return FaceDirectionInfo;
  100199. }());
  100200. /**
  100201. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  100202. */
  100203. var AttachToBoxBehavior = /** @class */ (function () {
  100204. /**
  100205. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  100206. * @param ui The transform node that should be attched to the mesh
  100207. */
  100208. function AttachToBoxBehavior(ui) {
  100209. this.ui = ui;
  100210. /**
  100211. * The name of the behavior
  100212. */
  100213. this.name = "AttachToBoxBehavior";
  100214. /**
  100215. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  100216. */
  100217. this.distanceAwayFromFace = 0.15;
  100218. /**
  100219. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  100220. */
  100221. this.distanceAwayFromBottomOfFace = 0.15;
  100222. 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))];
  100223. this._tmpMatrix = new BABYLON.Matrix();
  100224. this._tmpVector = new BABYLON.Vector3();
  100225. this._zeroVector = BABYLON.Vector3.Zero();
  100226. this._lookAtTmpMatrix = new BABYLON.Matrix();
  100227. /* Does nothing */
  100228. }
  100229. /**
  100230. * Initializes the behavior
  100231. */
  100232. AttachToBoxBehavior.prototype.init = function () {
  100233. /* Does nothing */
  100234. };
  100235. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  100236. var _this = this;
  100237. // Go over each face and calculate the angle between the face's normal and targetDirection
  100238. this._faceVectors.forEach(function (v) {
  100239. if (!_this._target.rotationQuaternion) {
  100240. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  100241. }
  100242. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  100243. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  100244. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  100245. });
  100246. // Return the face information of the one with the normal closeset to target direction
  100247. return this._faceVectors.reduce(function (min, p) {
  100248. if (min.ignore) {
  100249. return p;
  100250. }
  100251. else if (p.ignore) {
  100252. return min;
  100253. }
  100254. else {
  100255. return min.diff < p.diff ? min : p;
  100256. }
  100257. }, this._faceVectors[0]);
  100258. };
  100259. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  100260. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  100261. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  100262. this._lookAtTmpMatrix.invert();
  100263. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  100264. };
  100265. /**
  100266. * Attaches the AttachToBoxBehavior to the passed in mesh
  100267. * @param target The mesh that the specified node will be attached to
  100268. */
  100269. AttachToBoxBehavior.prototype.attach = function (target) {
  100270. var _this = this;
  100271. this._target = target;
  100272. this._scene = this._target.getScene();
  100273. // Every frame, update the app bars position
  100274. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  100275. if (!_this._scene.activeCamera) {
  100276. return;
  100277. }
  100278. // Find the face closest to the cameras position
  100279. var cameraPos = _this._scene.activeCamera.position;
  100280. if (_this._scene.activeCamera.devicePosition) {
  100281. cameraPos = _this._scene.activeCamera.devicePosition;
  100282. }
  100283. var facing = _this._closestFace(cameraPos.subtract(target.position));
  100284. if (_this._scene.activeCamera.leftCamera) {
  100285. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  100286. }
  100287. else {
  100288. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  100289. }
  100290. // Get camera up direction
  100291. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  100292. // Ignore faces to not select a parrelel face for the up vector of the UI
  100293. _this._faceVectors.forEach(function (v) {
  100294. if (facing.direction.x && v.direction.x) {
  100295. v.ignore = true;
  100296. }
  100297. if (facing.direction.y && v.direction.y) {
  100298. v.ignore = true;
  100299. }
  100300. if (facing.direction.z && v.direction.z) {
  100301. v.ignore = true;
  100302. }
  100303. });
  100304. var facingUp = _this._closestFace(_this._tmpVector);
  100305. // Unignore faces
  100306. _this._faceVectors.forEach(function (v) {
  100307. v.ignore = false;
  100308. });
  100309. // Position the app bar on that face
  100310. _this.ui.position.copyFrom(target.position);
  100311. if (facing.direction.x) {
  100312. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100313. _this.ui.position.addInPlace(_this._tmpVector);
  100314. }
  100315. if (facing.direction.y) {
  100316. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100317. _this.ui.position.addInPlace(_this._tmpVector);
  100318. }
  100319. if (facing.direction.z) {
  100320. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100321. _this.ui.position.addInPlace(_this._tmpVector);
  100322. }
  100323. // Rotate to be oriented properly to the camera
  100324. if (!_this.ui.rotationQuaternion) {
  100325. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  100326. }
  100327. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  100328. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  100329. // Place ui the correct distance from the bottom of the mesh
  100330. if (facingUp.direction.x) {
  100331. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  100332. }
  100333. if (facingUp.direction.y) {
  100334. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  100335. }
  100336. if (facingUp.direction.z) {
  100337. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  100338. }
  100339. _this.ui.position.addInPlace(_this._tmpVector);
  100340. });
  100341. };
  100342. /**
  100343. * Detaches the behavior from the mesh
  100344. */
  100345. AttachToBoxBehavior.prototype.detach = function () {
  100346. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  100347. };
  100348. return AttachToBoxBehavior;
  100349. }());
  100350. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  100351. })(BABYLON || (BABYLON = {}));
  100352. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  100353. var BABYLON;
  100354. (function (BABYLON) {
  100355. /**
  100356. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  100357. */
  100358. var FadeInOutBehavior = /** @class */ (function () {
  100359. /**
  100360. * Instatiates the FadeInOutBehavior
  100361. */
  100362. function FadeInOutBehavior() {
  100363. var _this = this;
  100364. /**
  100365. * Time in milliseconds to delay before fading in (Default: 0)
  100366. */
  100367. this.delay = 0;
  100368. /**
  100369. * Time in milliseconds for the mesh to fade in (Default: 300)
  100370. */
  100371. this.fadeInTime = 300;
  100372. this._millisecondsPerFrame = 1000 / 60;
  100373. this._hovered = false;
  100374. this._hoverValue = 0;
  100375. this._ownerNode = null;
  100376. this._update = function () {
  100377. if (_this._ownerNode) {
  100378. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  100379. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  100380. if (_this._ownerNode.visibility > 1) {
  100381. _this._setAllVisibility(_this._ownerNode, 1);
  100382. _this._hoverValue = _this.fadeInTime + _this.delay;
  100383. return;
  100384. }
  100385. else if (_this._ownerNode.visibility < 0) {
  100386. _this._setAllVisibility(_this._ownerNode, 0);
  100387. if (_this._hoverValue < 0) {
  100388. _this._hoverValue = 0;
  100389. return;
  100390. }
  100391. }
  100392. setTimeout(_this._update, _this._millisecondsPerFrame);
  100393. }
  100394. };
  100395. }
  100396. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  100397. /**
  100398. * The name of the behavior
  100399. */
  100400. get: function () {
  100401. return "FadeInOut";
  100402. },
  100403. enumerable: true,
  100404. configurable: true
  100405. });
  100406. /**
  100407. * Initializes the behavior
  100408. */
  100409. FadeInOutBehavior.prototype.init = function () {
  100410. };
  100411. /**
  100412. * Attaches the fade behavior on the passed in mesh
  100413. * @param ownerNode The mesh that will be faded in/out once attached
  100414. */
  100415. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  100416. this._ownerNode = ownerNode;
  100417. this._setAllVisibility(this._ownerNode, 0);
  100418. };
  100419. /**
  100420. * Detaches the behavior from the mesh
  100421. */
  100422. FadeInOutBehavior.prototype.detach = function () {
  100423. this._ownerNode = null;
  100424. };
  100425. /**
  100426. * Triggers the mesh to begin fading in or out
  100427. * @param value if the object should fade in or out (true to fade in)
  100428. */
  100429. FadeInOutBehavior.prototype.fadeIn = function (value) {
  100430. this._hovered = value;
  100431. this._update();
  100432. };
  100433. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  100434. var _this = this;
  100435. mesh.visibility = value;
  100436. mesh.getChildMeshes().forEach(function (c) {
  100437. _this._setAllVisibility(c, value);
  100438. });
  100439. };
  100440. return FadeInOutBehavior;
  100441. }());
  100442. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  100443. })(BABYLON || (BABYLON = {}));
  100444. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  100445. var BABYLON;
  100446. (function (BABYLON) {
  100447. /**
  100448. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  100449. */
  100450. var Gizmo = /** @class */ (function () {
  100451. /**
  100452. * Creates a gizmo
  100453. * @param gizmoLayer The utility layer the gizmo will be added to
  100454. */
  100455. function Gizmo(
  100456. /** The utility layer the gizmo will be added to */
  100457. gizmoLayer) {
  100458. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100459. var _this = this;
  100460. this.gizmoLayer = gizmoLayer;
  100461. /**
  100462. * Ratio for the scale of the gizmo (Default: 1)
  100463. */
  100464. this.scaleRatio = 1;
  100465. this._tmpMatrix = new BABYLON.Matrix();
  100466. /**
  100467. * If a custom mesh has been set (Default: false)
  100468. */
  100469. this._customMeshSet = false;
  100470. /**
  100471. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  100472. */
  100473. this.updateGizmoRotationToMatchAttachedMesh = true;
  100474. /**
  100475. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  100476. */
  100477. this.updateGizmoPositionToMatchAttachedMesh = true;
  100478. /**
  100479. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  100480. */
  100481. this._updateScale = true;
  100482. this._interactionsEnabled = true;
  100483. this._tempVector = new BABYLON.Vector3();
  100484. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  100485. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  100486. _this._update();
  100487. });
  100488. this.attachedMesh = null;
  100489. }
  100490. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  100491. /**
  100492. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  100493. * * When set, interactions will be enabled
  100494. */
  100495. get: function () {
  100496. return this._attachedMesh;
  100497. },
  100498. set: function (value) {
  100499. this._attachedMesh = value;
  100500. this._rootMesh.setEnabled(value ? true : false);
  100501. this._attachedMeshChanged(value);
  100502. },
  100503. enumerable: true,
  100504. configurable: true
  100505. });
  100506. /**
  100507. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100508. * @param mesh The mesh to replace the default mesh of the gizmo
  100509. */
  100510. Gizmo.prototype.setCustomMesh = function (mesh) {
  100511. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  100512. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  100513. }
  100514. this._rootMesh.getChildMeshes().forEach(function (c) {
  100515. c.dispose();
  100516. });
  100517. mesh.parent = this._rootMesh;
  100518. this._customMeshSet = true;
  100519. };
  100520. Gizmo.prototype._attachedMeshChanged = function (value) {
  100521. };
  100522. /**
  100523. * @hidden
  100524. * Updates the gizmo to match the attached mesh's position/rotation
  100525. */
  100526. Gizmo.prototype._update = function () {
  100527. if (this.attachedMesh) {
  100528. if (this.updateGizmoRotationToMatchAttachedMesh) {
  100529. if (!this._rootMesh.rotationQuaternion) {
  100530. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  100531. }
  100532. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  100533. this._tempVector.copyFrom(this.attachedMesh.scaling);
  100534. if (this.attachedMesh.scaling.x < 0) {
  100535. this.attachedMesh.scaling.x *= -1;
  100536. }
  100537. if (this.attachedMesh.scaling.y < 0) {
  100538. this.attachedMesh.scaling.y *= -1;
  100539. }
  100540. if (this.attachedMesh.scaling.z < 0) {
  100541. this.attachedMesh.scaling.z *= -1;
  100542. }
  100543. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  100544. this.attachedMesh.scaling.copyFrom(this._tempVector);
  100545. this.attachedMesh.computeWorldMatrix();
  100546. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  100547. }
  100548. else if (this._rootMesh.rotationQuaternion) {
  100549. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  100550. }
  100551. if (this.updateGizmoPositionToMatchAttachedMesh) {
  100552. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  100553. }
  100554. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  100555. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  100556. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  100557. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  100558. }
  100559. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  100560. var dist = this._tempVector.length() * this.scaleRatio;
  100561. this._rootMesh.scaling.set(dist, dist, dist);
  100562. }
  100563. }
  100564. };
  100565. /**
  100566. * Disposes of the gizmo
  100567. */
  100568. Gizmo.prototype.dispose = function () {
  100569. this._rootMesh.dispose();
  100570. if (this._beforeRenderObserver) {
  100571. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  100572. }
  100573. };
  100574. return Gizmo;
  100575. }());
  100576. BABYLON.Gizmo = Gizmo;
  100577. })(BABYLON || (BABYLON = {}));
  100578. //# sourceMappingURL=babylon.gizmo.js.map
  100579. var BABYLON;
  100580. (function (BABYLON) {
  100581. /**
  100582. * Single axis drag gizmo
  100583. */
  100584. var AxisDragGizmo = /** @class */ (function (_super) {
  100585. __extends(AxisDragGizmo, _super);
  100586. /**
  100587. * Creates an AxisDragGizmo
  100588. * @param gizmoLayer The utility layer the gizmo will be added to
  100589. * @param dragAxis The axis which the gizmo will be able to drag on
  100590. * @param color The color of the gizmo
  100591. */
  100592. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  100593. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100594. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100595. var _this = _super.call(this, gizmoLayer) || this;
  100596. _this._pointerObserver = null;
  100597. /**
  100598. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100599. */
  100600. _this.snapDistance = 0;
  100601. /**
  100602. * Event that fires each time the gizmo snaps to a new location.
  100603. * * snapDistance is the the change in distance
  100604. */
  100605. _this.onSnapObservable = new BABYLON.Observable();
  100606. // Create Material
  100607. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100608. coloredMaterial.disableLighting = true;
  100609. coloredMaterial.emissiveColor = color;
  100610. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100611. hoverMaterial.disableLighting = true;
  100612. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100613. // Build mesh on root node
  100614. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100615. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  100616. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100617. arrowTail.color = coloredMaterial.emissiveColor;
  100618. arrow.addChild(arrowMesh);
  100619. arrow.addChild(arrowTail);
  100620. // Position arrow pointing in its drag axis
  100621. arrowMesh.scaling.scaleInPlace(0.05);
  100622. arrowMesh.material = coloredMaterial;
  100623. arrowMesh.rotation.x = Math.PI / 2;
  100624. arrowMesh.position.z += 0.3;
  100625. arrowTail.scaling.scaleInPlace(0.26);
  100626. arrowTail.rotation.x = Math.PI / 2;
  100627. arrowTail.material = coloredMaterial;
  100628. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100629. arrow.scaling.scaleInPlace(1 / 3);
  100630. _this._rootMesh.addChild(arrow);
  100631. var currentSnapDragDistance = 0;
  100632. var tmpVector = new BABYLON.Vector3();
  100633. var tmpSnapEvent = { snapDistance: 0 };
  100634. // Add drag behavior to handle events when the gizmo is dragged
  100635. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100636. _this.dragBehavior.moveAttached = false;
  100637. _this._rootMesh.addBehavior(_this.dragBehavior);
  100638. var localDelta = new BABYLON.Vector3();
  100639. var tmpMatrix = new BABYLON.Matrix();
  100640. _this.dragBehavior.onDragObservable.add(function (event) {
  100641. if (_this.attachedMesh) {
  100642. // Convert delta to local translation if it has a parent
  100643. if (_this.attachedMesh.parent) {
  100644. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100645. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  100646. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  100647. }
  100648. else {
  100649. localDelta.copyFrom(event.delta);
  100650. }
  100651. // Snapping logic
  100652. if (_this.snapDistance == 0) {
  100653. _this.attachedMesh.position.addInPlace(localDelta);
  100654. }
  100655. else {
  100656. currentSnapDragDistance += event.dragDistance;
  100657. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100658. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  100659. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100660. localDelta.normalizeToRef(tmpVector);
  100661. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  100662. _this.attachedMesh.position.addInPlace(tmpVector);
  100663. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100664. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100665. }
  100666. }
  100667. }
  100668. });
  100669. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100670. if (_this._customMeshSet) {
  100671. return;
  100672. }
  100673. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100674. var material = isHovered ? hoverMaterial : coloredMaterial;
  100675. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100676. m.material = material;
  100677. if (m.color) {
  100678. m.color = material.emissiveColor;
  100679. }
  100680. });
  100681. });
  100682. return _this;
  100683. }
  100684. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  100685. if (this.dragBehavior) {
  100686. this.dragBehavior.enabled = value ? true : false;
  100687. }
  100688. };
  100689. /**
  100690. * Disposes of the gizmo
  100691. */
  100692. AxisDragGizmo.prototype.dispose = function () {
  100693. this.onSnapObservable.clear();
  100694. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100695. this.dragBehavior.detach();
  100696. _super.prototype.dispose.call(this);
  100697. };
  100698. return AxisDragGizmo;
  100699. }(BABYLON.Gizmo));
  100700. BABYLON.AxisDragGizmo = AxisDragGizmo;
  100701. })(BABYLON || (BABYLON = {}));
  100702. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  100703. var BABYLON;
  100704. (function (BABYLON) {
  100705. /**
  100706. * Single axis scale gizmo
  100707. */
  100708. var AxisScaleGizmo = /** @class */ (function (_super) {
  100709. __extends(AxisScaleGizmo, _super);
  100710. /**
  100711. * Creates an AxisScaleGizmo
  100712. * @param gizmoLayer The utility layer the gizmo will be added to
  100713. * @param dragAxis The axis which the gizmo will be able to scale on
  100714. * @param color The color of the gizmo
  100715. */
  100716. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  100717. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100718. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100719. var _this = _super.call(this, gizmoLayer) || this;
  100720. _this._pointerObserver = null;
  100721. /**
  100722. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100723. */
  100724. _this.snapDistance = 0;
  100725. /**
  100726. * Event that fires each time the gizmo snaps to a new location.
  100727. * * snapDistance is the the change in distance
  100728. */
  100729. _this.onSnapObservable = new BABYLON.Observable();
  100730. /**
  100731. * If the scaling operation should be done on all axis (default: false)
  100732. */
  100733. _this.uniformScaling = false;
  100734. // Create Material
  100735. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100736. _this._coloredMaterial.disableLighting = true;
  100737. _this._coloredMaterial.emissiveColor = color;
  100738. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100739. hoverMaterial.disableLighting = true;
  100740. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100741. // Build mesh on root node
  100742. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100743. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  100744. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100745. arrowTail.color = _this._coloredMaterial.emissiveColor;
  100746. arrow.addChild(arrowMesh);
  100747. arrow.addChild(arrowTail);
  100748. // Position arrow pointing in its drag axis
  100749. arrowMesh.scaling.scaleInPlace(0.1);
  100750. arrowMesh.material = _this._coloredMaterial;
  100751. arrowMesh.rotation.x = Math.PI / 2;
  100752. arrowMesh.position.z += 0.3;
  100753. arrowTail.scaling.scaleInPlace(0.26);
  100754. arrowTail.rotation.x = Math.PI / 2;
  100755. arrowTail.material = _this._coloredMaterial;
  100756. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100757. _this._rootMesh.addChild(arrow);
  100758. arrow.scaling.scaleInPlace(1 / 3);
  100759. // Add drag behavior to handle events when the gizmo is dragged
  100760. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100761. _this.dragBehavior.moveAttached = false;
  100762. _this._rootMesh.addBehavior(_this.dragBehavior);
  100763. var currentSnapDragDistance = 0;
  100764. var tmpVector = new BABYLON.Vector3();
  100765. var tmpSnapEvent = { snapDistance: 0 };
  100766. _this.dragBehavior.onDragObservable.add(function (event) {
  100767. if (_this.attachedMesh) {
  100768. // Snapping logic
  100769. var snapped = false;
  100770. var dragSteps = 0;
  100771. if (_this.uniformScaling) {
  100772. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  100773. if (tmpVector.y < 0) {
  100774. tmpVector.scaleInPlace(-1);
  100775. }
  100776. }
  100777. else {
  100778. tmpVector.copyFrom(dragAxis);
  100779. }
  100780. if (_this.snapDistance == 0) {
  100781. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  100782. }
  100783. else {
  100784. currentSnapDragDistance += event.dragDistance;
  100785. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100786. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100787. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100788. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  100789. snapped = true;
  100790. }
  100791. else {
  100792. tmpVector.scaleInPlace(0);
  100793. }
  100794. }
  100795. _this.attachedMesh.scaling.addInPlace(tmpVector);
  100796. if (snapped) {
  100797. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100798. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100799. }
  100800. }
  100801. });
  100802. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100803. if (_this._customMeshSet) {
  100804. return;
  100805. }
  100806. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100807. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  100808. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100809. m.material = material;
  100810. if (m.color) {
  100811. m.color = material.emissiveColor;
  100812. }
  100813. });
  100814. });
  100815. return _this;
  100816. }
  100817. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  100818. if (this.dragBehavior) {
  100819. this.dragBehavior.enabled = value ? true : false;
  100820. }
  100821. };
  100822. /**
  100823. * Disposes of the gizmo
  100824. */
  100825. AxisScaleGizmo.prototype.dispose = function () {
  100826. this.onSnapObservable.clear();
  100827. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100828. this.dragBehavior.detach();
  100829. _super.prototype.dispose.call(this);
  100830. };
  100831. /**
  100832. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100833. * @param mesh The mesh to replace the default mesh of the gizmo
  100834. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  100835. */
  100836. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  100837. var _this = this;
  100838. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  100839. _super.prototype.setCustomMesh.call(this, mesh);
  100840. if (useGizmoMaterial) {
  100841. this._rootMesh.getChildMeshes().forEach(function (m) {
  100842. m.material = _this._coloredMaterial;
  100843. if (m.color) {
  100844. m.color = _this._coloredMaterial.emissiveColor;
  100845. }
  100846. });
  100847. this._customMeshSet = false;
  100848. }
  100849. };
  100850. return AxisScaleGizmo;
  100851. }(BABYLON.Gizmo));
  100852. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  100853. })(BABYLON || (BABYLON = {}));
  100854. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  100855. var BABYLON;
  100856. (function (BABYLON) {
  100857. /**
  100858. * Single plane rotation gizmo
  100859. */
  100860. var PlaneRotationGizmo = /** @class */ (function (_super) {
  100861. __extends(PlaneRotationGizmo, _super);
  100862. /**
  100863. * Creates a PlaneRotationGizmo
  100864. * @param gizmoLayer The utility layer the gizmo will be added to
  100865. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  100866. * @param color The color of the gizmo
  100867. * @param tessellation Amount of tessellation to be used when creating rotation circles
  100868. */
  100869. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  100870. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100871. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100872. if (tessellation === void 0) { tessellation = 32; }
  100873. var _this = _super.call(this, gizmoLayer) || this;
  100874. _this._pointerObserver = null;
  100875. /**
  100876. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  100877. */
  100878. _this.snapDistance = 0;
  100879. /**
  100880. * Event that fires each time the gizmo snaps to a new location.
  100881. * * snapDistance is the the change in distance
  100882. */
  100883. _this.onSnapObservable = new BABYLON.Observable();
  100884. // Create Material
  100885. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100886. coloredMaterial.disableLighting = true;
  100887. coloredMaterial.emissiveColor = color;
  100888. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100889. hoverMaterial.disableLighting = true;
  100890. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100891. // Build mesh on root node
  100892. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100893. // Create circle out of lines
  100894. var radius = 0.8;
  100895. var points = new Array();
  100896. for (var i = 0; i < tessellation; i++) {
  100897. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  100898. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  100899. }
  100900. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  100901. rotationMesh.color = coloredMaterial.emissiveColor;
  100902. // Position arrow pointing in its drag axis
  100903. rotationMesh.scaling.scaleInPlace(0.26);
  100904. rotationMesh.material = coloredMaterial;
  100905. rotationMesh.rotation.x = Math.PI / 2;
  100906. parentMesh.addChild(rotationMesh);
  100907. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  100908. _this._rootMesh.addChild(parentMesh);
  100909. parentMesh.scaling.scaleInPlace(1 / 3);
  100910. // Add drag behavior to handle events when the gizmo is dragged
  100911. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  100912. _this.dragBehavior.moveAttached = false;
  100913. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  100914. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  100915. _this._rootMesh.addBehavior(_this.dragBehavior);
  100916. var lastDragPosition = new BABYLON.Vector3();
  100917. _this.dragBehavior.onDragStartObservable.add(function (e) {
  100918. if (_this.attachedMesh) {
  100919. lastDragPosition.copyFrom(e.dragPlanePoint);
  100920. }
  100921. });
  100922. var rotationMatrix = new BABYLON.Matrix();
  100923. var planeNormalTowardsCamera = new BABYLON.Vector3();
  100924. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  100925. var tmpSnapEvent = { snapDistance: 0 };
  100926. var currentSnapDragDistance = 0;
  100927. var tmpMatrix = new BABYLON.Matrix();
  100928. var tmpVector = new BABYLON.Vector3();
  100929. var amountToRotate = new BABYLON.Quaternion();
  100930. _this.dragBehavior.onDragObservable.add(function (event) {
  100931. if (_this.attachedMesh) {
  100932. if (!_this.attachedMesh.rotationQuaternion) {
  100933. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  100934. }
  100935. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  100936. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  100937. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  100938. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  100939. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  100940. var angle = Math.atan2(cross.length(), dot);
  100941. planeNormalTowardsCamera.copyFrom(planeNormal);
  100942. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  100943. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100944. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  100945. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  100946. }
  100947. // Flip up vector depending on which side the camera is on
  100948. if (gizmoLayer.utilityLayerScene.activeCamera) {
  100949. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  100950. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  100951. planeNormalTowardsCamera.scaleInPlace(-1);
  100952. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  100953. }
  100954. }
  100955. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  100956. if (halfCircleSide) {
  100957. angle = -angle;
  100958. }
  100959. // Snapping logic
  100960. var snapped = false;
  100961. if (_this.snapDistance != 0) {
  100962. currentSnapDragDistance += angle;
  100963. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100964. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100965. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100966. angle = _this.snapDistance * dragSteps;
  100967. snapped = true;
  100968. }
  100969. else {
  100970. angle = 0;
  100971. }
  100972. }
  100973. // If the mesh has a parent, convert needed world rotation to local rotation
  100974. tmpMatrix.reset();
  100975. if (_this.attachedMesh.parent) {
  100976. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100977. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  100978. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  100979. }
  100980. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  100981. var quaternionCoefficient = Math.sin(angle / 2);
  100982. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  100983. // 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
  100984. if (tmpMatrix.determinant() > 0) {
  100985. amountToRotate.toEulerAnglesToRef(tmpVector);
  100986. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  100987. }
  100988. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100989. // Rotate selected mesh quaternion over fixed axis
  100990. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  100991. }
  100992. else {
  100993. // Rotate selected mesh quaternion over rotated axis
  100994. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  100995. }
  100996. lastDragPosition.copyFrom(event.dragPlanePoint);
  100997. if (snapped) {
  100998. tmpSnapEvent.snapDistance = angle;
  100999. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  101000. }
  101001. }
  101002. });
  101003. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101004. if (_this._customMeshSet) {
  101005. return;
  101006. }
  101007. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  101008. var material = isHovered ? hoverMaterial : coloredMaterial;
  101009. _this._rootMesh.getChildMeshes().forEach(function (m) {
  101010. m.material = material;
  101011. if (m.color) {
  101012. m.color = material.emissiveColor;
  101013. }
  101014. });
  101015. });
  101016. return _this;
  101017. }
  101018. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  101019. if (this.dragBehavior) {
  101020. this.dragBehavior.enabled = value ? true : false;
  101021. }
  101022. };
  101023. /**
  101024. * Disposes of the gizmo
  101025. */
  101026. PlaneRotationGizmo.prototype.dispose = function () {
  101027. this.onSnapObservable.clear();
  101028. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101029. this.dragBehavior.detach();
  101030. _super.prototype.dispose.call(this);
  101031. };
  101032. return PlaneRotationGizmo;
  101033. }(BABYLON.Gizmo));
  101034. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  101035. })(BABYLON || (BABYLON = {}));
  101036. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  101037. var BABYLON;
  101038. (function (BABYLON) {
  101039. /**
  101040. * Gizmo that enables dragging a mesh along 3 axis
  101041. */
  101042. var PositionGizmo = /** @class */ (function (_super) {
  101043. __extends(PositionGizmo, _super);
  101044. /**
  101045. * Creates a PositionGizmo
  101046. * @param gizmoLayer The utility layer the gizmo will be added to
  101047. */
  101048. function PositionGizmo(gizmoLayer) {
  101049. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101050. var _this = _super.call(this, gizmoLayer) || this;
  101051. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  101052. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  101053. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  101054. _this.attachedMesh = null;
  101055. return _this;
  101056. }
  101057. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  101058. set: function (mesh) {
  101059. if (this.xGizmo) {
  101060. this.xGizmo.attachedMesh = mesh;
  101061. this.yGizmo.attachedMesh = mesh;
  101062. this.zGizmo.attachedMesh = mesh;
  101063. }
  101064. },
  101065. enumerable: true,
  101066. configurable: true
  101067. });
  101068. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101069. get: function () {
  101070. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101071. },
  101072. set: function (value) {
  101073. if (this.xGizmo) {
  101074. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101075. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101076. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101077. }
  101078. },
  101079. enumerable: true,
  101080. configurable: true
  101081. });
  101082. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  101083. get: function () {
  101084. return this.xGizmo.snapDistance;
  101085. },
  101086. /**
  101087. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101088. */
  101089. set: function (value) {
  101090. if (this.xGizmo) {
  101091. this.xGizmo.snapDistance = value;
  101092. this.yGizmo.snapDistance = value;
  101093. this.zGizmo.snapDistance = value;
  101094. }
  101095. },
  101096. enumerable: true,
  101097. configurable: true
  101098. });
  101099. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  101100. get: function () {
  101101. return this.xGizmo.scaleRatio;
  101102. },
  101103. /**
  101104. * Ratio for the scale of the gizmo (Default: 1)
  101105. */
  101106. set: function (value) {
  101107. if (this.xGizmo) {
  101108. this.xGizmo.scaleRatio = value;
  101109. this.yGizmo.scaleRatio = value;
  101110. this.zGizmo.scaleRatio = value;
  101111. }
  101112. },
  101113. enumerable: true,
  101114. configurable: true
  101115. });
  101116. /**
  101117. * Disposes of the gizmo
  101118. */
  101119. PositionGizmo.prototype.dispose = function () {
  101120. this.xGizmo.dispose();
  101121. this.yGizmo.dispose();
  101122. this.zGizmo.dispose();
  101123. };
  101124. /**
  101125. * CustomMeshes are not supported by this gizmo
  101126. * @param mesh The mesh to replace the default mesh of the gizmo
  101127. */
  101128. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  101129. 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)");
  101130. };
  101131. return PositionGizmo;
  101132. }(BABYLON.Gizmo));
  101133. BABYLON.PositionGizmo = PositionGizmo;
  101134. })(BABYLON || (BABYLON = {}));
  101135. //# sourceMappingURL=babylon.positionGizmo.js.map
  101136. var BABYLON;
  101137. (function (BABYLON) {
  101138. /**
  101139. * Gizmo that enables rotating a mesh along 3 axis
  101140. */
  101141. var RotationGizmo = /** @class */ (function (_super) {
  101142. __extends(RotationGizmo, _super);
  101143. /**
  101144. * Creates a RotationGizmo
  101145. * @param gizmoLayer The utility layer the gizmo will be added to
  101146. * @param tessellation Amount of tessellation to be used when creating rotation circles
  101147. */
  101148. function RotationGizmo(gizmoLayer, tessellation) {
  101149. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101150. if (tessellation === void 0) { tessellation = 32; }
  101151. var _this = _super.call(this, gizmoLayer) || this;
  101152. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  101153. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  101154. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  101155. _this.attachedMesh = null;
  101156. return _this;
  101157. }
  101158. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  101159. set: function (mesh) {
  101160. if (this.xGizmo) {
  101161. this.xGizmo.attachedMesh = mesh;
  101162. this.yGizmo.attachedMesh = mesh;
  101163. this.zGizmo.attachedMesh = mesh;
  101164. }
  101165. },
  101166. enumerable: true,
  101167. configurable: true
  101168. });
  101169. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101170. get: function () {
  101171. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101172. },
  101173. set: function (value) {
  101174. if (this.xGizmo) {
  101175. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101176. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101177. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101178. }
  101179. },
  101180. enumerable: true,
  101181. configurable: true
  101182. });
  101183. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  101184. get: function () {
  101185. return this.xGizmo.snapDistance;
  101186. },
  101187. /**
  101188. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101189. */
  101190. set: function (value) {
  101191. if (this.xGizmo) {
  101192. this.xGizmo.snapDistance = value;
  101193. this.yGizmo.snapDistance = value;
  101194. this.zGizmo.snapDistance = value;
  101195. }
  101196. },
  101197. enumerable: true,
  101198. configurable: true
  101199. });
  101200. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  101201. get: function () {
  101202. return this.xGizmo.scaleRatio;
  101203. },
  101204. /**
  101205. * Ratio for the scale of the gizmo (Default: 1)
  101206. */
  101207. set: function (value) {
  101208. if (this.xGizmo) {
  101209. this.xGizmo.scaleRatio = value;
  101210. this.yGizmo.scaleRatio = value;
  101211. this.zGizmo.scaleRatio = value;
  101212. }
  101213. },
  101214. enumerable: true,
  101215. configurable: true
  101216. });
  101217. /**
  101218. * Disposes of the gizmo
  101219. */
  101220. RotationGizmo.prototype.dispose = function () {
  101221. this.xGizmo.dispose();
  101222. this.yGizmo.dispose();
  101223. this.zGizmo.dispose();
  101224. };
  101225. /**
  101226. * CustomMeshes are not supported by this gizmo
  101227. * @param mesh The mesh to replace the default mesh of the gizmo
  101228. */
  101229. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  101230. 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)");
  101231. };
  101232. return RotationGizmo;
  101233. }(BABYLON.Gizmo));
  101234. BABYLON.RotationGizmo = RotationGizmo;
  101235. })(BABYLON || (BABYLON = {}));
  101236. //# sourceMappingURL=babylon.rotationGizmo.js.map
  101237. var BABYLON;
  101238. (function (BABYLON) {
  101239. /**
  101240. * Gizmo that enables scaling a mesh along 3 axis
  101241. */
  101242. var ScaleGizmo = /** @class */ (function (_super) {
  101243. __extends(ScaleGizmo, _super);
  101244. /**
  101245. * Creates a ScaleGizmo
  101246. * @param gizmoLayer The utility layer the gizmo will be added to
  101247. */
  101248. function ScaleGizmo(gizmoLayer) {
  101249. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101250. var _this = _super.call(this, gizmoLayer) || this;
  101251. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  101252. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  101253. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  101254. // Create uniform scale gizmo
  101255. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  101256. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  101257. _this.uniformScaleGizmo.uniformScaling = true;
  101258. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  101259. uniformScalingMesh.scaling.scaleInPlace(0.02);
  101260. uniformScalingMesh.visibility = 0;
  101261. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  101262. octahedron.scaling.scaleInPlace(0.007);
  101263. uniformScalingMesh.addChild(octahedron);
  101264. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  101265. _this.attachedMesh = null;
  101266. return _this;
  101267. }
  101268. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  101269. set: function (mesh) {
  101270. if (this.xGizmo) {
  101271. this.xGizmo.attachedMesh = mesh;
  101272. this.yGizmo.attachedMesh = mesh;
  101273. this.zGizmo.attachedMesh = mesh;
  101274. this.uniformScaleGizmo.attachedMesh = mesh;
  101275. }
  101276. },
  101277. enumerable: true,
  101278. configurable: true
  101279. });
  101280. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  101281. get: function () {
  101282. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  101283. },
  101284. set: function (value) {
  101285. if (!value) {
  101286. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  101287. }
  101288. if (this.xGizmo) {
  101289. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101290. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101291. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  101292. }
  101293. },
  101294. enumerable: true,
  101295. configurable: true
  101296. });
  101297. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  101298. get: function () {
  101299. return this.xGizmo.snapDistance;
  101300. },
  101301. /**
  101302. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101303. */
  101304. set: function (value) {
  101305. if (this.xGizmo) {
  101306. this.xGizmo.snapDistance = value;
  101307. this.yGizmo.snapDistance = value;
  101308. this.zGizmo.snapDistance = value;
  101309. this.uniformScaleGizmo.snapDistance = value;
  101310. }
  101311. },
  101312. enumerable: true,
  101313. configurable: true
  101314. });
  101315. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  101316. get: function () {
  101317. return this.xGizmo.scaleRatio;
  101318. },
  101319. /**
  101320. * Ratio for the scale of the gizmo (Default: 1)
  101321. */
  101322. set: function (value) {
  101323. if (this.xGizmo) {
  101324. this.xGizmo.scaleRatio = value;
  101325. this.yGizmo.scaleRatio = value;
  101326. this.zGizmo.scaleRatio = value;
  101327. this.uniformScaleGizmo.scaleRatio = value;
  101328. }
  101329. },
  101330. enumerable: true,
  101331. configurable: true
  101332. });
  101333. /**
  101334. * Disposes of the gizmo
  101335. */
  101336. ScaleGizmo.prototype.dispose = function () {
  101337. this.xGizmo.dispose();
  101338. this.yGizmo.dispose();
  101339. this.zGizmo.dispose();
  101340. this.uniformScaleGizmo.dispose();
  101341. };
  101342. return ScaleGizmo;
  101343. }(BABYLON.Gizmo));
  101344. BABYLON.ScaleGizmo = ScaleGizmo;
  101345. })(BABYLON || (BABYLON = {}));
  101346. //# sourceMappingURL=babylon.scaleGizmo.js.map
  101347. var BABYLON;
  101348. (function (BABYLON) {
  101349. /**
  101350. * Bounding box gizmo
  101351. */
  101352. var BoundingBoxGizmo = /** @class */ (function (_super) {
  101353. __extends(BoundingBoxGizmo, _super);
  101354. /**
  101355. * Creates an BoundingBoxGizmo
  101356. * @param gizmoLayer The utility layer the gizmo will be added to
  101357. * @param color The color of the gizmo
  101358. */
  101359. function BoundingBoxGizmo(color, gizmoLayer) {
  101360. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101361. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  101362. var _this = _super.call(this, gizmoLayer) || this;
  101363. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  101364. _this._renderObserver = null;
  101365. _this._pointerObserver = null;
  101366. _this._scaleDragSpeed = 0.2;
  101367. _this._tmpQuaternion = new BABYLON.Quaternion();
  101368. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  101369. _this._tmpRotationMatrix = new BABYLON.Matrix();
  101370. /**
  101371. * 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)
  101372. */
  101373. _this.ignoreChildren = false;
  101374. /**
  101375. * 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)
  101376. */
  101377. _this.includeChildPredicate = null;
  101378. /**
  101379. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  101380. */
  101381. _this.rotationSphereSize = 0.1;
  101382. /**
  101383. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  101384. */
  101385. _this.scaleBoxSize = 0.1;
  101386. /**
  101387. * 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)
  101388. */
  101389. _this.fixedDragMeshScreenSize = false;
  101390. /**
  101391. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  101392. */
  101393. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  101394. /**
  101395. * Fired when a rotation sphere or scale box is dragged
  101396. */
  101397. _this.onDragStartObservable = new BABYLON.Observable();
  101398. /**
  101399. * Fired when a scale box is dragged
  101400. */
  101401. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  101402. /**
  101403. * Fired when a scale box drag is ended
  101404. */
  101405. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  101406. /**
  101407. * Fired when a rotation sphere is dragged
  101408. */
  101409. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  101410. /**
  101411. * Fired when a rotation sphere drag is ended
  101412. */
  101413. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  101414. /**
  101415. * 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)
  101416. */
  101417. _this.scalePivot = null;
  101418. _this._existingMeshScale = new BABYLON.Vector3();
  101419. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  101420. _this._updateScale = false;
  101421. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  101422. // Create Materials
  101423. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101424. coloredMaterial.disableLighting = true;
  101425. coloredMaterial.emissiveColor = color;
  101426. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101427. hoverColoredMaterial.disableLighting = true;
  101428. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101429. // Build bounding box out of lines
  101430. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101431. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  101432. var lines = [];
  101433. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  101434. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  101435. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  101436. 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));
  101437. 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));
  101438. 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));
  101439. 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));
  101440. 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));
  101441. 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));
  101442. 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));
  101443. 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));
  101444. 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));
  101445. lines.forEach(function (l) {
  101446. l.color = color;
  101447. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  101448. l.isPickable = false;
  101449. _this._lineBoundingBox.addChild(l);
  101450. });
  101451. _this._rootMesh.addChild(_this._lineBoundingBox);
  101452. // Create rotation spheres
  101453. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101454. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  101455. var _loop_1 = function (i_1) {
  101456. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  101457. sphere.rotationQuaternion = new BABYLON.Quaternion();
  101458. sphere.material = coloredMaterial;
  101459. // Drag behavior
  101460. _dragBehavior = new BABYLON.PointerDragBehavior({});
  101461. _dragBehavior.moveAttached = false;
  101462. _dragBehavior.updateDragPlane = false;
  101463. sphere.addBehavior(_dragBehavior);
  101464. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  101465. var totalTurnAmountOfDrag = 0;
  101466. _dragBehavior.onDragStartObservable.add(function (event) {
  101467. startingTurnDirection.copyFrom(sphere.forward);
  101468. totalTurnAmountOfDrag = 0;
  101469. });
  101470. _dragBehavior.onDragObservable.add(function (event) {
  101471. _this.onRotationSphereDragObservable.notifyObservers({});
  101472. if (_this.attachedMesh) {
  101473. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101474. var worldDragDirection = startingTurnDirection;
  101475. // Project the world right on to the drag plane
  101476. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  101477. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  101478. // project drag delta on to the resulting drag axis and rotate based on that
  101479. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  101480. // Make rotation relative to size of mesh.
  101481. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101482. // Rotate based on axis
  101483. if (!_this.attachedMesh.rotationQuaternion) {
  101484. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  101485. }
  101486. if (!_this._anchorMesh.rotationQuaternion) {
  101487. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  101488. }
  101489. // Do not allow the object to turn more than a full circle
  101490. totalTurnAmountOfDrag += projectDist;
  101491. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  101492. if (i_1 >= 8) {
  101493. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  101494. }
  101495. else if (i_1 >= 4) {
  101496. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  101497. }
  101498. else {
  101499. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  101500. }
  101501. // Rotate around center of bounding box
  101502. _this._anchorMesh.addChild(_this.attachedMesh);
  101503. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  101504. _this._anchorMesh.removeChild(_this.attachedMesh);
  101505. }
  101506. _this.updateBoundingBox();
  101507. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101508. }
  101509. });
  101510. // Selection/deselection
  101511. _dragBehavior.onDragStartObservable.add(function () {
  101512. _this.onDragStartObservable.notifyObservers({});
  101513. _this._selectNode(sphere);
  101514. });
  101515. _dragBehavior.onDragEndObservable.add(function () {
  101516. _this.onRotationSphereDragEndObservable.notifyObservers({});
  101517. _this._selectNode(null);
  101518. });
  101519. this_1._rotateSpheresParent.addChild(sphere);
  101520. };
  101521. var this_1 = this, _dragBehavior;
  101522. for (var i_1 = 0; i_1 < 12; i_1++) {
  101523. _loop_1(i_1);
  101524. }
  101525. _this._rootMesh.addChild(_this._rotateSpheresParent);
  101526. // Create scale cubes
  101527. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101528. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  101529. for (var i = 0; i < 2; i++) {
  101530. for (var j = 0; j < 2; j++) {
  101531. var _loop_2 = function () {
  101532. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  101533. box.material = coloredMaterial;
  101534. // Dragging logic
  101535. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  101536. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101537. _dragBehavior.moveAttached = false;
  101538. box.addBehavior(_dragBehavior);
  101539. _dragBehavior.onDragObservable.add(function (event) {
  101540. _this.onScaleBoxDragObservable.notifyObservers({});
  101541. if (_this.attachedMesh) {
  101542. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101543. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101544. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  101545. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  101546. _this.updateBoundingBox();
  101547. if (_this.scalePivot) {
  101548. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  101549. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  101550. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  101551. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101552. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101553. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  101554. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101555. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  101556. }
  101557. else {
  101558. // Scale from the position of the opposite corner
  101559. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  101560. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101561. }
  101562. _this._anchorMesh.addChild(_this.attachedMesh);
  101563. _this._anchorMesh.scaling.addInPlace(deltaScale);
  101564. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  101565. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  101566. }
  101567. _this._anchorMesh.removeChild(_this.attachedMesh);
  101568. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101569. }
  101570. });
  101571. // Selection/deselection
  101572. _dragBehavior.onDragStartObservable.add(function () {
  101573. _this.onDragStartObservable.notifyObservers({});
  101574. _this._selectNode(box);
  101575. });
  101576. _dragBehavior.onDragEndObservable.add(function () {
  101577. _this.onScaleBoxDragEndObservable.notifyObservers({});
  101578. _this._selectNode(null);
  101579. });
  101580. this_2._scaleBoxesParent.addChild(box);
  101581. };
  101582. var this_2 = this, _dragBehavior;
  101583. for (var k = 0; k < 2; k++) {
  101584. _loop_2();
  101585. }
  101586. }
  101587. }
  101588. _this._rootMesh.addChild(_this._scaleBoxesParent);
  101589. // Hover color change
  101590. var pointerIds = new Array();
  101591. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101592. if (!pointerIds[pointerInfo.event.pointerId]) {
  101593. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  101594. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  101595. pointerIds[pointerInfo.event.pointerId] = mesh;
  101596. mesh.material = hoverColoredMaterial;
  101597. }
  101598. });
  101599. }
  101600. else {
  101601. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  101602. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  101603. delete pointerIds[pointerInfo.event.pointerId];
  101604. }
  101605. }
  101606. });
  101607. // Update bounding box positions
  101608. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  101609. // Only update the bouding box if scaling has changed
  101610. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  101611. _this.updateBoundingBox();
  101612. }
  101613. });
  101614. _this.updateBoundingBox();
  101615. return _this;
  101616. }
  101617. /** @hidden */
  101618. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  101619. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  101620. // Save old pivot and set pivot to 0,0,0
  101621. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  101622. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  101623. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  101624. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  101625. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101626. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101627. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101628. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  101629. }
  101630. }
  101631. BoundingBoxGizmo._PivotCached++;
  101632. };
  101633. /** @hidden */
  101634. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  101635. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  101636. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  101637. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101638. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101639. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101640. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  101641. }
  101642. this._PivotCached--;
  101643. };
  101644. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  101645. if (value) {
  101646. // Reset anchor mesh to match attached mesh's scale
  101647. // This is needed to avoid invalid box/sphere position on first drag
  101648. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  101649. this._anchorMesh.addChild(value);
  101650. this._anchorMesh.removeChild(value);
  101651. BoundingBoxGizmo._RestorePivotPoint(value);
  101652. this.updateBoundingBox();
  101653. }
  101654. };
  101655. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  101656. this._rotateSpheresParent.getChildMeshes()
  101657. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  101658. m.isVisible = (!selectedMesh || m == selectedMesh);
  101659. });
  101660. };
  101661. /**
  101662. * Updates the bounding box information for the Gizmo
  101663. */
  101664. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  101665. if (this.attachedMesh) {
  101666. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  101667. this._update();
  101668. // Rotate based on axis
  101669. if (!this.attachedMesh.rotationQuaternion) {
  101670. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  101671. }
  101672. if (!this._anchorMesh.rotationQuaternion) {
  101673. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  101674. }
  101675. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101676. // Store original position and reset mesh to origin before computing the bounding box
  101677. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101678. this._tmpVector.copyFrom(this.attachedMesh.position);
  101679. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  101680. this.attachedMesh.position.set(0, 0, 0);
  101681. // Update bounding dimensions/positions
  101682. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  101683. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  101684. // Update gizmo to match bounding box scaling and rotation
  101685. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  101686. 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);
  101687. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  101688. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  101689. this._lineBoundingBox.computeWorldMatrix();
  101690. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  101691. // restore position/rotation values
  101692. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  101693. this.attachedMesh.position.copyFrom(this._tmpVector);
  101694. }
  101695. // Update rotation sphere locations
  101696. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  101697. for (var i = 0; i < 3; i++) {
  101698. for (var j = 0; j < 2; j++) {
  101699. for (var k = 0; k < 2; k++) {
  101700. var index = ((i * 4) + (j * 2)) + k;
  101701. if (i == 0) {
  101702. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101703. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101704. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101705. }
  101706. if (i == 1) {
  101707. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  101708. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101709. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101710. }
  101711. if (i == 2) {
  101712. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  101713. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101714. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101715. }
  101716. if (this.fixedDragMeshScreenSize) {
  101717. this._rootMesh.computeWorldMatrix();
  101718. this._rotateSpheresParent.computeWorldMatrix();
  101719. rotateSpheres[index].computeWorldMatrix();
  101720. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101721. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101722. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101723. }
  101724. else {
  101725. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  101726. }
  101727. }
  101728. }
  101729. }
  101730. // Update scale box locations
  101731. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  101732. for (var i = 0; i < 2; i++) {
  101733. for (var j = 0; j < 2; j++) {
  101734. for (var k = 0; k < 2; k++) {
  101735. var index = ((i * 4) + (j * 2)) + k;
  101736. if (scaleBoxes[index]) {
  101737. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101738. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101739. if (this.fixedDragMeshScreenSize) {
  101740. this._rootMesh.computeWorldMatrix();
  101741. this._scaleBoxesParent.computeWorldMatrix();
  101742. scaleBoxes[index].computeWorldMatrix();
  101743. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101744. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101745. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101746. }
  101747. else {
  101748. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  101749. }
  101750. }
  101751. }
  101752. }
  101753. }
  101754. if (this.attachedMesh) {
  101755. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  101756. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  101757. }
  101758. };
  101759. /**
  101760. * Enables rotation on the specified axis and disables rotation on the others
  101761. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  101762. */
  101763. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  101764. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  101765. if (i < 4) {
  101766. m.setEnabled(axis.indexOf("x") != -1);
  101767. }
  101768. else if (i < 8) {
  101769. m.setEnabled(axis.indexOf("y") != -1);
  101770. }
  101771. else {
  101772. m.setEnabled(axis.indexOf("z") != -1);
  101773. }
  101774. });
  101775. };
  101776. /**
  101777. * Disposes of the gizmo
  101778. */
  101779. BoundingBoxGizmo.prototype.dispose = function () {
  101780. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101781. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  101782. this._lineBoundingBox.dispose();
  101783. this._rotateSpheresParent.dispose();
  101784. this._scaleBoxesParent.dispose();
  101785. _super.prototype.dispose.call(this);
  101786. };
  101787. /**
  101788. * 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)
  101789. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  101790. * @returns the bounding box mesh with the passed in mesh as a child
  101791. */
  101792. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  101793. var makeNotPickable = function (root) {
  101794. root.isPickable = false;
  101795. root.getChildMeshes().forEach(function (c) {
  101796. makeNotPickable(c);
  101797. });
  101798. };
  101799. makeNotPickable(mesh);
  101800. // Reset position to get boudning box from origin with no rotation
  101801. if (!mesh.rotationQuaternion) {
  101802. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  101803. }
  101804. var oldPos = mesh.position.clone();
  101805. var oldRot = mesh.rotationQuaternion.clone();
  101806. mesh.rotationQuaternion.set(0, 0, 0, 1);
  101807. mesh.position.set(0, 0, 0);
  101808. // Update bounding dimensions/positions
  101809. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  101810. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  101811. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  101812. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  101813. // Restore original positions
  101814. mesh.addChild(box);
  101815. mesh.rotationQuaternion.copyFrom(oldRot);
  101816. mesh.position.copyFrom(oldPos);
  101817. // Reverse parenting
  101818. mesh.removeChild(box);
  101819. box.addChild(mesh);
  101820. box.visibility = 0;
  101821. return box;
  101822. };
  101823. /**
  101824. * CustomMeshes are not supported by this gizmo
  101825. * @param mesh The mesh to replace the default mesh of the gizmo
  101826. */
  101827. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  101828. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  101829. };
  101830. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  101831. // store/remove pivot point should only be applied during their outermost calls
  101832. BoundingBoxGizmo._PivotCached = 0;
  101833. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  101834. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  101835. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  101836. return BoundingBoxGizmo;
  101837. }(BABYLON.Gizmo));
  101838. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  101839. })(BABYLON || (BABYLON = {}));
  101840. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  101841. var BABYLON;
  101842. (function (BABYLON) {
  101843. /**
  101844. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  101845. */
  101846. var GizmoManager = /** @class */ (function () {
  101847. /**
  101848. * Instatiates a gizmo manager
  101849. * @param scene the scene to overlay the gizmos on top of
  101850. */
  101851. function GizmoManager(scene) {
  101852. var _this = this;
  101853. this.scene = scene;
  101854. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  101855. this._pointerObserver = null;
  101856. this._attachedMesh = null;
  101857. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  101858. /**
  101859. * When bounding box gizmo is enabled, this can be used to track drag/end events
  101860. */
  101861. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  101862. /**
  101863. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  101864. */
  101865. this.attachableMeshes = null;
  101866. /**
  101867. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  101868. */
  101869. this.usePointerToAttachGizmos = true;
  101870. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101871. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  101872. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101873. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  101874. // Instatiate/dispose gizmos based on pointer actions
  101875. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  101876. if (!_this.usePointerToAttachGizmos) {
  101877. return;
  101878. }
  101879. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101880. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  101881. var node = pointerInfo.pickInfo.pickedMesh;
  101882. if (_this.attachableMeshes == null) {
  101883. // Attach to the most parent node
  101884. while (node && node.parent != null) {
  101885. node = node.parent;
  101886. }
  101887. }
  101888. else {
  101889. // Attach to the parent node that is an attachableMesh
  101890. var found = false;
  101891. _this.attachableMeshes.forEach(function (mesh) {
  101892. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  101893. node = mesh;
  101894. found = true;
  101895. }
  101896. });
  101897. if (!found) {
  101898. node = null;
  101899. }
  101900. }
  101901. if (node instanceof BABYLON.AbstractMesh) {
  101902. _this.attachToMesh(node);
  101903. }
  101904. else {
  101905. _this.attachToMesh(null);
  101906. }
  101907. }
  101908. else {
  101909. _this.attachToMesh(null);
  101910. }
  101911. }
  101912. });
  101913. }
  101914. /**
  101915. * Attaches a set of gizmos to the specified mesh
  101916. * @param mesh The mesh the gizmo's should be attached to
  101917. */
  101918. GizmoManager.prototype.attachToMesh = function (mesh) {
  101919. if (this._attachedMesh) {
  101920. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101921. }
  101922. this._attachedMesh = mesh;
  101923. for (var key in this.gizmos) {
  101924. var gizmo = (this.gizmos[key]);
  101925. if (gizmo && this._gizmosEnabled[key]) {
  101926. gizmo.attachedMesh = mesh;
  101927. }
  101928. }
  101929. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  101930. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101931. }
  101932. };
  101933. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  101934. get: function () {
  101935. return this._gizmosEnabled.positionGizmo;
  101936. },
  101937. /**
  101938. * If the position gizmo is enabled
  101939. */
  101940. set: function (value) {
  101941. if (value) {
  101942. if (!this.gizmos.positionGizmo) {
  101943. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  101944. }
  101945. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  101946. }
  101947. else if (this.gizmos.positionGizmo) {
  101948. this.gizmos.positionGizmo.attachedMesh = null;
  101949. }
  101950. this._gizmosEnabled.positionGizmo = value;
  101951. },
  101952. enumerable: true,
  101953. configurable: true
  101954. });
  101955. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  101956. get: function () {
  101957. return this._gizmosEnabled.rotationGizmo;
  101958. },
  101959. /**
  101960. * If the rotation gizmo is enabled
  101961. */
  101962. set: function (value) {
  101963. if (value) {
  101964. if (!this.gizmos.rotationGizmo) {
  101965. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  101966. }
  101967. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  101968. }
  101969. else if (this.gizmos.rotationGizmo) {
  101970. this.gizmos.rotationGizmo.attachedMesh = null;
  101971. }
  101972. this._gizmosEnabled.rotationGizmo = value;
  101973. },
  101974. enumerable: true,
  101975. configurable: true
  101976. });
  101977. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  101978. get: function () {
  101979. return this._gizmosEnabled.scaleGizmo;
  101980. },
  101981. /**
  101982. * If the scale gizmo is enabled
  101983. */
  101984. set: function (value) {
  101985. if (value) {
  101986. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  101987. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  101988. }
  101989. else if (this.gizmos.scaleGizmo) {
  101990. this.gizmos.scaleGizmo.attachedMesh = null;
  101991. }
  101992. this._gizmosEnabled.scaleGizmo = value;
  101993. },
  101994. enumerable: true,
  101995. configurable: true
  101996. });
  101997. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  101998. get: function () {
  101999. return this._gizmosEnabled.boundingBoxGizmo;
  102000. },
  102001. /**
  102002. * If the boundingBox gizmo is enabled
  102003. */
  102004. set: function (value) {
  102005. if (value) {
  102006. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  102007. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  102008. if (this._attachedMesh) {
  102009. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  102010. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  102011. }
  102012. }
  102013. else if (this.gizmos.boundingBoxGizmo) {
  102014. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  102015. }
  102016. this._gizmosEnabled.boundingBoxGizmo = value;
  102017. },
  102018. enumerable: true,
  102019. configurable: true
  102020. });
  102021. /**
  102022. * Disposes of the gizmo manager
  102023. */
  102024. GizmoManager.prototype.dispose = function () {
  102025. this.scene.onPointerObservable.remove(this._pointerObserver);
  102026. for (var key in this.gizmos) {
  102027. var gizmo = (this.gizmos[key]);
  102028. if (gizmo) {
  102029. gizmo.dispose();
  102030. }
  102031. }
  102032. this._defaultKeepDepthUtilityLayer.dispose();
  102033. this._defaultUtilityLayer.dispose();
  102034. this.boundingBoxDragBehavior.detach();
  102035. };
  102036. return GizmoManager;
  102037. }());
  102038. BABYLON.GizmoManager = GizmoManager;
  102039. })(BABYLON || (BABYLON = {}));
  102040. //# sourceMappingURL=babylon.gizmoManager.js.map
  102041. var BABYLON;
  102042. (function (BABYLON) {
  102043. /**
  102044. * Defines a target to use with MorphTargetManager
  102045. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  102046. */
  102047. var MorphTarget = /** @class */ (function () {
  102048. /**
  102049. * Creates a new MorphTarget
  102050. * @param name defines the name of the target
  102051. * @param influence defines the influence to use
  102052. */
  102053. function MorphTarget(
  102054. /** defines the name of the target */
  102055. name, influence, scene) {
  102056. if (influence === void 0) { influence = 0; }
  102057. if (scene === void 0) { scene = null; }
  102058. this.name = name;
  102059. /**
  102060. * Gets or sets the list of animations
  102061. */
  102062. this.animations = new Array();
  102063. this._positions = null;
  102064. this._normals = null;
  102065. this._tangents = null;
  102066. /**
  102067. * Observable raised when the influence changes
  102068. */
  102069. this.onInfluenceChanged = new BABYLON.Observable();
  102070. this._animationPropertiesOverride = null;
  102071. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102072. this.influence = influence;
  102073. }
  102074. Object.defineProperty(MorphTarget.prototype, "influence", {
  102075. /**
  102076. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  102077. */
  102078. get: function () {
  102079. return this._influence;
  102080. },
  102081. set: function (influence) {
  102082. if (this._influence === influence) {
  102083. return;
  102084. }
  102085. var previous = this._influence;
  102086. this._influence = influence;
  102087. if (this.onInfluenceChanged.hasObservers) {
  102088. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  102089. }
  102090. },
  102091. enumerable: true,
  102092. configurable: true
  102093. });
  102094. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  102095. /**
  102096. * Gets or sets the animation properties override
  102097. */
  102098. get: function () {
  102099. if (!this._animationPropertiesOverride && this._scene) {
  102100. return this._scene.animationPropertiesOverride;
  102101. }
  102102. return this._animationPropertiesOverride;
  102103. },
  102104. set: function (value) {
  102105. this._animationPropertiesOverride = value;
  102106. },
  102107. enumerable: true,
  102108. configurable: true
  102109. });
  102110. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  102111. /**
  102112. * Gets a boolean defining if the target contains position data
  102113. */
  102114. get: function () {
  102115. return !!this._positions;
  102116. },
  102117. enumerable: true,
  102118. configurable: true
  102119. });
  102120. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  102121. /**
  102122. * Gets a boolean defining if the target contains normal data
  102123. */
  102124. get: function () {
  102125. return !!this._normals;
  102126. },
  102127. enumerable: true,
  102128. configurable: true
  102129. });
  102130. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  102131. /**
  102132. * Gets a boolean defining if the target contains tangent data
  102133. */
  102134. get: function () {
  102135. return !!this._tangents;
  102136. },
  102137. enumerable: true,
  102138. configurable: true
  102139. });
  102140. /**
  102141. * Affects position data to this target
  102142. * @param data defines the position data to use
  102143. */
  102144. MorphTarget.prototype.setPositions = function (data) {
  102145. this._positions = data;
  102146. };
  102147. /**
  102148. * Gets the position data stored in this target
  102149. * @returns a FloatArray containing the position data (or null if not present)
  102150. */
  102151. MorphTarget.prototype.getPositions = function () {
  102152. return this._positions;
  102153. };
  102154. /**
  102155. * Affects normal data to this target
  102156. * @param data defines the normal data to use
  102157. */
  102158. MorphTarget.prototype.setNormals = function (data) {
  102159. this._normals = data;
  102160. };
  102161. /**
  102162. * Gets the normal data stored in this target
  102163. * @returns a FloatArray containing the normal data (or null if not present)
  102164. */
  102165. MorphTarget.prototype.getNormals = function () {
  102166. return this._normals;
  102167. };
  102168. /**
  102169. * Affects tangent data to this target
  102170. * @param data defines the tangent data to use
  102171. */
  102172. MorphTarget.prototype.setTangents = function (data) {
  102173. this._tangents = data;
  102174. };
  102175. /**
  102176. * Gets the tangent data stored in this target
  102177. * @returns a FloatArray containing the tangent data (or null if not present)
  102178. */
  102179. MorphTarget.prototype.getTangents = function () {
  102180. return this._tangents;
  102181. };
  102182. /**
  102183. * Serializes the current target into a Serialization object
  102184. * @returns the serialized object
  102185. */
  102186. MorphTarget.prototype.serialize = function () {
  102187. var serializationObject = {};
  102188. serializationObject.name = this.name;
  102189. serializationObject.influence = this.influence;
  102190. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  102191. if (this.hasNormals) {
  102192. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  102193. }
  102194. if (this.hasTangents) {
  102195. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  102196. }
  102197. // Animations
  102198. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  102199. return serializationObject;
  102200. };
  102201. // Statics
  102202. /**
  102203. * Creates a new target from serialized data
  102204. * @param serializationObject defines the serialized data to use
  102205. * @returns a new MorphTarget
  102206. */
  102207. MorphTarget.Parse = function (serializationObject) {
  102208. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  102209. result.setPositions(serializationObject.positions);
  102210. if (serializationObject.normals) {
  102211. result.setNormals(serializationObject.normals);
  102212. }
  102213. if (serializationObject.tangents) {
  102214. result.setTangents(serializationObject.tangents);
  102215. }
  102216. // Animations
  102217. if (serializationObject.animations) {
  102218. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  102219. var parsedAnimation = serializationObject.animations[animationIndex];
  102220. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  102221. }
  102222. }
  102223. return result;
  102224. };
  102225. /**
  102226. * Creates a MorphTarget from mesh data
  102227. * @param mesh defines the source mesh
  102228. * @param name defines the name to use for the new target
  102229. * @param influence defines the influence to attach to the target
  102230. * @returns a new MorphTarget
  102231. */
  102232. MorphTarget.FromMesh = function (mesh, name, influence) {
  102233. if (!name) {
  102234. name = mesh.name;
  102235. }
  102236. var result = new MorphTarget(name, influence, mesh.getScene());
  102237. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  102238. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102239. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  102240. }
  102241. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  102242. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  102243. }
  102244. return result;
  102245. };
  102246. return MorphTarget;
  102247. }());
  102248. BABYLON.MorphTarget = MorphTarget;
  102249. })(BABYLON || (BABYLON = {}));
  102250. //# sourceMappingURL=babylon.morphTarget.js.map
  102251. var BABYLON;
  102252. (function (BABYLON) {
  102253. /**
  102254. * This class is used to deform meshes using morphing between different targets
  102255. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  102256. */
  102257. var MorphTargetManager = /** @class */ (function () {
  102258. /**
  102259. * Creates a new MorphTargetManager
  102260. * @param scene defines the current scene
  102261. */
  102262. function MorphTargetManager(scene) {
  102263. if (scene === void 0) { scene = null; }
  102264. this._targets = new Array();
  102265. this._targetObservable = new Array();
  102266. this._activeTargets = new BABYLON.SmartArray(16);
  102267. this._supportsNormals = false;
  102268. this._supportsTangents = false;
  102269. this._vertexCount = 0;
  102270. this._uniqueId = 0;
  102271. this._tempInfluences = new Array();
  102272. if (!scene) {
  102273. scene = BABYLON.Engine.LastCreatedScene;
  102274. }
  102275. this._scene = scene;
  102276. if (this._scene) {
  102277. this._scene.morphTargetManagers.push(this);
  102278. this._uniqueId = this._scene.getUniqueId();
  102279. }
  102280. }
  102281. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  102282. /**
  102283. * Gets the unique ID of this manager
  102284. */
  102285. get: function () {
  102286. return this._uniqueId;
  102287. },
  102288. enumerable: true,
  102289. configurable: true
  102290. });
  102291. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  102292. /**
  102293. * Gets the number of vertices handled by this manager
  102294. */
  102295. get: function () {
  102296. return this._vertexCount;
  102297. },
  102298. enumerable: true,
  102299. configurable: true
  102300. });
  102301. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  102302. /**
  102303. * Gets a boolean indicating if this manager supports morphing of normals
  102304. */
  102305. get: function () {
  102306. return this._supportsNormals;
  102307. },
  102308. enumerable: true,
  102309. configurable: true
  102310. });
  102311. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  102312. /**
  102313. * Gets a boolean indicating if this manager supports morphing of tangents
  102314. */
  102315. get: function () {
  102316. return this._supportsTangents;
  102317. },
  102318. enumerable: true,
  102319. configurable: true
  102320. });
  102321. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  102322. /**
  102323. * Gets the number of targets stored in this manager
  102324. */
  102325. get: function () {
  102326. return this._targets.length;
  102327. },
  102328. enumerable: true,
  102329. configurable: true
  102330. });
  102331. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  102332. /**
  102333. * Gets the number of influencers (ie. the number of targets with influences > 0)
  102334. */
  102335. get: function () {
  102336. return this._activeTargets.length;
  102337. },
  102338. enumerable: true,
  102339. configurable: true
  102340. });
  102341. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  102342. /**
  102343. * Gets the list of influences (one per target)
  102344. */
  102345. get: function () {
  102346. return this._influences;
  102347. },
  102348. enumerable: true,
  102349. configurable: true
  102350. });
  102351. /**
  102352. * Gets the active target at specified index. An active target is a target with an influence > 0
  102353. * @param index defines the index to check
  102354. * @returns the requested target
  102355. */
  102356. MorphTargetManager.prototype.getActiveTarget = function (index) {
  102357. return this._activeTargets.data[index];
  102358. };
  102359. /**
  102360. * Gets the target at specified index
  102361. * @param index defines the index to check
  102362. * @returns the requested target
  102363. */
  102364. MorphTargetManager.prototype.getTarget = function (index) {
  102365. return this._targets[index];
  102366. };
  102367. /**
  102368. * Add a new target to this manager
  102369. * @param target defines the target to add
  102370. */
  102371. MorphTargetManager.prototype.addTarget = function (target) {
  102372. var _this = this;
  102373. this._targets.push(target);
  102374. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  102375. _this._syncActiveTargets(needUpdate);
  102376. }));
  102377. this._syncActiveTargets(true);
  102378. };
  102379. /**
  102380. * Removes a target from the manager
  102381. * @param target defines the target to remove
  102382. */
  102383. MorphTargetManager.prototype.removeTarget = function (target) {
  102384. var index = this._targets.indexOf(target);
  102385. if (index >= 0) {
  102386. this._targets.splice(index, 1);
  102387. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  102388. this._syncActiveTargets(true);
  102389. }
  102390. };
  102391. /**
  102392. * Serializes the current manager into a Serialization object
  102393. * @returns the serialized object
  102394. */
  102395. MorphTargetManager.prototype.serialize = function () {
  102396. var serializationObject = {};
  102397. serializationObject.id = this.uniqueId;
  102398. serializationObject.targets = [];
  102399. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102400. var target = _a[_i];
  102401. serializationObject.targets.push(target.serialize());
  102402. }
  102403. return serializationObject;
  102404. };
  102405. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  102406. var influenceCount = 0;
  102407. this._activeTargets.reset();
  102408. this._supportsNormals = true;
  102409. this._supportsTangents = true;
  102410. this._vertexCount = 0;
  102411. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102412. var target = _a[_i];
  102413. this._activeTargets.push(target);
  102414. this._tempInfluences[influenceCount++] = target.influence;
  102415. var positions = target.getPositions();
  102416. if (positions) {
  102417. this._supportsNormals = this._supportsNormals && target.hasNormals;
  102418. this._supportsTangents = this._supportsTangents && target.hasTangents;
  102419. var vertexCount = positions.length / 3;
  102420. if (this._vertexCount === 0) {
  102421. this._vertexCount = vertexCount;
  102422. }
  102423. else if (this._vertexCount !== vertexCount) {
  102424. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  102425. return;
  102426. }
  102427. }
  102428. }
  102429. if (!this._influences || this._influences.length !== influenceCount) {
  102430. this._influences = new Float32Array(influenceCount);
  102431. }
  102432. for (var index = 0; index < influenceCount; index++) {
  102433. this._influences[index] = this._tempInfluences[index];
  102434. }
  102435. if (needUpdate) {
  102436. this.synchronize();
  102437. }
  102438. };
  102439. /**
  102440. * Syncrhonize the targets with all the meshes using this morph target manager
  102441. */
  102442. MorphTargetManager.prototype.synchronize = function () {
  102443. if (!this._scene) {
  102444. return;
  102445. }
  102446. // Flag meshes as dirty to resync with the active targets
  102447. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  102448. var mesh = _a[_i];
  102449. if (mesh.morphTargetManager === this) {
  102450. mesh._syncGeometryWithMorphTargetManager();
  102451. }
  102452. }
  102453. };
  102454. // Statics
  102455. /**
  102456. * Creates a new MorphTargetManager from serialized data
  102457. * @param serializationObject defines the serialized data
  102458. * @param scene defines the hosting scene
  102459. * @returns the new MorphTargetManager
  102460. */
  102461. MorphTargetManager.Parse = function (serializationObject, scene) {
  102462. var result = new MorphTargetManager(scene);
  102463. result._uniqueId = serializationObject.id;
  102464. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  102465. var targetData = _a[_i];
  102466. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  102467. }
  102468. return result;
  102469. };
  102470. return MorphTargetManager;
  102471. }());
  102472. BABYLON.MorphTargetManager = MorphTargetManager;
  102473. })(BABYLON || (BABYLON = {}));
  102474. //# sourceMappingURL=babylon.morphTargetManager.js.map
  102475. var BABYLON;
  102476. (function (BABYLON) {
  102477. /**
  102478. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  102479. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102480. */
  102481. var Octree = /** @class */ (function () {
  102482. /**
  102483. * Creates a octree
  102484. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102485. * @param creationFunc function to be used to instatiate the octree
  102486. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  102487. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  102488. */
  102489. function Octree(creationFunc, maxBlockCapacity,
  102490. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  102491. maxDepth) {
  102492. if (maxDepth === void 0) { maxDepth = 2; }
  102493. this.maxDepth = maxDepth;
  102494. /**
  102495. * Content stored in the octree
  102496. */
  102497. this.dynamicContent = new Array();
  102498. this._maxBlockCapacity = maxBlockCapacity || 64;
  102499. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  102500. this._creationFunc = creationFunc;
  102501. }
  102502. // Methods
  102503. /**
  102504. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  102505. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102506. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102507. * @param entries meshes to be added to the octree blocks
  102508. */
  102509. Octree.prototype.update = function (worldMin, worldMax, entries) {
  102510. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  102511. };
  102512. /**
  102513. * Adds a mesh to the octree
  102514. * @param entry Mesh to add to the octree
  102515. */
  102516. Octree.prototype.addMesh = function (entry) {
  102517. for (var index = 0; index < this.blocks.length; index++) {
  102518. var block = this.blocks[index];
  102519. block.addEntry(entry);
  102520. }
  102521. };
  102522. /**
  102523. * Selects an array of meshes within the frustum
  102524. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  102525. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  102526. * @returns array of meshes within the frustum
  102527. */
  102528. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  102529. this._selectionContent.reset();
  102530. for (var index = 0; index < this.blocks.length; index++) {
  102531. var block = this.blocks[index];
  102532. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  102533. }
  102534. if (allowDuplicate) {
  102535. this._selectionContent.concat(this.dynamicContent);
  102536. }
  102537. else {
  102538. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102539. }
  102540. return this._selectionContent;
  102541. };
  102542. /**
  102543. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  102544. * @param sphereCenter defines the bounding sphere center
  102545. * @param sphereRadius defines the bounding sphere radius
  102546. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102547. * @returns an array of objects that intersect the sphere
  102548. */
  102549. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  102550. this._selectionContent.reset();
  102551. for (var index = 0; index < this.blocks.length; index++) {
  102552. var block = this.blocks[index];
  102553. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  102554. }
  102555. if (allowDuplicate) {
  102556. this._selectionContent.concat(this.dynamicContent);
  102557. }
  102558. else {
  102559. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102560. }
  102561. return this._selectionContent;
  102562. };
  102563. /**
  102564. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  102565. * @param ray defines the ray to test with
  102566. * @returns array of intersected objects
  102567. */
  102568. Octree.prototype.intersectsRay = function (ray) {
  102569. this._selectionContent.reset();
  102570. for (var index = 0; index < this.blocks.length; index++) {
  102571. var block = this.blocks[index];
  102572. block.intersectsRay(ray, this._selectionContent);
  102573. }
  102574. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102575. return this._selectionContent;
  102576. };
  102577. /**
  102578. * @hidden
  102579. */
  102580. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  102581. target.blocks = new Array();
  102582. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102583. // Segmenting space
  102584. for (var x = 0; x < 2; x++) {
  102585. for (var y = 0; y < 2; y++) {
  102586. for (var z = 0; z < 2; z++) {
  102587. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  102588. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  102589. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  102590. block.addEntries(entries);
  102591. target.blocks.push(block);
  102592. }
  102593. }
  102594. }
  102595. };
  102596. /**
  102597. * Adds a mesh into the octree block if it intersects the block
  102598. */
  102599. Octree.CreationFuncForMeshes = function (entry, block) {
  102600. var boundingInfo = entry.getBoundingInfo();
  102601. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102602. block.entries.push(entry);
  102603. }
  102604. };
  102605. /**
  102606. * Adds a submesh into the octree block if it intersects the block
  102607. */
  102608. Octree.CreationFuncForSubMeshes = function (entry, block) {
  102609. var boundingInfo = entry.getBoundingInfo();
  102610. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102611. block.entries.push(entry);
  102612. }
  102613. };
  102614. return Octree;
  102615. }());
  102616. BABYLON.Octree = Octree;
  102617. })(BABYLON || (BABYLON = {}));
  102618. //# sourceMappingURL=babylon.octree.js.map
  102619. var BABYLON;
  102620. (function (BABYLON) {
  102621. /**
  102622. * Class used to store a cell in an octree
  102623. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102624. */
  102625. var OctreeBlock = /** @class */ (function () {
  102626. /**
  102627. * Creates a new block
  102628. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  102629. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  102630. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102631. * @param depth defines the current depth of this block in the octree
  102632. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  102633. * @param creationFunc defines a callback to call when an element is added to the block
  102634. */
  102635. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  102636. /**
  102637. * Gets the content of the current block
  102638. */
  102639. this.entries = new Array();
  102640. this._boundingVectors = new Array();
  102641. this._capacity = capacity;
  102642. this._depth = depth;
  102643. this._maxDepth = maxDepth;
  102644. this._creationFunc = creationFunc;
  102645. this._minPoint = minPoint;
  102646. this._maxPoint = maxPoint;
  102647. this._boundingVectors.push(minPoint.clone());
  102648. this._boundingVectors.push(maxPoint.clone());
  102649. this._boundingVectors.push(minPoint.clone());
  102650. this._boundingVectors[2].x = maxPoint.x;
  102651. this._boundingVectors.push(minPoint.clone());
  102652. this._boundingVectors[3].y = maxPoint.y;
  102653. this._boundingVectors.push(minPoint.clone());
  102654. this._boundingVectors[4].z = maxPoint.z;
  102655. this._boundingVectors.push(maxPoint.clone());
  102656. this._boundingVectors[5].z = minPoint.z;
  102657. this._boundingVectors.push(maxPoint.clone());
  102658. this._boundingVectors[6].x = minPoint.x;
  102659. this._boundingVectors.push(maxPoint.clone());
  102660. this._boundingVectors[7].y = minPoint.y;
  102661. }
  102662. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  102663. // Property
  102664. /**
  102665. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102666. */
  102667. get: function () {
  102668. return this._capacity;
  102669. },
  102670. enumerable: true,
  102671. configurable: true
  102672. });
  102673. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  102674. /**
  102675. * Gets the minimum vector (in world space) of the block's bounding box
  102676. */
  102677. get: function () {
  102678. return this._minPoint;
  102679. },
  102680. enumerable: true,
  102681. configurable: true
  102682. });
  102683. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  102684. /**
  102685. * Gets the maximum vector (in world space) of the block's bounding box
  102686. */
  102687. get: function () {
  102688. return this._maxPoint;
  102689. },
  102690. enumerable: true,
  102691. configurable: true
  102692. });
  102693. // Methods
  102694. /**
  102695. * Add a new element to this block
  102696. * @param entry defines the element to add
  102697. */
  102698. OctreeBlock.prototype.addEntry = function (entry) {
  102699. if (this.blocks) {
  102700. for (var index = 0; index < this.blocks.length; index++) {
  102701. var block = this.blocks[index];
  102702. block.addEntry(entry);
  102703. }
  102704. return;
  102705. }
  102706. this._creationFunc(entry, this);
  102707. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  102708. this.createInnerBlocks();
  102709. }
  102710. };
  102711. /**
  102712. * Add an array of elements to this block
  102713. * @param entries defines the array of elements to add
  102714. */
  102715. OctreeBlock.prototype.addEntries = function (entries) {
  102716. for (var index = 0; index < entries.length; index++) {
  102717. var mesh = entries[index];
  102718. this.addEntry(mesh);
  102719. }
  102720. };
  102721. /**
  102722. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  102723. * @param frustumPlanes defines the frustum planes to test
  102724. * @param selection defines the array to store current content if selection is positive
  102725. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102726. */
  102727. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  102728. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  102729. if (this.blocks) {
  102730. for (var index = 0; index < this.blocks.length; index++) {
  102731. var block = this.blocks[index];
  102732. block.select(frustumPlanes, selection, allowDuplicate);
  102733. }
  102734. return;
  102735. }
  102736. if (allowDuplicate) {
  102737. selection.concat(this.entries);
  102738. }
  102739. else {
  102740. selection.concatWithNoDuplicate(this.entries);
  102741. }
  102742. }
  102743. };
  102744. /**
  102745. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  102746. * @param sphereCenter defines the bounding sphere center
  102747. * @param sphereRadius defines the bounding sphere radius
  102748. * @param selection defines the array to store current content if selection is positive
  102749. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102750. */
  102751. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  102752. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  102753. if (this.blocks) {
  102754. for (var index = 0; index < this.blocks.length; index++) {
  102755. var block = this.blocks[index];
  102756. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  102757. }
  102758. return;
  102759. }
  102760. if (allowDuplicate) {
  102761. selection.concat(this.entries);
  102762. }
  102763. else {
  102764. selection.concatWithNoDuplicate(this.entries);
  102765. }
  102766. }
  102767. };
  102768. /**
  102769. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  102770. * @param ray defines the ray to test with
  102771. * @param selection defines the array to store current content if selection is positive
  102772. */
  102773. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  102774. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  102775. if (this.blocks) {
  102776. for (var index = 0; index < this.blocks.length; index++) {
  102777. var block = this.blocks[index];
  102778. block.intersectsRay(ray, selection);
  102779. }
  102780. return;
  102781. }
  102782. selection.concatWithNoDuplicate(this.entries);
  102783. }
  102784. };
  102785. /**
  102786. * Subdivide the content into child blocks (this block will then be empty)
  102787. */
  102788. OctreeBlock.prototype.createInnerBlocks = function () {
  102789. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  102790. };
  102791. return OctreeBlock;
  102792. }());
  102793. BABYLON.OctreeBlock = OctreeBlock;
  102794. })(BABYLON || (BABYLON = {}));
  102795. //# sourceMappingURL=babylon.octreeBlock.js.map
  102796. var BABYLON;
  102797. (function (BABYLON) {
  102798. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  102799. if (maxCapacity === void 0) { maxCapacity = 64; }
  102800. if (maxDepth === void 0) { maxDepth = 2; }
  102801. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102802. if (!component) {
  102803. component = new OctreeSceneComponent(this);
  102804. this._addComponent(component);
  102805. }
  102806. if (!this._selectionOctree) {
  102807. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  102808. }
  102809. var worldExtends = this.getWorldExtends();
  102810. // Update octree
  102811. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  102812. return this._selectionOctree;
  102813. };
  102814. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  102815. get: function () {
  102816. return this._selectionOctree;
  102817. },
  102818. enumerable: true,
  102819. configurable: true
  102820. });
  102821. /**
  102822. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  102823. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  102824. * @param maxCapacity defines the maximum size of each block (64 by default)
  102825. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  102826. * @returns the new octree
  102827. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  102828. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102829. */
  102830. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  102831. if (maxCapacity === void 0) { maxCapacity = 64; }
  102832. if (maxDepth === void 0) { maxDepth = 2; }
  102833. var scene = this.getScene();
  102834. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102835. if (!component) {
  102836. component = new OctreeSceneComponent(scene);
  102837. scene._addComponent(component);
  102838. }
  102839. if (!this._submeshesOctree) {
  102840. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  102841. }
  102842. this.computeWorldMatrix(true);
  102843. var boundingInfo = this.getBoundingInfo();
  102844. // Update octree
  102845. var bbox = boundingInfo.boundingBox;
  102846. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  102847. return this._submeshesOctree;
  102848. };
  102849. /**
  102850. * Defines the octree scene component responsible to manage any octrees
  102851. * in a given scene.
  102852. */
  102853. var OctreeSceneComponent = /** @class */ (function () {
  102854. /**
  102855. * Creates a new instance of the component for the given scene
  102856. * @param scene Defines the scene to register the component in
  102857. */
  102858. function OctreeSceneComponent(scene) {
  102859. /**
  102860. * The component name helpfull to identify the component in the list of scene components.
  102861. */
  102862. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  102863. /**
  102864. * Indicates if the meshes have been checked to make sure they are isEnabled()
  102865. */
  102866. this.checksIsEnabled = true;
  102867. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  102868. this.scene = scene;
  102869. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  102870. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  102871. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  102872. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  102873. }
  102874. /**
  102875. * Registers the component in a given scene
  102876. */
  102877. OctreeSceneComponent.prototype.register = function () {
  102878. var _this = this;
  102879. this.scene.onMeshRemovedObservable.add(function (mesh) {
  102880. var sceneOctree = _this.scene.selectionOctree;
  102881. if (sceneOctree !== undefined && sceneOctree !== null) {
  102882. var index = sceneOctree.dynamicContent.indexOf(mesh);
  102883. if (index !== -1) {
  102884. sceneOctree.dynamicContent.splice(index, 1);
  102885. }
  102886. }
  102887. });
  102888. this.scene.onMeshImportedObservable.add(function (mesh) {
  102889. var sceneOctree = _this.scene.selectionOctree;
  102890. if (sceneOctree !== undefined && sceneOctree !== null) {
  102891. sceneOctree.addMesh(mesh);
  102892. }
  102893. });
  102894. };
  102895. /**
  102896. * Return the list of active meshes
  102897. * @returns the list of active meshes
  102898. */
  102899. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  102900. if (this.scene._selectionOctree) {
  102901. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  102902. return selection;
  102903. }
  102904. return this.scene._getDefaultMeshCandidates();
  102905. };
  102906. /**
  102907. * Return the list of active sub meshes
  102908. * @param mesh The mesh to get the candidates sub meshes from
  102909. * @returns the list of active sub meshes
  102910. */
  102911. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  102912. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  102913. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  102914. return intersections;
  102915. }
  102916. return this.scene._getDefaultSubMeshCandidates(mesh);
  102917. };
  102918. /**
  102919. * Return the list of sub meshes intersecting with a given local ray
  102920. * @param mesh defines the mesh to find the submesh for
  102921. * @param localRay defines the ray in local space
  102922. * @returns the list of intersecting sub meshes
  102923. */
  102924. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  102925. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  102926. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  102927. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  102928. return intersections;
  102929. }
  102930. return this.scene._getDefaultSubMeshCandidates(mesh);
  102931. };
  102932. /**
  102933. * Return the list of sub meshes colliding with a collider
  102934. * @param mesh defines the mesh to find the submesh for
  102935. * @param collider defines the collider to evaluate the collision against
  102936. * @returns the list of colliding sub meshes
  102937. */
  102938. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  102939. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  102940. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  102941. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  102942. return intersections;
  102943. }
  102944. return this.scene._getDefaultSubMeshCandidates(mesh);
  102945. };
  102946. /**
  102947. * Rebuilds the elements related to this component in case of
  102948. * context lost for instance.
  102949. */
  102950. OctreeSceneComponent.prototype.rebuild = function () {
  102951. // Nothing to do here.
  102952. };
  102953. /**
  102954. * Disposes the component and the associated ressources.
  102955. */
  102956. OctreeSceneComponent.prototype.dispose = function () {
  102957. // Nothing to do here.
  102958. };
  102959. return OctreeSceneComponent;
  102960. }());
  102961. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  102962. })(BABYLON || (BABYLON = {}));
  102963. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  102964. var BABYLON;
  102965. (function (BABYLON) {
  102966. /**
  102967. * Postprocess used to generate anaglyphic rendering
  102968. */
  102969. var AnaglyphPostProcess = /** @class */ (function (_super) {
  102970. __extends(AnaglyphPostProcess, _super);
  102971. /**
  102972. * Creates a new AnaglyphPostProcess
  102973. * @param name defines postprocess name
  102974. * @param options defines creation options or target ratio scale
  102975. * @param rigCameras defines cameras using this postprocess
  102976. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  102977. * @param engine defines hosting engine
  102978. * @param reusable defines if the postprocess will be reused multiple times per frame
  102979. */
  102980. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  102981. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  102982. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102983. _this.onApplyObservable.add(function (effect) {
  102984. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  102985. });
  102986. return _this;
  102987. }
  102988. return AnaglyphPostProcess;
  102989. }(BABYLON.PostProcess));
  102990. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  102991. })(BABYLON || (BABYLON = {}));
  102992. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  102993. var BABYLON;
  102994. (function (BABYLON) {
  102995. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  102996. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102997. });
  102998. /**
  102999. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  103000. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103001. */
  103002. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  103003. __extends(AnaglyphArcRotateCamera, _super);
  103004. /**
  103005. * Creates a new AnaglyphArcRotateCamera
  103006. * @param name defines camera name
  103007. * @param alpha defines alpha angle (in radians)
  103008. * @param beta defines beta angle (in radians)
  103009. * @param radius defines radius
  103010. * @param target defines camera target
  103011. * @param interaxialDistance defines distance between each color axis
  103012. * @param scene defines the hosting scene
  103013. */
  103014. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  103015. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  103016. _this.interaxialDistance = interaxialDistance;
  103017. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103018. return _this;
  103019. }
  103020. /**
  103021. * Gets camera class name
  103022. * @returns AnaglyphArcRotateCamera
  103023. */
  103024. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  103025. return "AnaglyphArcRotateCamera";
  103026. };
  103027. return AnaglyphArcRotateCamera;
  103028. }(BABYLON.ArcRotateCamera));
  103029. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  103030. })(BABYLON || (BABYLON = {}));
  103031. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  103032. var BABYLON;
  103033. (function (BABYLON) {
  103034. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  103035. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103036. });
  103037. /**
  103038. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  103039. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103040. */
  103041. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  103042. __extends(AnaglyphFreeCamera, _super);
  103043. /**
  103044. * Creates a new AnaglyphFreeCamera
  103045. * @param name defines camera name
  103046. * @param position defines initial position
  103047. * @param interaxialDistance defines distance between each color axis
  103048. * @param scene defines the hosting scene
  103049. */
  103050. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  103051. var _this = _super.call(this, name, position, scene) || this;
  103052. _this.interaxialDistance = interaxialDistance;
  103053. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103054. return _this;
  103055. }
  103056. /**
  103057. * Gets camera class name
  103058. * @returns AnaglyphFreeCamera
  103059. */
  103060. AnaglyphFreeCamera.prototype.getClassName = function () {
  103061. return "AnaglyphFreeCamera";
  103062. };
  103063. return AnaglyphFreeCamera;
  103064. }(BABYLON.FreeCamera));
  103065. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  103066. })(BABYLON || (BABYLON = {}));
  103067. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  103068. var BABYLON;
  103069. (function (BABYLON) {
  103070. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  103071. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103072. });
  103073. /**
  103074. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  103075. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103076. */
  103077. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  103078. __extends(AnaglyphGamepadCamera, _super);
  103079. /**
  103080. * Creates a new AnaglyphGamepadCamera
  103081. * @param name defines camera name
  103082. * @param position defines initial position
  103083. * @param interaxialDistance defines distance between each color axis
  103084. * @param scene defines the hosting scene
  103085. */
  103086. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  103087. var _this = _super.call(this, name, position, scene) || this;
  103088. _this.interaxialDistance = interaxialDistance;
  103089. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103090. return _this;
  103091. }
  103092. /**
  103093. * Gets camera class name
  103094. * @returns AnaglyphGamepadCamera
  103095. */
  103096. AnaglyphGamepadCamera.prototype.getClassName = function () {
  103097. return "AnaglyphGamepadCamera";
  103098. };
  103099. return AnaglyphGamepadCamera;
  103100. }(BABYLON.GamepadCamera));
  103101. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  103102. })(BABYLON || (BABYLON = {}));
  103103. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  103104. var BABYLON;
  103105. (function (BABYLON) {
  103106. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  103107. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  103108. });
  103109. /**
  103110. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  103111. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  103112. */
  103113. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  103114. __extends(AnaglyphUniversalCamera, _super);
  103115. /**
  103116. * Creates a new AnaglyphUniversalCamera
  103117. * @param name defines camera name
  103118. * @param position defines initial position
  103119. * @param interaxialDistance defines distance between each color axis
  103120. * @param scene defines the hosting scene
  103121. */
  103122. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  103123. var _this = _super.call(this, name, position, scene) || this;
  103124. _this.interaxialDistance = interaxialDistance;
  103125. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  103126. return _this;
  103127. }
  103128. /**
  103129. * Gets camera class name
  103130. * @returns AnaglyphUniversalCamera
  103131. */
  103132. AnaglyphUniversalCamera.prototype.getClassName = function () {
  103133. return "AnaglyphUniversalCamera";
  103134. };
  103135. return AnaglyphUniversalCamera;
  103136. }(BABYLON.UniversalCamera));
  103137. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  103138. })(BABYLON || (BABYLON = {}));
  103139. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  103140. var BABYLON;
  103141. (function (BABYLON) {
  103142. /**
  103143. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  103144. */
  103145. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  103146. __extends(StereoscopicInterlacePostProcess, _super);
  103147. /**
  103148. * Initializes a StereoscopicInterlacePostProcess
  103149. * @param name The name of the effect.
  103150. * @param rigCameras The rig cameras to be appled to the post process
  103151. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  103152. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  103153. * @param engine The engine which the post process will be applied. (default: current engine)
  103154. * @param reusable If the post process can be reused on the same frame. (default: false)
  103155. */
  103156. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  103157. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  103158. _this._passedProcess = rigCameras[0]._rigPostProcess;
  103159. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  103160. _this.onSizeChangedObservable.add(function () {
  103161. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  103162. });
  103163. _this.onApplyObservable.add(function (effect) {
  103164. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  103165. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  103166. });
  103167. return _this;
  103168. }
  103169. return StereoscopicInterlacePostProcess;
  103170. }(BABYLON.PostProcess));
  103171. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  103172. })(BABYLON || (BABYLON = {}));
  103173. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  103174. var BABYLON;
  103175. (function (BABYLON) {
  103176. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  103177. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103178. });
  103179. /**
  103180. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  103181. * @see http://doc.babylonjs.com/features/cameras
  103182. */
  103183. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  103184. __extends(StereoscopicArcRotateCamera, _super);
  103185. /**
  103186. * Creates a new StereoscopicArcRotateCamera
  103187. * @param name defines camera name
  103188. * @param alpha defines alpha angle (in radians)
  103189. * @param beta defines beta angle (in radians)
  103190. * @param radius defines radius
  103191. * @param target defines camera target
  103192. * @param interaxialDistance defines distance between each color axis
  103193. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103194. * @param scene defines the hosting scene
  103195. */
  103196. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  103197. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  103198. _this.interaxialDistance = interaxialDistance;
  103199. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103200. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103201. return _this;
  103202. }
  103203. /**
  103204. * Gets camera class name
  103205. * @returns StereoscopicArcRotateCamera
  103206. */
  103207. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  103208. return "StereoscopicArcRotateCamera";
  103209. };
  103210. return StereoscopicArcRotateCamera;
  103211. }(BABYLON.ArcRotateCamera));
  103212. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  103213. })(BABYLON || (BABYLON = {}));
  103214. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  103215. var BABYLON;
  103216. (function (BABYLON) {
  103217. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103218. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103219. });
  103220. /**
  103221. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  103222. * @see http://doc.babylonjs.com/features/cameras
  103223. */
  103224. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  103225. __extends(StereoscopicFreeCamera, _super);
  103226. /**
  103227. * Creates a new StereoscopicFreeCamera
  103228. * @param name defines camera name
  103229. * @param position defines initial position
  103230. * @param interaxialDistance defines distance between each color axis
  103231. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103232. * @param scene defines the hosting scene
  103233. */
  103234. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103235. var _this = _super.call(this, name, position, scene) || this;
  103236. _this.interaxialDistance = interaxialDistance;
  103237. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103238. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103239. return _this;
  103240. }
  103241. /**
  103242. * Gets camera class name
  103243. * @returns StereoscopicFreeCamera
  103244. */
  103245. StereoscopicFreeCamera.prototype.getClassName = function () {
  103246. return "StereoscopicFreeCamera";
  103247. };
  103248. return StereoscopicFreeCamera;
  103249. }(BABYLON.FreeCamera));
  103250. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  103251. })(BABYLON || (BABYLON = {}));
  103252. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  103253. var BABYLON;
  103254. (function (BABYLON) {
  103255. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  103256. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103257. });
  103258. /**
  103259. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  103260. * @see http://doc.babylonjs.com/features/cameras
  103261. */
  103262. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  103263. __extends(StereoscopicGamepadCamera, _super);
  103264. /**
  103265. * Creates a new StereoscopicGamepadCamera
  103266. * @param name defines camera name
  103267. * @param position defines initial position
  103268. * @param interaxialDistance defines distance between each color axis
  103269. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103270. * @param scene defines the hosting scene
  103271. */
  103272. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103273. var _this = _super.call(this, name, position, scene) || this;
  103274. _this.interaxialDistance = interaxialDistance;
  103275. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103276. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103277. return _this;
  103278. }
  103279. /**
  103280. * Gets camera class name
  103281. * @returns StereoscopicGamepadCamera
  103282. */
  103283. StereoscopicGamepadCamera.prototype.getClassName = function () {
  103284. return "StereoscopicGamepadCamera";
  103285. };
  103286. return StereoscopicGamepadCamera;
  103287. }(BABYLON.GamepadCamera));
  103288. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  103289. })(BABYLON || (BABYLON = {}));
  103290. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  103291. var BABYLON;
  103292. (function (BABYLON) {
  103293. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103294. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103295. });
  103296. /**
  103297. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  103298. * @see http://doc.babylonjs.com/features/cameras
  103299. */
  103300. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  103301. __extends(StereoscopicUniversalCamera, _super);
  103302. /**
  103303. * Creates a new StereoscopicUniversalCamera
  103304. * @param name defines camera name
  103305. * @param position defines initial position
  103306. * @param interaxialDistance defines distance between each color axis
  103307. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103308. * @param scene defines the hosting scene
  103309. */
  103310. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103311. var _this = _super.call(this, name, position, scene) || this;
  103312. _this.interaxialDistance = interaxialDistance;
  103313. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103314. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103315. return _this;
  103316. }
  103317. /**
  103318. * Gets camera class name
  103319. * @returns StereoscopicUniversalCamera
  103320. */
  103321. StereoscopicUniversalCamera.prototype.getClassName = function () {
  103322. return "StereoscopicUniversalCamera";
  103323. };
  103324. return StereoscopicUniversalCamera;
  103325. }(BABYLON.UniversalCamera));
  103326. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  103327. })(BABYLON || (BABYLON = {}));
  103328. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  103329. var BABYLON;
  103330. (function (BABYLON) {
  103331. /**
  103332. * VRDistortionCorrectionPostProcess used for mobile VR
  103333. */
  103334. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  103335. __extends(VRDistortionCorrectionPostProcess, _super);
  103336. /**
  103337. * Initializes the VRDistortionCorrectionPostProcess
  103338. * @param name The name of the effect.
  103339. * @param camera The camera to apply the render pass to.
  103340. * @param isRightEye If this is for the right eye distortion
  103341. * @param vrMetrics All the required metrics for the VR camera
  103342. */
  103343. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  103344. var _this = _super.call(this, name, "vrDistortionCorrection", [
  103345. 'LensCenter',
  103346. 'Scale',
  103347. 'ScaleIn',
  103348. 'HmdWarpParam'
  103349. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  103350. _this._isRightEye = isRightEye;
  103351. _this._distortionFactors = vrMetrics.distortionK;
  103352. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  103353. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  103354. _this.adaptScaleToCurrentViewport = true;
  103355. _this.onSizeChangedObservable.add(function () {
  103356. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  103357. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  103358. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  103359. });
  103360. _this.onApplyObservable.add(function (effect) {
  103361. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  103362. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  103363. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  103364. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  103365. });
  103366. return _this;
  103367. }
  103368. return VRDistortionCorrectionPostProcess;
  103369. }(BABYLON.PostProcess));
  103370. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  103371. })(BABYLON || (BABYLON = {}));
  103372. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  103373. var BABYLON;
  103374. (function (BABYLON) {
  103375. /**
  103376. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  103377. * Screen rotation is taken into account.
  103378. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103379. */
  103380. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  103381. /**
  103382. * Instantiates a new input
  103383. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103384. */
  103385. function FreeCameraDeviceOrientationInput() {
  103386. var _this = this;
  103387. this._screenOrientationAngle = 0;
  103388. this._screenQuaternion = new BABYLON.Quaternion();
  103389. this._alpha = 0;
  103390. this._beta = 0;
  103391. this._gamma = 0;
  103392. this._orientationChanged = function () {
  103393. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  103394. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  103395. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  103396. };
  103397. this._deviceOrientation = function (evt) {
  103398. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  103399. _this._beta = evt.beta !== null ? evt.beta : 0;
  103400. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  103401. };
  103402. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  103403. this._orientationChanged();
  103404. }
  103405. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  103406. /**
  103407. * Define the camera controlled by the input.
  103408. */
  103409. get: function () {
  103410. return this._camera;
  103411. },
  103412. set: function (camera) {
  103413. this._camera = camera;
  103414. if (this._camera != null && !this._camera.rotationQuaternion) {
  103415. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  103416. }
  103417. },
  103418. enumerable: true,
  103419. configurable: true
  103420. });
  103421. /**
  103422. * Attach the input controls to a specific dom element to get the input from.
  103423. * @param element Defines the element the controls should be listened from
  103424. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103425. */
  103426. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103427. window.addEventListener("orientationchange", this._orientationChanged);
  103428. window.addEventListener("deviceorientation", this._deviceOrientation);
  103429. //In certain cases, the attach control is called AFTER orientation was changed,
  103430. //So this is needed.
  103431. this._orientationChanged();
  103432. };
  103433. /**
  103434. * Detach the current controls from the specified dom element.
  103435. * @param element Defines the element to stop listening the inputs from
  103436. */
  103437. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  103438. window.removeEventListener("orientationchange", this._orientationChanged);
  103439. window.removeEventListener("deviceorientation", this._deviceOrientation);
  103440. };
  103441. /**
  103442. * Update the current camera state depending on the inputs that have been used this frame.
  103443. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103444. */
  103445. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  103446. //if no device orientation provided, don't update the rotation.
  103447. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  103448. if (!this._alpha) {
  103449. return;
  103450. }
  103451. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  103452. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  103453. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  103454. //Mirror on XY Plane
  103455. this._camera.rotationQuaternion.z *= -1;
  103456. this._camera.rotationQuaternion.w *= -1;
  103457. };
  103458. /**
  103459. * Gets the class name of the current intput.
  103460. * @returns the class name
  103461. */
  103462. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  103463. return "FreeCameraDeviceOrientationInput";
  103464. };
  103465. /**
  103466. * Get the friendly name associated with the input class.
  103467. * @returns the input friendly name
  103468. */
  103469. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  103470. return "deviceOrientation";
  103471. };
  103472. return FreeCameraDeviceOrientationInput;
  103473. }());
  103474. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  103475. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  103476. })(BABYLON || (BABYLON = {}));
  103477. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  103478. var BABYLON;
  103479. (function (BABYLON) {
  103480. /**
  103481. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  103482. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103483. */
  103484. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  103485. /**
  103486. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  103487. */
  103488. function ArcRotateCameraVRDeviceOrientationInput() {
  103489. /**
  103490. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  103491. */
  103492. this.alphaCorrection = 1;
  103493. /**
  103494. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  103495. */
  103496. this.betaCorrection = 1;
  103497. /**
  103498. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  103499. */
  103500. this.gammaCorrection = 1;
  103501. this._alpha = 0;
  103502. this._gamma = 0;
  103503. this._dirty = false;
  103504. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  103505. }
  103506. /**
  103507. * Attach the input controls to a specific dom element to get the input from.
  103508. * @param element Defines the element the controls should be listened from
  103509. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103510. */
  103511. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103512. this.camera.attachControl(element, noPreventDefault);
  103513. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  103514. };
  103515. /** @hidden */
  103516. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  103517. if (evt.alpha !== null) {
  103518. this._alpha = +evt.alpha | 0;
  103519. }
  103520. if (evt.gamma !== null) {
  103521. this._gamma = +evt.gamma | 0;
  103522. }
  103523. this._dirty = true;
  103524. };
  103525. /**
  103526. * Update the current camera state depending on the inputs that have been used this frame.
  103527. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103528. */
  103529. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  103530. if (this._dirty) {
  103531. this._dirty = false;
  103532. if (this._gamma < 0) {
  103533. this._gamma = 180 + this._gamma;
  103534. }
  103535. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  103536. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  103537. }
  103538. };
  103539. /**
  103540. * Detach the current controls from the specified dom element.
  103541. * @param element Defines the element to stop listening the inputs from
  103542. */
  103543. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  103544. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  103545. };
  103546. /**
  103547. * Gets the class name of the current intput.
  103548. * @returns the class name
  103549. */
  103550. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  103551. return "ArcRotateCameraVRDeviceOrientationInput";
  103552. };
  103553. /**
  103554. * Get the friendly name associated with the input class.
  103555. * @returns the input friendly name
  103556. */
  103557. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  103558. return "VRDeviceOrientation";
  103559. };
  103560. return ArcRotateCameraVRDeviceOrientationInput;
  103561. }());
  103562. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  103563. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  103564. })(BABYLON || (BABYLON = {}));
  103565. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  103566. var BABYLON;
  103567. (function (BABYLON) {
  103568. /**
  103569. * This represents all the required metrics to create a VR camera.
  103570. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  103571. */
  103572. var VRCameraMetrics = /** @class */ (function () {
  103573. function VRCameraMetrics() {
  103574. /**
  103575. * Define if the current vr camera should compensate the distortion of the lense or not.
  103576. */
  103577. this.compensateDistortion = true;
  103578. }
  103579. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  103580. /**
  103581. * Gets the rendering aspect ratio based on the provided resolutions.
  103582. */
  103583. get: function () {
  103584. return this.hResolution / (2 * this.vResolution);
  103585. },
  103586. enumerable: true,
  103587. configurable: true
  103588. });
  103589. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  103590. /**
  103591. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  103592. */
  103593. get: function () {
  103594. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  103595. },
  103596. enumerable: true,
  103597. configurable: true
  103598. });
  103599. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  103600. /**
  103601. * @hidden
  103602. */
  103603. get: function () {
  103604. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103605. var h = (4 * meters) / this.hScreenSize;
  103606. return BABYLON.Matrix.Translation(h, 0, 0);
  103607. },
  103608. enumerable: true,
  103609. configurable: true
  103610. });
  103611. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  103612. /**
  103613. * @hidden
  103614. */
  103615. get: function () {
  103616. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103617. var h = (4 * meters) / this.hScreenSize;
  103618. return BABYLON.Matrix.Translation(-h, 0, 0);
  103619. },
  103620. enumerable: true,
  103621. configurable: true
  103622. });
  103623. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  103624. /**
  103625. * @hidden
  103626. */
  103627. get: function () {
  103628. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  103629. },
  103630. enumerable: true,
  103631. configurable: true
  103632. });
  103633. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  103634. /**
  103635. * @hidden
  103636. */
  103637. get: function () {
  103638. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  103639. },
  103640. enumerable: true,
  103641. configurable: true
  103642. });
  103643. /**
  103644. * Get the default VRMetrics based on the most generic setup.
  103645. * @returns the default vr metrics
  103646. */
  103647. VRCameraMetrics.GetDefault = function () {
  103648. var result = new VRCameraMetrics();
  103649. result.hResolution = 1280;
  103650. result.vResolution = 800;
  103651. result.hScreenSize = 0.149759993;
  103652. result.vScreenSize = 0.0935999975;
  103653. result.vScreenCenter = 0.0467999987;
  103654. result.eyeToScreenDistance = 0.0410000011;
  103655. result.lensSeparationDistance = 0.0635000020;
  103656. result.interpupillaryDistance = 0.0640000030;
  103657. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  103658. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  103659. result.postProcessScaleFactor = 1.714605507808412;
  103660. result.lensCenterOffset = 0.151976421;
  103661. return result;
  103662. };
  103663. return VRCameraMetrics;
  103664. }());
  103665. BABYLON.VRCameraMetrics = VRCameraMetrics;
  103666. })(BABYLON || (BABYLON = {}));
  103667. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  103668. var BABYLON;
  103669. (function (BABYLON) {
  103670. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  103671. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103672. });
  103673. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  103674. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103675. });
  103676. /**
  103677. * This represents a WebVR camera.
  103678. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  103679. * @example http://doc.babylonjs.com/how_to/webvr_camera
  103680. */
  103681. var WebVRFreeCamera = /** @class */ (function (_super) {
  103682. __extends(WebVRFreeCamera, _super);
  103683. /**
  103684. * Instantiates a WebVRFreeCamera.
  103685. * @param name The name of the WebVRFreeCamera
  103686. * @param position The starting anchor position for the camera
  103687. * @param scene The scene the camera belongs to
  103688. * @param webVROptions a set of customizable options for the webVRCamera
  103689. */
  103690. function WebVRFreeCamera(name, position, scene, webVROptions) {
  103691. if (webVROptions === void 0) { webVROptions = {}; }
  103692. var _this = _super.call(this, name, position, scene) || this;
  103693. _this.webVROptions = webVROptions;
  103694. /**
  103695. * @hidden
  103696. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  103697. */
  103698. _this._vrDevice = null;
  103699. /**
  103700. * The rawPose of the vrDevice.
  103701. */
  103702. _this.rawPose = null;
  103703. _this._specsVersion = "1.1";
  103704. _this._attached = false;
  103705. _this._descendants = [];
  103706. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  103707. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  103708. /** @hidden */
  103709. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  103710. _this._standingMatrix = null;
  103711. /**
  103712. * Represents device position in babylon space.
  103713. */
  103714. _this.devicePosition = BABYLON.Vector3.Zero();
  103715. /**
  103716. * Represents device rotation in babylon space.
  103717. */
  103718. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  103719. /**
  103720. * The scale of the device to be used when translating from device space to babylon space.
  103721. */
  103722. _this.deviceScaleFactor = 1;
  103723. _this._deviceToWorld = BABYLON.Matrix.Identity();
  103724. _this._worldToDevice = BABYLON.Matrix.Identity();
  103725. /**
  103726. * References to the webVR controllers for the vrDevice.
  103727. */
  103728. _this.controllers = [];
  103729. /**
  103730. * Emits an event when a controller is attached.
  103731. */
  103732. _this.onControllersAttachedObservable = new BABYLON.Observable();
  103733. /**
  103734. * Emits an event when a controller's mesh has been loaded;
  103735. */
  103736. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  103737. /**
  103738. * Emits an event when the HMD's pose has been updated.
  103739. */
  103740. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  103741. _this._poseSet = false;
  103742. /**
  103743. * If the rig cameras be used as parent instead of this camera.
  103744. */
  103745. _this.rigParenting = true;
  103746. _this._defaultHeight = undefined;
  103747. _this._htmlElementAttached = null;
  103748. _this._detachIfAttached = function () {
  103749. var vrDisplay = _this.getEngine().getVRDevice();
  103750. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  103751. _this.detachControl(_this._htmlElementAttached);
  103752. }
  103753. };
  103754. _this._workingVector = BABYLON.Vector3.Zero();
  103755. _this._oneVector = BABYLON.Vector3.One();
  103756. _this._workingMatrix = BABYLON.Matrix.Identity();
  103757. _this._tmpMatrix = new BABYLON.Matrix();
  103758. _this._cache.position = BABYLON.Vector3.Zero();
  103759. if (webVROptions.defaultHeight) {
  103760. _this._defaultHeight = webVROptions.defaultHeight;
  103761. _this.position.y = _this._defaultHeight;
  103762. }
  103763. _this.minZ = 0.1;
  103764. //legacy support - the compensation boolean was removed.
  103765. if (arguments.length === 5) {
  103766. _this.webVROptions = arguments[4];
  103767. }
  103768. // default webVR options
  103769. if (_this.webVROptions.trackPosition == undefined) {
  103770. _this.webVROptions.trackPosition = true;
  103771. }
  103772. if (_this.webVROptions.controllerMeshes == undefined) {
  103773. _this.webVROptions.controllerMeshes = true;
  103774. }
  103775. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  103776. _this.webVROptions.defaultLightingOnControllers = true;
  103777. }
  103778. _this.rotationQuaternion = new BABYLON.Quaternion();
  103779. if (_this.webVROptions && _this.webVROptions.positionScale) {
  103780. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  103781. }
  103782. //enable VR
  103783. var engine = _this.getEngine();
  103784. _this._onVREnabled = function (success) { if (success) {
  103785. _this.initControllers();
  103786. } };
  103787. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  103788. engine.initWebVR().add(function (event) {
  103789. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  103790. return;
  103791. }
  103792. _this._vrDevice = event.vrDisplay;
  103793. //reset the rig parameters.
  103794. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  103795. if (_this._attached) {
  103796. _this.getEngine().enableVR();
  103797. }
  103798. });
  103799. if (typeof (VRFrameData) !== "undefined") {
  103800. _this._frameData = new VRFrameData();
  103801. }
  103802. /**
  103803. * The idea behind the following lines:
  103804. * objects that have the camera as parent should actually have the rig cameras as a parent.
  103805. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  103806. * the second will not show it correctly.
  103807. *
  103808. * To solve this - each object that has the camera as parent will be added to a protected array.
  103809. * When the rig camera renders, it will take this array and set all of those to be its children.
  103810. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  103811. * Amazing!
  103812. */
  103813. scene.onBeforeCameraRenderObservable.add(function (camera) {
  103814. if (camera.parent === _this && _this.rigParenting) {
  103815. _this._descendants = _this.getDescendants(true, function (n) {
  103816. // don't take the cameras or the controllers!
  103817. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  103818. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  103819. return !isController && !isRigCamera;
  103820. });
  103821. _this._descendants.forEach(function (node) {
  103822. node.parent = camera;
  103823. });
  103824. }
  103825. });
  103826. scene.onAfterCameraRenderObservable.add(function (camera) {
  103827. if (camera.parent === _this && _this.rigParenting) {
  103828. _this._descendants.forEach(function (node) {
  103829. node.parent = _this;
  103830. });
  103831. }
  103832. });
  103833. return _this;
  103834. }
  103835. /**
  103836. * Gets the device distance from the ground in meters.
  103837. * @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.
  103838. */
  103839. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  103840. if (this._standingMatrix) {
  103841. // Add standing matrix offset to get real offset from ground in room
  103842. this._standingMatrix.getTranslationToRef(this._workingVector);
  103843. return this._deviceRoomPosition.y + this._workingVector.y;
  103844. }
  103845. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  103846. return this._defaultHeight || 0;
  103847. };
  103848. /**
  103849. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103850. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  103851. */
  103852. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  103853. var _this = this;
  103854. if (callback === void 0) { callback = function (bool) { }; }
  103855. // Use standing matrix if available
  103856. this.getEngine().initWebVRAsync().then(function (result) {
  103857. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  103858. callback(false);
  103859. }
  103860. else {
  103861. _this._standingMatrix = new BABYLON.Matrix();
  103862. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  103863. if (!_this.getScene().useRightHandedSystem) {
  103864. [2, 6, 8, 9, 14].forEach(function (num) {
  103865. if (_this._standingMatrix) {
  103866. _this._standingMatrix.m[num] *= -1;
  103867. }
  103868. });
  103869. }
  103870. callback(true);
  103871. }
  103872. });
  103873. };
  103874. /**
  103875. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103876. * @returns A promise with a boolean set to if the standing matrix is supported.
  103877. */
  103878. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  103879. var _this = this;
  103880. return new Promise(function (res, rej) {
  103881. _this.useStandingMatrix(function (supported) {
  103882. res(supported);
  103883. });
  103884. });
  103885. };
  103886. /**
  103887. * Disposes the camera
  103888. */
  103889. WebVRFreeCamera.prototype.dispose = function () {
  103890. this._detachIfAttached();
  103891. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  103892. if (this._updateCacheWhenTrackingDisabledObserver) {
  103893. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  103894. }
  103895. _super.prototype.dispose.call(this);
  103896. };
  103897. /**
  103898. * Gets a vrController by name.
  103899. * @param name The name of the controller to retreive
  103900. * @returns the controller matching the name specified or null if not found
  103901. */
  103902. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  103903. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  103904. var gp = _a[_i];
  103905. if (gp.hand === name) {
  103906. return gp;
  103907. }
  103908. }
  103909. return null;
  103910. };
  103911. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  103912. /**
  103913. * The controller corrisponding to the users left hand.
  103914. */
  103915. get: function () {
  103916. if (!this._leftController) {
  103917. this._leftController = this.getControllerByName("left");
  103918. }
  103919. return this._leftController;
  103920. },
  103921. enumerable: true,
  103922. configurable: true
  103923. });
  103924. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  103925. /**
  103926. * The controller corrisponding to the users right hand.
  103927. */
  103928. get: function () {
  103929. if (!this._rightController) {
  103930. this._rightController = this.getControllerByName("right");
  103931. }
  103932. return this._rightController;
  103933. },
  103934. enumerable: true,
  103935. configurable: true
  103936. });
  103937. /**
  103938. * Casts a ray forward from the vrCamera's gaze.
  103939. * @param length Length of the ray (default: 100)
  103940. * @returns the ray corrisponding to the gaze
  103941. */
  103942. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  103943. if (length === void 0) { length = 100; }
  103944. if (this.leftCamera) {
  103945. // Use left eye to avoid computation to compute center on every call
  103946. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  103947. }
  103948. else {
  103949. return _super.prototype.getForwardRay.call(this, length);
  103950. }
  103951. };
  103952. /**
  103953. * @hidden
  103954. * Updates the camera based on device's frame data
  103955. */
  103956. WebVRFreeCamera.prototype._checkInputs = function () {
  103957. if (this._vrDevice && this._vrDevice.isPresenting) {
  103958. this._vrDevice.getFrameData(this._frameData);
  103959. this.updateFromDevice(this._frameData.pose);
  103960. }
  103961. _super.prototype._checkInputs.call(this);
  103962. };
  103963. /**
  103964. * Updates the poseControlled values based on the input device pose.
  103965. * @param poseData Pose coming from the device
  103966. */
  103967. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  103968. if (poseData && poseData.orientation) {
  103969. this.rawPose = poseData;
  103970. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  103971. if (this.getScene().useRightHandedSystem) {
  103972. this._deviceRoomRotationQuaternion.z *= -1;
  103973. this._deviceRoomRotationQuaternion.w *= -1;
  103974. }
  103975. if (this.webVROptions.trackPosition && this.rawPose.position) {
  103976. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  103977. if (this.getScene().useRightHandedSystem) {
  103978. this._deviceRoomPosition.z *= -1;
  103979. }
  103980. }
  103981. this._poseSet = true;
  103982. }
  103983. };
  103984. /**
  103985. * WebVR's attach control will start broadcasting frames to the device.
  103986. * Note that in certain browsers (chrome for example) this function must be called
  103987. * within a user-interaction callback. Example:
  103988. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  103989. *
  103990. * @param element html element to attach the vrDevice to
  103991. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  103992. */
  103993. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  103994. _super.prototype.attachControl.call(this, element, noPreventDefault);
  103995. this._attached = true;
  103996. this._htmlElementAttached = element;
  103997. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  103998. if (this._vrDevice) {
  103999. this.getEngine().enableVR();
  104000. }
  104001. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  104002. };
  104003. /**
  104004. * Detaches the camera from the html element and disables VR
  104005. *
  104006. * @param element html element to detach from
  104007. */
  104008. WebVRFreeCamera.prototype.detachControl = function (element) {
  104009. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  104010. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  104011. _super.prototype.detachControl.call(this, element);
  104012. this._attached = false;
  104013. this.getEngine().disableVR();
  104014. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  104015. };
  104016. /**
  104017. * @returns the name of this class
  104018. */
  104019. WebVRFreeCamera.prototype.getClassName = function () {
  104020. return "WebVRFreeCamera";
  104021. };
  104022. /**
  104023. * Calls resetPose on the vrDisplay
  104024. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  104025. */
  104026. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  104027. //uses the vrDisplay's "resetPose()".
  104028. //pitch and roll won't be affected.
  104029. this._vrDevice.resetPose();
  104030. };
  104031. /**
  104032. * @hidden
  104033. * Updates the rig cameras (left and right eye)
  104034. */
  104035. WebVRFreeCamera.prototype._updateRigCameras = function () {
  104036. var camLeft = this._rigCameras[0];
  104037. var camRight = this._rigCameras[1];
  104038. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  104039. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  104040. camLeft.position.copyFrom(this._deviceRoomPosition);
  104041. camRight.position.copyFrom(this._deviceRoomPosition);
  104042. };
  104043. // Remove translation from 6dof headset if trackposition is set to false
  104044. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  104045. if (isViewMatrix === void 0) { isViewMatrix = false; }
  104046. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  104047. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  104048. if (!isViewMatrix) {
  104049. this._tmpMatrix.invert();
  104050. }
  104051. this._tmpMatrix.multiplyToRef(matrix, matrix);
  104052. }
  104053. };
  104054. /**
  104055. * @hidden
  104056. * Updates the cached values of the camera
  104057. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  104058. */
  104059. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  104060. var _this = this;
  104061. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  104062. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  104063. if (!this.updateCacheCalled) {
  104064. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  104065. this.updateCacheCalled = true;
  104066. this.update();
  104067. }
  104068. // Set working vector to the device position in room space rotated by the new rotation
  104069. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  104070. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  104071. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  104072. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  104073. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  104074. // Add translation from anchor position
  104075. this._deviceToWorld.getTranslationToRef(this._workingVector);
  104076. this._workingVector.addInPlace(this.position);
  104077. this._workingVector.subtractInPlace(this._cache.position);
  104078. this._deviceToWorld.setTranslation(this._workingVector);
  104079. // Set an inverted matrix to be used when updating the camera
  104080. this._deviceToWorld.invertToRef(this._worldToDevice);
  104081. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  104082. this.controllers.forEach(function (controller) {
  104083. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  104084. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  104085. controller.update();
  104086. });
  104087. }
  104088. if (!ignoreParentClass) {
  104089. _super.prototype._updateCache.call(this);
  104090. }
  104091. this.updateCacheCalled = false;
  104092. };
  104093. /**
  104094. * @hidden
  104095. * Get current device position in babylon world
  104096. */
  104097. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  104098. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  104099. };
  104100. /**
  104101. * Updates the current device position and rotation in the babylon world
  104102. */
  104103. WebVRFreeCamera.prototype.update = function () {
  104104. this._computeDevicePosition();
  104105. // Get current device rotation in babylon world
  104106. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  104107. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  104108. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  104109. if (this._poseSet) {
  104110. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  104111. }
  104112. _super.prototype.update.call(this);
  104113. };
  104114. /**
  104115. * @hidden
  104116. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  104117. * @returns an identity matrix
  104118. */
  104119. WebVRFreeCamera.prototype._getViewMatrix = function () {
  104120. return BABYLON.Matrix.Identity();
  104121. };
  104122. /**
  104123. * This function is called by the two RIG cameras.
  104124. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  104125. */
  104126. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  104127. var _this = this;
  104128. // Update the parent camera prior to using a child camera to avoid desynchronization
  104129. var parentCamera = this._cameraRigParams["parentCamera"];
  104130. parentCamera._updateCache();
  104131. //WebVR 1.1
  104132. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  104133. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  104134. if (!this.getScene().useRightHandedSystem) {
  104135. [2, 6, 8, 9, 14].forEach(function (num) {
  104136. _this._webvrViewMatrix.m[num] *= -1;
  104137. });
  104138. }
  104139. // update the camera rotation matrix
  104140. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  104141. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  104142. // Computing target and final matrix
  104143. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  104144. // should the view matrix be updated with scale and position offset?
  104145. if (parentCamera.deviceScaleFactor !== 1) {
  104146. this._webvrViewMatrix.invert();
  104147. // scale the position, if set
  104148. if (parentCamera.deviceScaleFactor) {
  104149. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  104150. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  104151. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  104152. }
  104153. this._webvrViewMatrix.invert();
  104154. }
  104155. // Remove translation from 6dof headset if trackposition is set to false
  104156. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  104157. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  104158. // Compute global position
  104159. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  104160. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  104161. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  104162. this._workingMatrix.getTranslationToRef(this._globalPosition);
  104163. this._markSyncedWithParent();
  104164. return this._webvrViewMatrix;
  104165. };
  104166. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  104167. var _this = this;
  104168. var parentCamera = this.parent;
  104169. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  104170. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  104171. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  104172. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  104173. //babylon compatible matrix
  104174. if (!this.getScene().useRightHandedSystem) {
  104175. [8, 9, 10, 11].forEach(function (num) {
  104176. _this._projectionMatrix.m[num] *= -1;
  104177. });
  104178. }
  104179. return this._projectionMatrix;
  104180. };
  104181. /**
  104182. * Initializes the controllers and their meshes
  104183. */
  104184. WebVRFreeCamera.prototype.initControllers = function () {
  104185. var _this = this;
  104186. this.controllers = [];
  104187. var manager = this.getScene().gamepadManager;
  104188. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  104189. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  104190. var webVrController = gamepad;
  104191. if (webVrController.defaultModel) {
  104192. webVrController.defaultModel.setEnabled(false);
  104193. }
  104194. if (webVrController.hand === "right") {
  104195. _this._rightController = null;
  104196. }
  104197. if (webVrController.hand === "left") {
  104198. _this._leftController = null;
  104199. }
  104200. var controllerIndex = _this.controllers.indexOf(webVrController);
  104201. if (controllerIndex !== -1) {
  104202. _this.controllers.splice(controllerIndex, 1);
  104203. }
  104204. }
  104205. });
  104206. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  104207. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  104208. var webVrController_1 = gamepad;
  104209. if (!_this.webVROptions.trackPosition) {
  104210. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  104211. // Cache must be updated before rendering controllers to avoid them being one frame behind
  104212. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  104213. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  104214. _this._updateCache();
  104215. });
  104216. }
  104217. }
  104218. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  104219. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  104220. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  104221. if (_this.webVROptions.controllerMeshes) {
  104222. if (webVrController_1.defaultModel) {
  104223. webVrController_1.defaultModel.setEnabled(true);
  104224. }
  104225. else {
  104226. // Load the meshes
  104227. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  104228. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  104229. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  104230. if (_this.webVROptions.defaultLightingOnControllers) {
  104231. if (!_this._lightOnControllers) {
  104232. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  104233. }
  104234. var activateLightOnSubMeshes_1 = function (mesh, light) {
  104235. var children = mesh.getChildren();
  104236. if (children && children.length !== 0) {
  104237. children.forEach(function (mesh) {
  104238. light.includedOnlyMeshes.push(mesh);
  104239. activateLightOnSubMeshes_1(mesh, light);
  104240. });
  104241. }
  104242. };
  104243. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  104244. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  104245. }
  104246. });
  104247. }
  104248. }
  104249. webVrController_1.attachToPoseControlledCamera(_this);
  104250. // since this is async - sanity check. Is the controller already stored?
  104251. if (_this.controllers.indexOf(webVrController_1) === -1) {
  104252. //add to the controllers array
  104253. _this.controllers.push(webVrController_1);
  104254. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  104255. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  104256. // So we're overriding setting left & right manually to be sure
  104257. var firstViveWandDetected = false;
  104258. for (var i = 0; i < _this.controllers.length; i++) {
  104259. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  104260. if (!firstViveWandDetected) {
  104261. firstViveWandDetected = true;
  104262. _this.controllers[i].hand = "left";
  104263. }
  104264. else {
  104265. _this.controllers[i].hand = "right";
  104266. }
  104267. }
  104268. }
  104269. //did we find enough controllers? Great! let the developer know.
  104270. if (_this.controllers.length >= 2) {
  104271. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  104272. }
  104273. }
  104274. }
  104275. });
  104276. };
  104277. return WebVRFreeCamera;
  104278. }(BABYLON.FreeCamera));
  104279. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  104280. })(BABYLON || (BABYLON = {}));
  104281. //# sourceMappingURL=babylon.webVRCamera.js.map
  104282. var BABYLON;
  104283. (function (BABYLON) {
  104284. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  104285. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  104286. });
  104287. // We're mainly based on the logic defined into the FreeCamera code
  104288. /**
  104289. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  104290. * being tilted forward or back and left or right.
  104291. */
  104292. var DeviceOrientationCamera = /** @class */ (function (_super) {
  104293. __extends(DeviceOrientationCamera, _super);
  104294. /**
  104295. * Creates a new device orientation camera
  104296. * @param name The name of the camera
  104297. * @param position The start position camera
  104298. * @param scene The scene the camera belongs to
  104299. */
  104300. function DeviceOrientationCamera(name, position, scene) {
  104301. var _this = _super.call(this, name, position, scene) || this;
  104302. _this._quaternionCache = new BABYLON.Quaternion();
  104303. _this.inputs.addDeviceOrientation();
  104304. return _this;
  104305. }
  104306. /**
  104307. * Gets the current instance class name ("DeviceOrientationCamera").
  104308. * This helps avoiding instanceof at run time.
  104309. * @returns the class name
  104310. */
  104311. DeviceOrientationCamera.prototype.getClassName = function () {
  104312. return "DeviceOrientationCamera";
  104313. };
  104314. /**
  104315. * @hidden
  104316. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  104317. */
  104318. DeviceOrientationCamera.prototype._checkInputs = function () {
  104319. _super.prototype._checkInputs.call(this);
  104320. this._quaternionCache.copyFrom(this.rotationQuaternion);
  104321. if (this._initialQuaternion) {
  104322. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104323. }
  104324. };
  104325. /**
  104326. * Reset the camera to its default orientation on the specified axis only.
  104327. * @param axis The axis to reset
  104328. */
  104329. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  104330. var _this = this;
  104331. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  104332. //can only work if this camera has a rotation quaternion already.
  104333. if (!this.rotationQuaternion) {
  104334. return;
  104335. }
  104336. if (!this._initialQuaternion) {
  104337. this._initialQuaternion = new BABYLON.Quaternion();
  104338. }
  104339. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  104340. ['x', 'y', 'z'].forEach(function (axisName) {
  104341. if (!axis[axisName]) {
  104342. _this._initialQuaternion[axisName] = 0;
  104343. }
  104344. else {
  104345. _this._initialQuaternion[axisName] *= -1;
  104346. }
  104347. });
  104348. this._initialQuaternion.normalize();
  104349. //force rotation update
  104350. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104351. };
  104352. return DeviceOrientationCamera;
  104353. }(BABYLON.FreeCamera));
  104354. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  104355. })(BABYLON || (BABYLON = {}));
  104356. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  104357. var BABYLON;
  104358. (function (BABYLON) {
  104359. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104360. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104361. });
  104362. /**
  104363. * Camera used to simulate VR rendering (based on FreeCamera)
  104364. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104365. */
  104366. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  104367. __extends(VRDeviceOrientationFreeCamera, _super);
  104368. /**
  104369. * Creates a new VRDeviceOrientationFreeCamera
  104370. * @param name defines camera name
  104371. * @param position defines the start position of the camera
  104372. * @param scene defines the scene the camera belongs to
  104373. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104374. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104375. */
  104376. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104377. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104378. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104379. var _this = _super.call(this, name, position, scene) || this;
  104380. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104381. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104382. return _this;
  104383. }
  104384. /**
  104385. * Gets camera class name
  104386. * @returns VRDeviceOrientationFreeCamera
  104387. */
  104388. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  104389. return "VRDeviceOrientationFreeCamera";
  104390. };
  104391. return VRDeviceOrientationFreeCamera;
  104392. }(BABYLON.DeviceOrientationCamera));
  104393. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  104394. })(BABYLON || (BABYLON = {}));
  104395. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  104396. var BABYLON;
  104397. (function (BABYLON) {
  104398. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104399. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  104400. });
  104401. /**
  104402. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  104403. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104404. */
  104405. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  104406. __extends(VRDeviceOrientationArcRotateCamera, _super);
  104407. /**
  104408. * Creates a new VRDeviceOrientationArcRotateCamera
  104409. * @param name defines camera name
  104410. * @param alpha defines the camera rotation along the logitudinal axis
  104411. * @param beta defines the camera rotation along the latitudinal axis
  104412. * @param radius defines the camera distance from its target
  104413. * @param target defines the camera target
  104414. * @param scene defines the scene the camera belongs to
  104415. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104416. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104417. */
  104418. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  104419. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104420. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104421. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104422. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104423. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104424. _this.inputs.addVRDeviceOrientation();
  104425. return _this;
  104426. }
  104427. /**
  104428. * Gets camera class name
  104429. * @returns VRDeviceOrientationArcRotateCamera
  104430. */
  104431. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  104432. return "VRDeviceOrientationArcRotateCamera";
  104433. };
  104434. return VRDeviceOrientationArcRotateCamera;
  104435. }(BABYLON.ArcRotateCamera));
  104436. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  104437. })(BABYLON || (BABYLON = {}));
  104438. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  104439. var BABYLON;
  104440. (function (BABYLON) {
  104441. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  104442. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  104443. });
  104444. /**
  104445. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  104446. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104447. */
  104448. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  104449. __extends(VRDeviceOrientationGamepadCamera, _super);
  104450. /**
  104451. * Creates a new VRDeviceOrientationGamepadCamera
  104452. * @param name defines camera name
  104453. * @param position defines the start position of the camera
  104454. * @param scene defines the scene the camera belongs to
  104455. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104456. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104457. */
  104458. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104459. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104460. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104461. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  104462. _this.inputs.addGamepad();
  104463. return _this;
  104464. }
  104465. /**
  104466. * Gets camera class name
  104467. * @returns VRDeviceOrientationGamepadCamera
  104468. */
  104469. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  104470. return "VRDeviceOrientationGamepadCamera";
  104471. };
  104472. return VRDeviceOrientationGamepadCamera;
  104473. }(BABYLON.VRDeviceOrientationFreeCamera));
  104474. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  104475. })(BABYLON || (BABYLON = {}));
  104476. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  104477. var BABYLON;
  104478. (function (BABYLON) {
  104479. var VRExperienceHelperGazer = /** @class */ (function () {
  104480. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  104481. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  104482. this.scene = scene;
  104483. /** @hidden */
  104484. this._pointerDownOnMeshAsked = false;
  104485. /** @hidden */
  104486. this._isActionableMesh = false;
  104487. /** @hidden */
  104488. this._teleportationRequestInitiated = false;
  104489. /** @hidden */
  104490. this._teleportationBackRequestInitiated = false;
  104491. /** @hidden */
  104492. this._rotationRightAsked = false;
  104493. /** @hidden */
  104494. this._rotationLeftAsked = false;
  104495. /** @hidden */
  104496. this._dpadPressed = true;
  104497. /** @hidden */
  104498. this._activePointer = false;
  104499. this._id = VRExperienceHelperGazer._idCounter++;
  104500. // Gaze tracker
  104501. if (!gazeTrackerToClone) {
  104502. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  104503. this._gazeTracker.bakeCurrentTransformIntoVertices();
  104504. this._gazeTracker.isPickable = false;
  104505. this._gazeTracker.isVisible = false;
  104506. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  104507. targetMat.specularColor = BABYLON.Color3.Black();
  104508. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104509. targetMat.backFaceCulling = false;
  104510. this._gazeTracker.material = targetMat;
  104511. }
  104512. else {
  104513. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  104514. }
  104515. }
  104516. /** @hidden */
  104517. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  104518. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  104519. };
  104520. /** @hidden */
  104521. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  104522. this._pointerDownOnMeshAsked = true;
  104523. if (this._currentHit) {
  104524. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  104525. }
  104526. };
  104527. /** @hidden */
  104528. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  104529. if (this._currentHit) {
  104530. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  104531. }
  104532. this._pointerDownOnMeshAsked = false;
  104533. };
  104534. /** @hidden */
  104535. VRExperienceHelperGazer.prototype._activatePointer = function () {
  104536. this._activePointer = true;
  104537. };
  104538. /** @hidden */
  104539. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  104540. this._activePointer = false;
  104541. };
  104542. /** @hidden */
  104543. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  104544. if (distance === void 0) { distance = 100; }
  104545. };
  104546. VRExperienceHelperGazer.prototype.dispose = function () {
  104547. this._interactionsEnabled = false;
  104548. this._teleportationEnabled = false;
  104549. if (this._gazeTracker) {
  104550. this._gazeTracker.dispose();
  104551. }
  104552. };
  104553. VRExperienceHelperGazer._idCounter = 0;
  104554. return VRExperienceHelperGazer;
  104555. }());
  104556. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  104557. __extends(VRExperienceHelperControllerGazer, _super);
  104558. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  104559. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  104560. _this.webVRController = webVRController;
  104561. // Laser pointer
  104562. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  104563. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  104564. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104565. laserPointerMaterial.alpha = 0.6;
  104566. _this._laserPointer.material = laserPointerMaterial;
  104567. _this._laserPointer.rotation.x = Math.PI / 2;
  104568. _this._laserPointer.position.z = -0.5;
  104569. _this._laserPointer.isVisible = false;
  104570. _this._laserPointer.isPickable = false;
  104571. if (!webVRController.mesh) {
  104572. // Create an empty mesh that is used prior to loading the high quality model
  104573. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  104574. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  104575. preloadPointerPose.rotation.x = -0.7;
  104576. preloadMesh.addChild(preloadPointerPose);
  104577. webVRController.attachToMesh(preloadMesh);
  104578. }
  104579. _this._setLaserPointerParent(webVRController.mesh);
  104580. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  104581. _this._setLaserPointerParent(mesh);
  104582. });
  104583. return _this;
  104584. }
  104585. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  104586. return this.webVRController.getForwardRay(length);
  104587. };
  104588. /** @hidden */
  104589. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  104590. _super.prototype._activatePointer.call(this);
  104591. this._laserPointer.isVisible = true;
  104592. };
  104593. /** @hidden */
  104594. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  104595. _super.prototype._deactivatePointer.call(this);
  104596. this._laserPointer.isVisible = false;
  104597. };
  104598. /** @hidden */
  104599. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  104600. this._laserPointer.material.emissiveColor = color;
  104601. };
  104602. /** @hidden */
  104603. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  104604. var makeNotPick = function (root) {
  104605. root.isPickable = false;
  104606. root.getChildMeshes().forEach(function (c) {
  104607. makeNotPick(c);
  104608. });
  104609. };
  104610. makeNotPick(mesh);
  104611. var childMeshes = mesh.getChildMeshes();
  104612. this.webVRController._pointingPoseNode = null;
  104613. for (var i = 0; i < childMeshes.length; i++) {
  104614. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  104615. mesh = childMeshes[i];
  104616. this.webVRController._pointingPoseNode = mesh;
  104617. break;
  104618. }
  104619. }
  104620. this._laserPointer.parent = mesh;
  104621. };
  104622. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  104623. if (distance === void 0) { distance = 100; }
  104624. this._laserPointer.scaling.y = distance;
  104625. this._laserPointer.position.z = -distance / 2;
  104626. };
  104627. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  104628. _super.prototype.dispose.call(this);
  104629. this._laserPointer.dispose();
  104630. if (this._meshAttachedObserver) {
  104631. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  104632. }
  104633. };
  104634. return VRExperienceHelperControllerGazer;
  104635. }(VRExperienceHelperGazer));
  104636. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  104637. __extends(VRExperienceHelperCameraGazer, _super);
  104638. function VRExperienceHelperCameraGazer(getCamera, scene) {
  104639. var _this = _super.call(this, scene) || this;
  104640. _this.getCamera = getCamera;
  104641. return _this;
  104642. }
  104643. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  104644. var camera = this.getCamera();
  104645. if (camera) {
  104646. return camera.getForwardRay(length);
  104647. }
  104648. else {
  104649. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  104650. }
  104651. };
  104652. return VRExperienceHelperCameraGazer;
  104653. }(VRExperienceHelperGazer));
  104654. /**
  104655. * Helps to quickly add VR support to an existing scene.
  104656. * See http://doc.babylonjs.com/how_to/webvr_helper
  104657. */
  104658. var VRExperienceHelper = /** @class */ (function () {
  104659. /**
  104660. * Instantiates a VRExperienceHelper.
  104661. * Helps to quickly add VR support to an existing scene.
  104662. * @param scene The scene the VRExperienceHelper belongs to.
  104663. * @param webVROptions Options to modify the vr experience helper's behavior.
  104664. */
  104665. function VRExperienceHelper(scene,
  104666. /** Options to modify the vr experience helper's behavior. */
  104667. webVROptions) {
  104668. if (webVROptions === void 0) { webVROptions = {}; }
  104669. var _this = this;
  104670. this.webVROptions = webVROptions;
  104671. // Can the system support WebVR, even if a headset isn't plugged in?
  104672. this._webVRsupported = false;
  104673. // If WebVR is supported, is a headset plugged in and are we ready to present?
  104674. this._webVRready = false;
  104675. // Are we waiting for the requestPresent callback to complete?
  104676. this._webVRrequesting = false;
  104677. // Are we presenting to the headset right now? (this is the vrDevice state)
  104678. this._webVRpresenting = false;
  104679. // Are we presenting in the fullscreen fallback?
  104680. this._fullscreenVRpresenting = false;
  104681. /**
  104682. * Observable raised when entering VR.
  104683. */
  104684. this.onEnteringVRObservable = new BABYLON.Observable();
  104685. /**
  104686. * Observable raised when exiting VR.
  104687. */
  104688. this.onExitingVRObservable = new BABYLON.Observable();
  104689. /**
  104690. * Observable raised when controller mesh is loaded.
  104691. */
  104692. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  104693. this._useCustomVRButton = false;
  104694. this._teleportationRequested = false;
  104695. this._teleportActive = false;
  104696. this._floorMeshesCollection = [];
  104697. this._rotationAllowed = true;
  104698. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  104699. this._isDefaultTeleportationTarget = true;
  104700. this._teleportationFillColor = "#444444";
  104701. this._teleportationBorderColor = "#FFFFFF";
  104702. this._rotationAngle = 0;
  104703. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  104704. this._padSensibilityUp = 0.65;
  104705. this._padSensibilityDown = 0.35;
  104706. this._leftController = null;
  104707. this._rightController = null;
  104708. /**
  104709. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  104710. */
  104711. this.onNewMeshSelected = new BABYLON.Observable();
  104712. /**
  104713. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  104714. */
  104715. this.onNewMeshPicked = new BABYLON.Observable();
  104716. /**
  104717. * Observable raised before camera teleportation
  104718. */
  104719. this.onBeforeCameraTeleport = new BABYLON.Observable();
  104720. /**
  104721. * Observable raised after camera teleportation
  104722. */
  104723. this.onAfterCameraTeleport = new BABYLON.Observable();
  104724. /**
  104725. * Observable raised when current selected mesh gets unselected
  104726. */
  104727. this.onSelectedMeshUnselected = new BABYLON.Observable();
  104728. /**
  104729. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  104730. */
  104731. this.teleportationEnabled = true;
  104732. this._teleportationInitialized = false;
  104733. this._interactionsEnabled = false;
  104734. this._interactionsRequested = false;
  104735. this._displayGaze = true;
  104736. this._displayLaserPointer = true;
  104737. /**
  104738. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  104739. */
  104740. this.updateGazeTrackerScale = true;
  104741. this._onResize = function () {
  104742. _this.moveButtonToBottomRight();
  104743. if (_this._fullscreenVRpresenting && _this._webVRready) {
  104744. _this.exitVR();
  104745. }
  104746. };
  104747. this._onFullscreenChange = function () {
  104748. if (document.fullscreen !== undefined) {
  104749. _this._fullscreenVRpresenting = document.fullscreen;
  104750. }
  104751. else if (document.mozFullScreen !== undefined) {
  104752. _this._fullscreenVRpresenting = document.mozFullScreen;
  104753. }
  104754. else if (document.webkitIsFullScreen !== undefined) {
  104755. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  104756. }
  104757. else if (document.msIsFullScreen !== undefined) {
  104758. _this._fullscreenVRpresenting = document.msIsFullScreen;
  104759. }
  104760. else if (document.msFullscreenElement !== undefined) {
  104761. _this._fullscreenVRpresenting = document.msFullscreenElement;
  104762. }
  104763. if (!_this._fullscreenVRpresenting && _this._canvas) {
  104764. _this.exitVR();
  104765. if (!_this._useCustomVRButton) {
  104766. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  104767. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  104768. }
  104769. }
  104770. };
  104771. this.beforeRender = function () {
  104772. if (_this._leftController && _this._leftController._activePointer) {
  104773. _this._castRayAndSelectObject(_this._leftController);
  104774. }
  104775. if (_this._rightController && _this._rightController._activePointer) {
  104776. _this._castRayAndSelectObject(_this._rightController);
  104777. }
  104778. if (_this._noControllerIsActive) {
  104779. _this._castRayAndSelectObject(_this._cameraGazer);
  104780. }
  104781. else {
  104782. _this._cameraGazer._gazeTracker.isVisible = false;
  104783. }
  104784. };
  104785. this._onNewGamepadConnected = function (gamepad) {
  104786. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  104787. if (gamepad.leftStick) {
  104788. gamepad.onleftstickchanged(function (stickValues) {
  104789. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  104790. // Listening to classic/xbox gamepad only if no VR controller is active
  104791. if ((!_this._leftController && !_this._rightController) ||
  104792. ((_this._leftController && !_this._leftController._activePointer) &&
  104793. (_this._rightController && !_this._rightController._activePointer))) {
  104794. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  104795. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  104796. }
  104797. }
  104798. });
  104799. }
  104800. if (gamepad.rightStick) {
  104801. gamepad.onrightstickchanged(function (stickValues) {
  104802. if (_this._teleportationInitialized) {
  104803. _this._checkRotate(stickValues, _this._cameraGazer);
  104804. }
  104805. });
  104806. }
  104807. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  104808. gamepad.onbuttondown(function (buttonPressed) {
  104809. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104810. _this._cameraGazer._selectionPointerDown();
  104811. }
  104812. });
  104813. gamepad.onbuttonup(function (buttonPressed) {
  104814. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104815. _this._cameraGazer._selectionPointerUp();
  104816. }
  104817. });
  104818. }
  104819. }
  104820. else {
  104821. var webVRController = gamepad;
  104822. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  104823. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  104824. _this._rightController = controller;
  104825. }
  104826. else {
  104827. _this._leftController = controller;
  104828. }
  104829. _this._tryEnableInteractionOnController(controller);
  104830. }
  104831. };
  104832. // 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
  104833. this._tryEnableInteractionOnController = function (controller) {
  104834. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  104835. _this._enableInteractionOnController(controller);
  104836. }
  104837. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  104838. _this._enableTeleportationOnController(controller);
  104839. }
  104840. };
  104841. this._onNewGamepadDisconnected = function (gamepad) {
  104842. if (gamepad instanceof BABYLON.WebVRController) {
  104843. if (gamepad.hand === "left" && _this._leftController != null) {
  104844. _this._leftController.dispose();
  104845. _this._leftController = null;
  104846. }
  104847. if (gamepad.hand === "right" && _this._rightController != null) {
  104848. _this._rightController.dispose();
  104849. _this._rightController = null;
  104850. }
  104851. }
  104852. };
  104853. this._workingVector = BABYLON.Vector3.Zero();
  104854. this._workingQuaternion = BABYLON.Quaternion.Identity();
  104855. this._workingMatrix = BABYLON.Matrix.Identity();
  104856. this._scene = scene;
  104857. this._canvas = scene.getEngine().getRenderingCanvas();
  104858. // Parse options
  104859. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  104860. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  104861. }
  104862. if (webVROptions.createDeviceOrientationCamera === undefined) {
  104863. webVROptions.createDeviceOrientationCamera = true;
  104864. }
  104865. if (webVROptions.laserToggle === undefined) {
  104866. webVROptions.laserToggle = true;
  104867. }
  104868. if (webVROptions.defaultHeight === undefined) {
  104869. webVROptions.defaultHeight = 1.7;
  104870. }
  104871. if (webVROptions.useCustomVRButton) {
  104872. this._useCustomVRButton = true;
  104873. if (webVROptions.customVRButton) {
  104874. this._btnVR = webVROptions.customVRButton;
  104875. }
  104876. }
  104877. if (webVROptions.rayLength) {
  104878. this._rayLength = webVROptions.rayLength;
  104879. }
  104880. this._defaultHeight = webVROptions.defaultHeight;
  104881. if (webVROptions.positionScale) {
  104882. this._rayLength *= webVROptions.positionScale;
  104883. this._defaultHeight *= webVROptions.positionScale;
  104884. }
  104885. this._hasEnteredVR = false;
  104886. // Set position
  104887. if (this._scene.activeCamera) {
  104888. this._position = this._scene.activeCamera.position.clone();
  104889. }
  104890. else {
  104891. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  104892. }
  104893. // Set non-vr camera
  104894. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  104895. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  104896. // Copy data from existing camera
  104897. if (this._scene.activeCamera) {
  104898. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  104899. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  104900. // Set rotation from previous camera
  104901. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  104902. var targetCamera = this._scene.activeCamera;
  104903. if (targetCamera.rotationQuaternion) {
  104904. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  104905. }
  104906. else {
  104907. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  104908. }
  104909. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  104910. }
  104911. }
  104912. this._scene.activeCamera = this._deviceOrientationCamera;
  104913. if (this._canvas) {
  104914. this._scene.activeCamera.attachControl(this._canvas);
  104915. }
  104916. }
  104917. else {
  104918. this._existingCamera = this._scene.activeCamera;
  104919. }
  104920. // Create VR cameras
  104921. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104922. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  104923. }
  104924. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  104925. this._webVRCamera.useStandingMatrix();
  104926. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  104927. // Create default button
  104928. if (!this._useCustomVRButton) {
  104929. this._btnVR = document.createElement("BUTTON");
  104930. this._btnVR.className = "babylonVRicon";
  104931. this._btnVR.id = "babylonVRiconbtn";
  104932. this._btnVR.title = "Click to switch to VR";
  104933. 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) }";
  104934. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  104935. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  104936. // css += ".babylonVRicon.vrdisplaysupported { }";
  104937. // css += ".babylonVRicon.vrdisplayready { }";
  104938. // css += ".babylonVRicon.vrdisplayrequesting { }";
  104939. var style = document.createElement('style');
  104940. style.appendChild(document.createTextNode(css));
  104941. document.getElementsByTagName('head')[0].appendChild(style);
  104942. this.moveButtonToBottomRight();
  104943. }
  104944. // VR button click event
  104945. if (this._btnVR) {
  104946. this._btnVR.addEventListener("click", function () {
  104947. if (!_this.isInVRMode) {
  104948. _this.enterVR();
  104949. }
  104950. else {
  104951. _this.exitVR();
  104952. }
  104953. });
  104954. }
  104955. // Window events
  104956. window.addEventListener("resize", this._onResize);
  104957. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  104958. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  104959. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  104960. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  104961. document.onmsfullscreenchange = this._onFullscreenChange;
  104962. // Display vr button when headset is connected
  104963. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104964. this.displayVRButton();
  104965. }
  104966. else {
  104967. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  104968. if (e.vrDisplay) {
  104969. _this.displayVRButton();
  104970. }
  104971. });
  104972. }
  104973. // Exiting VR mode using 'ESC' key on desktop
  104974. this._onKeyDown = function (event) {
  104975. if (event.keyCode === 27 && _this.isInVRMode) {
  104976. _this.exitVR();
  104977. }
  104978. };
  104979. document.addEventListener("keydown", this._onKeyDown);
  104980. // Exiting VR mode double tapping the touch screen
  104981. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  104982. if (_this.isInVRMode) {
  104983. _this.exitVR();
  104984. if (_this._fullscreenVRpresenting) {
  104985. _this._scene.getEngine().switchFullscreen(true);
  104986. }
  104987. }
  104988. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  104989. // Listen for WebVR display changes
  104990. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  104991. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  104992. this._onVRRequestPresentStart = function () {
  104993. _this._webVRrequesting = true;
  104994. _this.updateButtonVisibility();
  104995. };
  104996. this._onVRRequestPresentComplete = function (success) {
  104997. _this._webVRrequesting = false;
  104998. _this.updateButtonVisibility();
  104999. };
  105000. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  105001. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  105002. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  105003. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  105004. scene.onDisposeObservable.add(function () {
  105005. _this.dispose();
  105006. });
  105007. // Gamepad connection events
  105008. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  105009. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  105010. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  105011. this.updateButtonVisibility();
  105012. //create easing functions
  105013. this._circleEase = new BABYLON.CircleEase();
  105014. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105015. if (this.webVROptions.floorMeshes) {
  105016. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  105017. }
  105018. }
  105019. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  105020. /** Return this.onEnteringVRObservable
  105021. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  105022. */
  105023. get: function () {
  105024. return this.onEnteringVRObservable;
  105025. },
  105026. enumerable: true,
  105027. configurable: true
  105028. });
  105029. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  105030. /** Return this.onExitingVRObservable
  105031. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  105032. */
  105033. get: function () {
  105034. return this.onExitingVRObservable;
  105035. },
  105036. enumerable: true,
  105037. configurable: true
  105038. });
  105039. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  105040. /** Return this.onControllerMeshLoadedObservable
  105041. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  105042. */
  105043. get: function () {
  105044. return this.onControllerMeshLoadedObservable;
  105045. },
  105046. enumerable: true,
  105047. configurable: true
  105048. });
  105049. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  105050. /**
  105051. * The mesh used to display where the user is going to teleport.
  105052. */
  105053. get: function () {
  105054. return this._teleportationTarget;
  105055. },
  105056. /**
  105057. * Sets the mesh to be used to display where the user is going to teleport.
  105058. */
  105059. set: function (value) {
  105060. if (value) {
  105061. value.name = "teleportationTarget";
  105062. this._isDefaultTeleportationTarget = false;
  105063. this._teleportationTarget = value;
  105064. }
  105065. },
  105066. enumerable: true,
  105067. configurable: true
  105068. });
  105069. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  105070. /**
  105071. * 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
  105072. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  105073. * See http://doc.babylonjs.com/resources/baking_transformations
  105074. */
  105075. get: function () {
  105076. return this._cameraGazer._gazeTracker;
  105077. },
  105078. set: function (value) {
  105079. if (value) {
  105080. // Dispose of existing meshes
  105081. if (this._cameraGazer._gazeTracker) {
  105082. this._cameraGazer._gazeTracker.dispose();
  105083. }
  105084. if (this._leftController && this._leftController._gazeTracker) {
  105085. this._leftController._gazeTracker.dispose();
  105086. }
  105087. if (this._rightController && this._rightController._gazeTracker) {
  105088. this._rightController._gazeTracker.dispose();
  105089. }
  105090. // Set and create gaze trackers on head and controllers
  105091. this._cameraGazer._gazeTracker = value;
  105092. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  105093. this._cameraGazer._gazeTracker.isPickable = false;
  105094. this._cameraGazer._gazeTracker.isVisible = false;
  105095. this._cameraGazer._gazeTracker.name = "gazeTracker";
  105096. if (this._leftController) {
  105097. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  105098. }
  105099. if (this._rightController) {
  105100. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  105101. }
  105102. }
  105103. },
  105104. enumerable: true,
  105105. configurable: true
  105106. });
  105107. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  105108. /**
  105109. * The gaze tracking mesh corresponding to the left controller
  105110. */
  105111. get: function () {
  105112. if (this._leftController) {
  105113. return this._leftController._gazeTracker;
  105114. }
  105115. return null;
  105116. },
  105117. enumerable: true,
  105118. configurable: true
  105119. });
  105120. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  105121. /**
  105122. * The gaze tracking mesh corresponding to the right controller
  105123. */
  105124. get: function () {
  105125. if (this._rightController) {
  105126. return this._rightController._gazeTracker;
  105127. }
  105128. return null;
  105129. },
  105130. enumerable: true,
  105131. configurable: true
  105132. });
  105133. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  105134. /**
  105135. * If the ray of the gaze should be displayed.
  105136. */
  105137. get: function () {
  105138. return this._displayGaze;
  105139. },
  105140. /**
  105141. * Sets if the ray of the gaze should be displayed.
  105142. */
  105143. set: function (value) {
  105144. this._displayGaze = value;
  105145. if (!value) {
  105146. this._cameraGazer._gazeTracker.isVisible = false;
  105147. if (this._leftController) {
  105148. this._leftController._gazeTracker.isVisible = false;
  105149. }
  105150. if (this._rightController) {
  105151. this._rightController._gazeTracker.isVisible = false;
  105152. }
  105153. }
  105154. },
  105155. enumerable: true,
  105156. configurable: true
  105157. });
  105158. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  105159. /**
  105160. * If the ray of the LaserPointer should be displayed.
  105161. */
  105162. get: function () {
  105163. return this._displayLaserPointer;
  105164. },
  105165. /**
  105166. * Sets if the ray of the LaserPointer should be displayed.
  105167. */
  105168. set: function (value) {
  105169. this._displayLaserPointer = value;
  105170. if (!value) {
  105171. if (this._rightController) {
  105172. this._rightController._deactivatePointer();
  105173. this._rightController._gazeTracker.isVisible = false;
  105174. }
  105175. if (this._leftController) {
  105176. this._leftController._deactivatePointer();
  105177. this._leftController._gazeTracker.isVisible = false;
  105178. }
  105179. }
  105180. else {
  105181. if (this._rightController) {
  105182. this._rightController._activatePointer();
  105183. }
  105184. if (this._leftController) {
  105185. this._leftController._activatePointer();
  105186. }
  105187. }
  105188. },
  105189. enumerable: true,
  105190. configurable: true
  105191. });
  105192. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  105193. /**
  105194. * The deviceOrientationCamera used as the camera when not in VR.
  105195. */
  105196. get: function () {
  105197. return this._deviceOrientationCamera;
  105198. },
  105199. enumerable: true,
  105200. configurable: true
  105201. });
  105202. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  105203. /**
  105204. * Based on the current WebVR support, returns the current VR camera used.
  105205. */
  105206. get: function () {
  105207. if (this._webVRready) {
  105208. return this._webVRCamera;
  105209. }
  105210. else {
  105211. return this._scene.activeCamera;
  105212. }
  105213. },
  105214. enumerable: true,
  105215. configurable: true
  105216. });
  105217. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  105218. /**
  105219. * The webVRCamera which is used when in VR.
  105220. */
  105221. get: function () {
  105222. return this._webVRCamera;
  105223. },
  105224. enumerable: true,
  105225. configurable: true
  105226. });
  105227. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  105228. /**
  105229. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  105230. */
  105231. get: function () {
  105232. return this._vrDeviceOrientationCamera;
  105233. },
  105234. enumerable: true,
  105235. configurable: true
  105236. });
  105237. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  105238. get: function () {
  105239. var result = this._cameraGazer._teleportationRequestInitiated
  105240. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  105241. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  105242. return result;
  105243. },
  105244. enumerable: true,
  105245. configurable: true
  105246. });
  105247. // Raised when one of the controller has loaded successfully its associated default mesh
  105248. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  105249. if (this._leftController && this._leftController.webVRController == webVRController) {
  105250. if (webVRController.mesh) {
  105251. this._leftController._setLaserPointerParent(webVRController.mesh);
  105252. }
  105253. }
  105254. if (this._rightController && this._rightController.webVRController == webVRController) {
  105255. if (webVRController.mesh) {
  105256. this._rightController._setLaserPointerParent(webVRController.mesh);
  105257. }
  105258. }
  105259. try {
  105260. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  105261. }
  105262. catch (err) {
  105263. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  105264. }
  105265. };
  105266. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  105267. /**
  105268. * Gets a value indicating if we are currently in VR mode.
  105269. */
  105270. get: function () {
  105271. return this._webVRpresenting || this._fullscreenVRpresenting;
  105272. },
  105273. enumerable: true,
  105274. configurable: true
  105275. });
  105276. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  105277. var vrDisplay = this._scene.getEngine().getVRDevice();
  105278. if (vrDisplay) {
  105279. var wasPresenting = this._webVRpresenting;
  105280. this._webVRpresenting = vrDisplay.isPresenting;
  105281. if (wasPresenting && !this._webVRpresenting) {
  105282. this.exitVR();
  105283. }
  105284. }
  105285. else {
  105286. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  105287. }
  105288. this.updateButtonVisibility();
  105289. };
  105290. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  105291. this._webVRsupported = eventArgs.vrSupported;
  105292. this._webVRready = !!eventArgs.vrDisplay;
  105293. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  105294. this.updateButtonVisibility();
  105295. };
  105296. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  105297. if (this._canvas && !this._useCustomVRButton) {
  105298. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  105299. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  105300. }
  105301. };
  105302. VRExperienceHelper.prototype.displayVRButton = function () {
  105303. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  105304. document.body.appendChild(this._btnVR);
  105305. this._btnVRDisplayed = true;
  105306. }
  105307. };
  105308. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  105309. if (!this._btnVR || this._useCustomVRButton) {
  105310. return;
  105311. }
  105312. this._btnVR.className = "babylonVRicon";
  105313. if (this.isInVRMode) {
  105314. this._btnVR.className += " vrdisplaypresenting";
  105315. }
  105316. else {
  105317. if (this._webVRready) {
  105318. this._btnVR.className += " vrdisplayready";
  105319. }
  105320. if (this._webVRsupported) {
  105321. this._btnVR.className += " vrdisplaysupported";
  105322. }
  105323. if (this._webVRrequesting) {
  105324. this._btnVR.className += " vrdisplayrequesting";
  105325. }
  105326. }
  105327. };
  105328. /**
  105329. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  105330. * Otherwise, will use the fullscreen API.
  105331. */
  105332. VRExperienceHelper.prototype.enterVR = function () {
  105333. if (this.onEnteringVRObservable) {
  105334. try {
  105335. this.onEnteringVRObservable.notifyObservers(this);
  105336. }
  105337. catch (err) {
  105338. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  105339. }
  105340. }
  105341. if (this._scene.activeCamera) {
  105342. this._position = this._scene.activeCamera.position.clone();
  105343. // make sure that we return to the last active camera
  105344. this._existingCamera = this._scene.activeCamera;
  105345. }
  105346. if (this._webVRrequesting) {
  105347. return;
  105348. }
  105349. // If WebVR is supported and a headset is connected
  105350. if (this._webVRready) {
  105351. if (!this._webVRpresenting) {
  105352. this._webVRCamera.position = this._position;
  105353. this._scene.activeCamera = this._webVRCamera;
  105354. }
  105355. }
  105356. else if (this._vrDeviceOrientationCamera) {
  105357. this._vrDeviceOrientationCamera.position = this._position;
  105358. if (this._scene.activeCamera) {
  105359. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  105360. }
  105361. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  105362. this._scene.getEngine().switchFullscreen(true);
  105363. this.updateButtonVisibility();
  105364. }
  105365. if (this._scene.activeCamera && this._canvas) {
  105366. this._scene.activeCamera.attachControl(this._canvas);
  105367. }
  105368. if (this._interactionsEnabled) {
  105369. this._scene.registerBeforeRender(this.beforeRender);
  105370. }
  105371. this._hasEnteredVR = true;
  105372. };
  105373. /**
  105374. * Attempt to exit VR, or fullscreen.
  105375. */
  105376. VRExperienceHelper.prototype.exitVR = function () {
  105377. if (this._hasEnteredVR) {
  105378. if (this.onExitingVRObservable) {
  105379. try {
  105380. this.onExitingVRObservable.notifyObservers(this);
  105381. }
  105382. catch (err) {
  105383. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  105384. }
  105385. }
  105386. if (this._webVRpresenting) {
  105387. this._scene.getEngine().disableVR();
  105388. }
  105389. if (this._scene.activeCamera) {
  105390. this._position = this._scene.activeCamera.position.clone();
  105391. }
  105392. if (this._deviceOrientationCamera) {
  105393. this._deviceOrientationCamera.position = this._position;
  105394. this._scene.activeCamera = this._deviceOrientationCamera;
  105395. if (this._canvas) {
  105396. this._scene.activeCamera.attachControl(this._canvas);
  105397. }
  105398. }
  105399. else if (this._existingCamera) {
  105400. this._existingCamera.position = this._position;
  105401. this._scene.activeCamera = this._existingCamera;
  105402. }
  105403. this.updateButtonVisibility();
  105404. if (this._interactionsEnabled) {
  105405. this._scene.unregisterBeforeRender(this.beforeRender);
  105406. this._cameraGazer._gazeTracker.isVisible = false;
  105407. if (this._leftController) {
  105408. this._leftController._gazeTracker.isVisible = false;
  105409. }
  105410. if (this._rightController) {
  105411. this._rightController._gazeTracker.isVisible = false;
  105412. }
  105413. }
  105414. // resize to update width and height when exiting vr exits fullscreen
  105415. this._scene.getEngine().resize();
  105416. this._hasEnteredVR = false;
  105417. }
  105418. };
  105419. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  105420. /**
  105421. * The position of the vr experience helper.
  105422. */
  105423. get: function () {
  105424. return this._position;
  105425. },
  105426. /**
  105427. * Sets the position of the vr experience helper.
  105428. */
  105429. set: function (value) {
  105430. this._position = value;
  105431. if (this._scene.activeCamera) {
  105432. this._scene.activeCamera.position = value;
  105433. }
  105434. },
  105435. enumerable: true,
  105436. configurable: true
  105437. });
  105438. /**
  105439. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  105440. */
  105441. VRExperienceHelper.prototype.enableInteractions = function () {
  105442. var _this = this;
  105443. if (!this._interactionsEnabled) {
  105444. this._interactionsRequested = true;
  105445. if (this._leftController) {
  105446. this._enableInteractionOnController(this._leftController);
  105447. }
  105448. if (this._rightController) {
  105449. this._enableInteractionOnController(this._rightController);
  105450. }
  105451. this.raySelectionPredicate = function (mesh) {
  105452. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  105453. };
  105454. this.meshSelectionPredicate = function (mesh) {
  105455. return true;
  105456. };
  105457. this._raySelectionPredicate = function (mesh) {
  105458. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  105459. && mesh.name.indexOf("teleportationTarget") === -1
  105460. && mesh.name.indexOf("torusTeleportation") === -1)) {
  105461. return _this.raySelectionPredicate(mesh);
  105462. }
  105463. return false;
  105464. };
  105465. this._interactionsEnabled = true;
  105466. }
  105467. };
  105468. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  105469. get: function () {
  105470. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  105471. },
  105472. enumerable: true,
  105473. configurable: true
  105474. });
  105475. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  105476. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  105477. if (this._floorMeshesCollection[i].id === mesh.id) {
  105478. return true;
  105479. }
  105480. }
  105481. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  105482. return true;
  105483. }
  105484. return false;
  105485. };
  105486. /**
  105487. * Adds a floor mesh to be used for teleportation.
  105488. * @param floorMesh the mesh to be used for teleportation.
  105489. */
  105490. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  105491. if (!this._floorMeshesCollection) {
  105492. return;
  105493. }
  105494. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  105495. return;
  105496. }
  105497. this._floorMeshesCollection.push(floorMesh);
  105498. };
  105499. /**
  105500. * Removes a floor mesh from being used for teleportation.
  105501. * @param floorMesh the mesh to be removed.
  105502. */
  105503. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  105504. if (!this._floorMeshesCollection) {
  105505. return;
  105506. }
  105507. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  105508. if (meshIndex !== -1) {
  105509. this._floorMeshesCollection.splice(meshIndex, 1);
  105510. }
  105511. };
  105512. /**
  105513. * Enables interactions and teleportation using the VR controllers and gaze.
  105514. * @param vrTeleportationOptions options to modify teleportation behavior.
  105515. */
  105516. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  105517. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  105518. if (!this._teleportationInitialized) {
  105519. this._teleportationRequested = true;
  105520. this.enableInteractions();
  105521. if (vrTeleportationOptions.floorMeshName) {
  105522. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  105523. }
  105524. if (vrTeleportationOptions.floorMeshes) {
  105525. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  105526. }
  105527. if (this._leftController != null) {
  105528. this._enableTeleportationOnController(this._leftController);
  105529. }
  105530. if (this._rightController != null) {
  105531. this._enableTeleportationOnController(this._rightController);
  105532. }
  105533. // Creates an image processing post process for the vignette not relying
  105534. // on the main scene configuration for image processing to reduce setup and spaces
  105535. // (gamma/linear) conflicts.
  105536. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  105537. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  105538. imageProcessingConfiguration.vignetteEnabled = true;
  105539. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  105540. this._webVRCamera.detachPostProcess(this._postProcessMove);
  105541. this._teleportationInitialized = true;
  105542. if (this._isDefaultTeleportationTarget) {
  105543. this._createTeleportationCircles();
  105544. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  105545. }
  105546. }
  105547. };
  105548. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  105549. var _this = this;
  105550. var controllerMesh = controller.webVRController.mesh;
  105551. if (controllerMesh) {
  105552. controller._interactionsEnabled = true;
  105553. controller._activatePointer();
  105554. if (this.webVROptions.laserToggle) {
  105555. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  105556. // Enabling / disabling laserPointer
  105557. if (_this._displayLaserPointer && stateObject.value === 1) {
  105558. if (controller._activePointer) {
  105559. controller._deactivatePointer();
  105560. }
  105561. else {
  105562. controller._activatePointer();
  105563. }
  105564. if (_this.displayGaze) {
  105565. controller._gazeTracker.isVisible = controller._activePointer;
  105566. }
  105567. }
  105568. });
  105569. }
  105570. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  105571. var gazer = controller;
  105572. if (_this._noControllerIsActive) {
  105573. gazer = _this._cameraGazer;
  105574. }
  105575. if (!gazer._pointerDownOnMeshAsked) {
  105576. if (stateObject.value > _this._padSensibilityUp) {
  105577. gazer._selectionPointerDown();
  105578. }
  105579. }
  105580. else if (stateObject.value < _this._padSensibilityDown) {
  105581. gazer._selectionPointerUp();
  105582. }
  105583. });
  105584. }
  105585. };
  105586. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  105587. // Dont teleport if another gaze already requested teleportation
  105588. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  105589. return;
  105590. }
  105591. if (!gazer._teleportationRequestInitiated) {
  105592. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  105593. gazer._activatePointer();
  105594. gazer._teleportationRequestInitiated = true;
  105595. }
  105596. }
  105597. else {
  105598. // Listening to the proper controller values changes to confirm teleportation
  105599. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  105600. if (this._teleportActive) {
  105601. this.teleportCamera(this._haloCenter);
  105602. }
  105603. gazer._teleportationRequestInitiated = false;
  105604. }
  105605. }
  105606. };
  105607. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  105608. // Only rotate when user is not currently selecting a teleportation location
  105609. if (gazer._teleportationRequestInitiated) {
  105610. return;
  105611. }
  105612. if (!gazer._rotationLeftAsked) {
  105613. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  105614. gazer._rotationLeftAsked = true;
  105615. if (this._rotationAllowed) {
  105616. this._rotateCamera(false);
  105617. }
  105618. }
  105619. }
  105620. else {
  105621. if (stateObject.x > -this._padSensibilityDown) {
  105622. gazer._rotationLeftAsked = false;
  105623. }
  105624. }
  105625. if (!gazer._rotationRightAsked) {
  105626. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  105627. gazer._rotationRightAsked = true;
  105628. if (this._rotationAllowed) {
  105629. this._rotateCamera(true);
  105630. }
  105631. }
  105632. }
  105633. else {
  105634. if (stateObject.x < this._padSensibilityDown) {
  105635. gazer._rotationRightAsked = false;
  105636. }
  105637. }
  105638. };
  105639. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  105640. // Only teleport backwards when user is not currently selecting a teleportation location
  105641. if (gazer._teleportationRequestInitiated) {
  105642. return;
  105643. }
  105644. // Teleport backwards
  105645. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  105646. if (!gazer._teleportationBackRequestInitiated) {
  105647. if (!this.currentVRCamera) {
  105648. return;
  105649. }
  105650. // Get rotation and position of the current camera
  105651. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  105652. var position = this.currentVRCamera.position;
  105653. // If the camera has device position, use that instead
  105654. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  105655. rotation = this.currentVRCamera.deviceRotationQuaternion;
  105656. position = this.currentVRCamera.devicePosition;
  105657. }
  105658. // Get matrix with only the y rotation of the device rotation
  105659. rotation.toEulerAnglesToRef(this._workingVector);
  105660. this._workingVector.z = 0;
  105661. this._workingVector.x = 0;
  105662. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  105663. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  105664. // Rotate backwards ray by device rotation to cast at the ground behind the user
  105665. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  105666. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  105667. var ray = new BABYLON.Ray(position, this._workingVector);
  105668. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105669. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  105670. this.teleportCamera(hit.pickedPoint);
  105671. }
  105672. gazer._teleportationBackRequestInitiated = true;
  105673. }
  105674. }
  105675. else {
  105676. gazer._teleportationBackRequestInitiated = false;
  105677. }
  105678. };
  105679. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  105680. var _this = this;
  105681. var controllerMesh = controller.webVRController.mesh;
  105682. if (controllerMesh) {
  105683. if (!controller._interactionsEnabled) {
  105684. this._enableInteractionOnController(controller);
  105685. }
  105686. controller._interactionsEnabled = true;
  105687. controller._teleportationEnabled = true;
  105688. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105689. controller._dpadPressed = false;
  105690. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  105691. controller._dpadPressed = stateObject.pressed;
  105692. if (!controller._dpadPressed) {
  105693. controller._rotationLeftAsked = false;
  105694. controller._rotationRightAsked = false;
  105695. controller._teleportationBackRequestInitiated = false;
  105696. }
  105697. });
  105698. }
  105699. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  105700. if (_this.teleportationEnabled) {
  105701. _this._checkTeleportBackwards(stateObject, controller);
  105702. _this._checkTeleportWithRay(stateObject, controller);
  105703. }
  105704. _this._checkRotate(stateObject, controller);
  105705. });
  105706. }
  105707. };
  105708. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  105709. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  105710. this._teleportationTarget.isPickable = false;
  105711. var length = 512;
  105712. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  105713. dynamicTexture.hasAlpha = true;
  105714. var context = dynamicTexture.getContext();
  105715. var centerX = length / 2;
  105716. var centerY = length / 2;
  105717. var radius = 200;
  105718. context.beginPath();
  105719. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  105720. context.fillStyle = this._teleportationFillColor;
  105721. context.fill();
  105722. context.lineWidth = 10;
  105723. context.strokeStyle = this._teleportationBorderColor;
  105724. context.stroke();
  105725. context.closePath();
  105726. dynamicTexture.update();
  105727. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  105728. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  105729. this._teleportationTarget.material = teleportationCircleMaterial;
  105730. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  105731. torus.isPickable = false;
  105732. torus.parent = this._teleportationTarget;
  105733. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105734. var keys = [];
  105735. keys.push({
  105736. frame: 0,
  105737. value: 0
  105738. });
  105739. keys.push({
  105740. frame: 30,
  105741. value: 0.4
  105742. });
  105743. keys.push({
  105744. frame: 60,
  105745. value: 0
  105746. });
  105747. animationInnerCircle.setKeys(keys);
  105748. var easingFunction = new BABYLON.SineEase();
  105749. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105750. animationInnerCircle.setEasingFunction(easingFunction);
  105751. torus.animations = [];
  105752. torus.animations.push(animationInnerCircle);
  105753. this._scene.beginAnimation(torus, 0, 60, true);
  105754. this._hideTeleportationTarget();
  105755. };
  105756. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  105757. this._teleportActive = true;
  105758. if (this._teleportationInitialized) {
  105759. this._teleportationTarget.isVisible = true;
  105760. if (this._isDefaultTeleportationTarget) {
  105761. this._teleportationTarget.getChildren()[0].isVisible = true;
  105762. }
  105763. }
  105764. };
  105765. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  105766. this._teleportActive = false;
  105767. if (this._teleportationInitialized) {
  105768. this._teleportationTarget.isVisible = false;
  105769. if (this._isDefaultTeleportationTarget) {
  105770. this._teleportationTarget.getChildren()[0].isVisible = false;
  105771. }
  105772. }
  105773. };
  105774. VRExperienceHelper.prototype._rotateCamera = function (right) {
  105775. var _this = this;
  105776. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105777. return;
  105778. }
  105779. if (right) {
  105780. this._rotationAngle++;
  105781. }
  105782. else {
  105783. this._rotationAngle--;
  105784. }
  105785. this.currentVRCamera.animations = [];
  105786. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  105787. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105788. var animationRotationKeys = [];
  105789. animationRotationKeys.push({
  105790. frame: 0,
  105791. value: this.currentVRCamera.rotationQuaternion
  105792. });
  105793. animationRotationKeys.push({
  105794. frame: 6,
  105795. value: target
  105796. });
  105797. animationRotation.setKeys(animationRotationKeys);
  105798. animationRotation.setEasingFunction(this._circleEase);
  105799. this.currentVRCamera.animations.push(animationRotation);
  105800. this._postProcessMove.animations = [];
  105801. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105802. var vignetteWeightKeys = [];
  105803. vignetteWeightKeys.push({
  105804. frame: 0,
  105805. value: 0
  105806. });
  105807. vignetteWeightKeys.push({
  105808. frame: 3,
  105809. value: 4
  105810. });
  105811. vignetteWeightKeys.push({
  105812. frame: 6,
  105813. value: 0
  105814. });
  105815. animationPP.setKeys(vignetteWeightKeys);
  105816. animationPP.setEasingFunction(this._circleEase);
  105817. this._postProcessMove.animations.push(animationPP);
  105818. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105819. var vignetteStretchKeys = [];
  105820. vignetteStretchKeys.push({
  105821. frame: 0,
  105822. value: 0
  105823. });
  105824. vignetteStretchKeys.push({
  105825. frame: 3,
  105826. value: 10
  105827. });
  105828. vignetteStretchKeys.push({
  105829. frame: 6,
  105830. value: 0
  105831. });
  105832. animationPP2.setKeys(vignetteStretchKeys);
  105833. animationPP2.setEasingFunction(this._circleEase);
  105834. this._postProcessMove.animations.push(animationPP2);
  105835. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105836. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105837. this._postProcessMove.samples = 4;
  105838. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105839. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  105840. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105841. });
  105842. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  105843. };
  105844. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  105845. if (hit.pickedPoint) {
  105846. if (gazer._teleportationRequestInitiated) {
  105847. this._displayTeleportationTarget();
  105848. this._haloCenter.copyFrom(hit.pickedPoint);
  105849. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  105850. }
  105851. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  105852. if (pickNormal) {
  105853. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105854. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105855. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  105856. }
  105857. this._teleportationTarget.position.y += 0.1;
  105858. }
  105859. };
  105860. /**
  105861. * Teleports the users feet to the desired location
  105862. * @param location The location where the user's feet should be placed
  105863. */
  105864. VRExperienceHelper.prototype.teleportCamera = function (location) {
  105865. var _this = this;
  105866. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105867. return;
  105868. }
  105869. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  105870. // offset of the headset from the anchor.
  105871. if (this.webVRCamera.leftCamera) {
  105872. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  105873. this._workingVector.subtractInPlace(this.webVRCamera.position);
  105874. location.subtractToRef(this._workingVector, this._workingVector);
  105875. }
  105876. else {
  105877. this._workingVector.copyFrom(location);
  105878. }
  105879. // Add height to account for user's height offset
  105880. if (this.isInVRMode) {
  105881. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  105882. }
  105883. else {
  105884. this._workingVector.y += this._defaultHeight;
  105885. }
  105886. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  105887. // Create animation from the camera's position to the new location
  105888. this.currentVRCamera.animations = [];
  105889. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105890. var animationCameraTeleportationKeys = [{
  105891. frame: 0,
  105892. value: this.currentVRCamera.position
  105893. },
  105894. {
  105895. frame: 11,
  105896. value: this._workingVector
  105897. }
  105898. ];
  105899. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  105900. animationCameraTeleportation.setEasingFunction(this._circleEase);
  105901. this.currentVRCamera.animations.push(animationCameraTeleportation);
  105902. this._postProcessMove.animations = [];
  105903. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105904. var vignetteWeightKeys = [];
  105905. vignetteWeightKeys.push({
  105906. frame: 0,
  105907. value: 0
  105908. });
  105909. vignetteWeightKeys.push({
  105910. frame: 5,
  105911. value: 8
  105912. });
  105913. vignetteWeightKeys.push({
  105914. frame: 11,
  105915. value: 0
  105916. });
  105917. animationPP.setKeys(vignetteWeightKeys);
  105918. this._postProcessMove.animations.push(animationPP);
  105919. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105920. var vignetteStretchKeys = [];
  105921. vignetteStretchKeys.push({
  105922. frame: 0,
  105923. value: 0
  105924. });
  105925. vignetteStretchKeys.push({
  105926. frame: 5,
  105927. value: 10
  105928. });
  105929. vignetteStretchKeys.push({
  105930. frame: 11,
  105931. value: 0
  105932. });
  105933. animationPP2.setKeys(vignetteStretchKeys);
  105934. this._postProcessMove.animations.push(animationPP2);
  105935. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105936. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105937. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105938. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  105939. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105940. });
  105941. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  105942. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  105943. });
  105944. this._hideTeleportationTarget();
  105945. };
  105946. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  105947. if (normal) {
  105948. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  105949. if (angle < Math.PI / 2) {
  105950. normal.scaleInPlace(-1);
  105951. }
  105952. }
  105953. return normal;
  105954. };
  105955. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  105956. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105957. return;
  105958. }
  105959. var ray = gazer._getForwardRay(this._rayLength);
  105960. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105961. if (hit) {
  105962. // Populate the contrllers mesh that can be used for drag/drop
  105963. if (gazer._laserPointer) {
  105964. hit.originMesh = gazer._laserPointer.parent;
  105965. }
  105966. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  105967. }
  105968. gazer._currentHit = hit;
  105969. // Moving the gazeTracker on the mesh face targetted
  105970. if (hit && hit.pickedPoint) {
  105971. if (this._displayGaze) {
  105972. var multiplier = 1;
  105973. gazer._gazeTracker.isVisible = true;
  105974. if (gazer._isActionableMesh) {
  105975. multiplier = 3;
  105976. }
  105977. if (this.updateGazeTrackerScale) {
  105978. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  105979. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  105980. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  105981. }
  105982. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  105983. // To avoid z-fighting
  105984. var deltaFighting = 0.002;
  105985. if (pickNormal) {
  105986. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105987. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105988. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  105989. }
  105990. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  105991. if (gazer._gazeTracker.position.x < 0) {
  105992. gazer._gazeTracker.position.x += deltaFighting;
  105993. }
  105994. else {
  105995. gazer._gazeTracker.position.x -= deltaFighting;
  105996. }
  105997. if (gazer._gazeTracker.position.y < 0) {
  105998. gazer._gazeTracker.position.y += deltaFighting;
  105999. }
  106000. else {
  106001. gazer._gazeTracker.position.y -= deltaFighting;
  106002. }
  106003. if (gazer._gazeTracker.position.z < 0) {
  106004. gazer._gazeTracker.position.z += deltaFighting;
  106005. }
  106006. else {
  106007. gazer._gazeTracker.position.z -= deltaFighting;
  106008. }
  106009. }
  106010. // Changing the size of the laser pointer based on the distance from the targetted point
  106011. gazer._updatePointerDistance(hit.distance);
  106012. }
  106013. else {
  106014. gazer._updatePointerDistance();
  106015. gazer._gazeTracker.isVisible = false;
  106016. }
  106017. if (hit && hit.pickedMesh) {
  106018. // The object selected is the floor, we're in a teleportation scenario
  106019. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  106020. // Moving the teleportation area to this targetted point
  106021. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  106022. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  106023. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106024. }
  106025. gazer._currentMeshSelected = null;
  106026. if (gazer._teleportationRequestInitiated) {
  106027. this._moveTeleportationSelectorTo(hit, gazer, ray);
  106028. }
  106029. return;
  106030. }
  106031. // If not, we're in a selection scenario
  106032. //this._teleportationAllowed = false;
  106033. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  106034. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  106035. this.onNewMeshPicked.notifyObservers(hit);
  106036. gazer._currentMeshSelected = hit.pickedMesh;
  106037. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  106038. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  106039. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  106040. gazer._isActionableMesh = true;
  106041. }
  106042. else {
  106043. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106044. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106045. gazer._isActionableMesh = false;
  106046. }
  106047. try {
  106048. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  106049. }
  106050. catch (err) {
  106051. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  106052. }
  106053. }
  106054. else {
  106055. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106056. gazer._currentMeshSelected = null;
  106057. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106058. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106059. }
  106060. }
  106061. }
  106062. else {
  106063. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  106064. gazer._currentMeshSelected = null;
  106065. //this._teleportationAllowed = false;
  106066. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106067. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  106068. }
  106069. };
  106070. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  106071. if (mesh) {
  106072. this.onSelectedMeshUnselected.notifyObservers(mesh);
  106073. }
  106074. };
  106075. /**
  106076. * Sets the color of the laser ray from the vr controllers.
  106077. * @param color new color for the ray.
  106078. */
  106079. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  106080. if (this._leftController) {
  106081. this._leftController._setLaserPointerColor(color);
  106082. }
  106083. if (this._rightController) {
  106084. this._rightController._setLaserPointerColor(color);
  106085. }
  106086. };
  106087. /**
  106088. * Sets the color of the ray from the vr headsets gaze.
  106089. * @param color new color for the ray.
  106090. */
  106091. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  106092. if (!this._cameraGazer._gazeTracker.material) {
  106093. return;
  106094. }
  106095. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  106096. if (this._leftController) {
  106097. this._leftController._gazeTracker.material.emissiveColor = color;
  106098. }
  106099. if (this._rightController) {
  106100. this._rightController._gazeTracker.material.emissiveColor = color;
  106101. }
  106102. };
  106103. /**
  106104. * Exits VR and disposes of the vr experience helper
  106105. */
  106106. VRExperienceHelper.prototype.dispose = function () {
  106107. if (this.isInVRMode) {
  106108. this.exitVR();
  106109. }
  106110. if (this._postProcessMove) {
  106111. this._postProcessMove.dispose();
  106112. }
  106113. if (this._webVRCamera) {
  106114. this._webVRCamera.dispose();
  106115. }
  106116. if (this._vrDeviceOrientationCamera) {
  106117. this._vrDeviceOrientationCamera.dispose();
  106118. }
  106119. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  106120. document.body.removeChild(this._btnVR);
  106121. }
  106122. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  106123. this._deviceOrientationCamera.dispose();
  106124. }
  106125. if (this._cameraGazer) {
  106126. this._cameraGazer.dispose();
  106127. }
  106128. if (this._leftController) {
  106129. this._leftController.dispose();
  106130. }
  106131. if (this._rightController) {
  106132. this._rightController.dispose();
  106133. }
  106134. if (this._teleportationTarget) {
  106135. this._teleportationTarget.dispose();
  106136. }
  106137. this._floorMeshesCollection = [];
  106138. document.removeEventListener("keydown", this._onKeyDown);
  106139. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106140. window.removeEventListener("resize", this._onResize);
  106141. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  106142. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  106143. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  106144. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  106145. document.onmsfullscreenchange = null;
  106146. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  106147. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  106148. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  106149. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106150. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  106151. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  106152. this._scene.unregisterBeforeRender(this.beforeRender);
  106153. };
  106154. /**
  106155. * Gets the name of the VRExperienceHelper class
  106156. * @returns "VRExperienceHelper"
  106157. */
  106158. VRExperienceHelper.prototype.getClassName = function () {
  106159. return "VRExperienceHelper";
  106160. };
  106161. return VRExperienceHelper;
  106162. }());
  106163. BABYLON.VRExperienceHelper = VRExperienceHelper;
  106164. })(BABYLON || (BABYLON = {}));
  106165. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  106166. // Mainly based on these 2 articles :
  106167. // 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
  106168. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  106169. var BABYLON;
  106170. (function (BABYLON) {
  106171. /**
  106172. * Defines the potential axis of a Joystick
  106173. */
  106174. var JoystickAxis;
  106175. (function (JoystickAxis) {
  106176. /** X axis */
  106177. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  106178. /** Y axis */
  106179. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  106180. /** Z axis */
  106181. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  106182. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  106183. /**
  106184. * Class used to define virtual joystick (used in touch mode)
  106185. */
  106186. var VirtualJoystick = /** @class */ (function () {
  106187. /**
  106188. * Creates a new virtual joystick
  106189. * @param leftJoystick defines that the joystick is for left hand (false by default)
  106190. */
  106191. function VirtualJoystick(leftJoystick) {
  106192. var _this = this;
  106193. if (leftJoystick) {
  106194. this._leftJoystick = true;
  106195. }
  106196. else {
  106197. this._leftJoystick = false;
  106198. }
  106199. VirtualJoystick._globalJoystickIndex++;
  106200. // By default left & right arrow keys are moving the X
  106201. // and up & down keys are moving the Y
  106202. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106203. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106204. this.reverseLeftRight = false;
  106205. this.reverseUpDown = false;
  106206. // collections of pointers
  106207. this._touches = new BABYLON.StringDictionary();
  106208. this.deltaPosition = BABYLON.Vector3.Zero();
  106209. this._joystickSensibility = 25;
  106210. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  106211. this._onResize = function (evt) {
  106212. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  106213. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  106214. if (VirtualJoystick.vjCanvas) {
  106215. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  106216. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  106217. }
  106218. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  106219. };
  106220. // injecting a canvas element on top of the canvas 3D game
  106221. if (!VirtualJoystick.vjCanvas) {
  106222. window.addEventListener("resize", this._onResize, false);
  106223. VirtualJoystick.vjCanvas = document.createElement("canvas");
  106224. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  106225. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  106226. VirtualJoystick.vjCanvas.width = window.innerWidth;
  106227. VirtualJoystick.vjCanvas.height = window.innerHeight;
  106228. VirtualJoystick.vjCanvas.style.width = "100%";
  106229. VirtualJoystick.vjCanvas.style.height = "100%";
  106230. VirtualJoystick.vjCanvas.style.position = "absolute";
  106231. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  106232. VirtualJoystick.vjCanvas.style.top = "0px";
  106233. VirtualJoystick.vjCanvas.style.left = "0px";
  106234. VirtualJoystick.vjCanvas.style.zIndex = "5";
  106235. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  106236. // Support for jQuery PEP polyfill
  106237. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  106238. var context = VirtualJoystick.vjCanvas.getContext('2d');
  106239. if (!context) {
  106240. throw new Error("Unable to create canvas for virtual joystick");
  106241. }
  106242. VirtualJoystick.vjCanvasContext = context;
  106243. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  106244. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106245. document.body.appendChild(VirtualJoystick.vjCanvas);
  106246. }
  106247. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  106248. this.pressed = false;
  106249. // default joystick color
  106250. this._joystickColor = "cyan";
  106251. this._joystickPointerID = -1;
  106252. // current joystick position
  106253. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  106254. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  106255. // origin joystick position
  106256. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  106257. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  106258. this._onPointerDownHandlerRef = function (evt) {
  106259. _this._onPointerDown(evt);
  106260. };
  106261. this._onPointerMoveHandlerRef = function (evt) {
  106262. _this._onPointerMove(evt);
  106263. };
  106264. this._onPointerUpHandlerRef = function (evt) {
  106265. _this._onPointerUp(evt);
  106266. };
  106267. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  106268. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  106269. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  106270. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  106271. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  106272. evt.preventDefault(); // Disables system menu
  106273. }, false);
  106274. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106275. }
  106276. /**
  106277. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  106278. * @param newJoystickSensibility defines the new sensibility
  106279. */
  106280. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  106281. this._joystickSensibility = newJoystickSensibility;
  106282. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  106283. };
  106284. VirtualJoystick.prototype._onPointerDown = function (e) {
  106285. var positionOnScreenCondition;
  106286. e.preventDefault();
  106287. if (this._leftJoystick === true) {
  106288. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  106289. }
  106290. else {
  106291. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  106292. }
  106293. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  106294. // First contact will be dedicated to the virtual joystick
  106295. this._joystickPointerID = e.pointerId;
  106296. this._joystickPointerStartPos.x = e.clientX;
  106297. this._joystickPointerStartPos.y = e.clientY;
  106298. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  106299. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  106300. this._deltaJoystickVector.x = 0;
  106301. this._deltaJoystickVector.y = 0;
  106302. this.pressed = true;
  106303. this._touches.add(e.pointerId.toString(), e);
  106304. }
  106305. else {
  106306. // You can only trigger the action buttons with a joystick declared
  106307. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  106308. this._action();
  106309. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  106310. }
  106311. }
  106312. };
  106313. VirtualJoystick.prototype._onPointerMove = function (e) {
  106314. // If the current pointer is the one associated to the joystick (first touch contact)
  106315. if (this._joystickPointerID == e.pointerId) {
  106316. this._joystickPointerPos.x = e.clientX;
  106317. this._joystickPointerPos.y = e.clientY;
  106318. this._deltaJoystickVector = this._joystickPointerPos.clone();
  106319. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  106320. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  106321. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  106322. switch (this._axisTargetedByLeftAndRight) {
  106323. case JoystickAxis.X:
  106324. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  106325. break;
  106326. case JoystickAxis.Y:
  106327. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  106328. break;
  106329. case JoystickAxis.Z:
  106330. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  106331. break;
  106332. }
  106333. var directionUpDown = this.reverseUpDown ? 1 : -1;
  106334. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  106335. switch (this._axisTargetedByUpAndDown) {
  106336. case JoystickAxis.X:
  106337. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  106338. break;
  106339. case JoystickAxis.Y:
  106340. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  106341. break;
  106342. case JoystickAxis.Z:
  106343. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  106344. break;
  106345. }
  106346. }
  106347. else {
  106348. var data = this._touches.get(e.pointerId.toString());
  106349. if (data) {
  106350. data.x = e.clientX;
  106351. data.y = e.clientY;
  106352. }
  106353. }
  106354. };
  106355. VirtualJoystick.prototype._onPointerUp = function (e) {
  106356. if (this._joystickPointerID == e.pointerId) {
  106357. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  106358. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  106359. this._joystickPointerID = -1;
  106360. this.pressed = false;
  106361. }
  106362. else {
  106363. var touch = this._touches.get(e.pointerId.toString());
  106364. if (touch) {
  106365. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106366. }
  106367. }
  106368. this._deltaJoystickVector.x = 0;
  106369. this._deltaJoystickVector.y = 0;
  106370. this._touches.remove(e.pointerId.toString());
  106371. };
  106372. /**
  106373. * Change the color of the virtual joystick
  106374. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  106375. */
  106376. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  106377. this._joystickColor = newColor;
  106378. };
  106379. /**
  106380. * Defines a callback to call when the joystick is touched
  106381. * @param action defines the callback
  106382. */
  106383. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  106384. this._action = action;
  106385. };
  106386. /**
  106387. * Defines which axis you'd like to control for left & right
  106388. * @param axis defines the axis to use
  106389. */
  106390. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  106391. switch (axis) {
  106392. case JoystickAxis.X:
  106393. case JoystickAxis.Y:
  106394. case JoystickAxis.Z:
  106395. this._axisTargetedByLeftAndRight = axis;
  106396. break;
  106397. default:
  106398. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106399. break;
  106400. }
  106401. };
  106402. /**
  106403. * Defines which axis you'd like to control for up & down
  106404. * @param axis defines the axis to use
  106405. */
  106406. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  106407. switch (axis) {
  106408. case JoystickAxis.X:
  106409. case JoystickAxis.Y:
  106410. case JoystickAxis.Z:
  106411. this._axisTargetedByUpAndDown = axis;
  106412. break;
  106413. default:
  106414. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106415. break;
  106416. }
  106417. };
  106418. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  106419. var _this = this;
  106420. if (this.pressed) {
  106421. this._touches.forEach(function (key, touch) {
  106422. if (touch.pointerId === _this._joystickPointerID) {
  106423. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  106424. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  106425. VirtualJoystick.vjCanvasContext.beginPath();
  106426. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106427. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106428. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  106429. VirtualJoystick.vjCanvasContext.stroke();
  106430. VirtualJoystick.vjCanvasContext.closePath();
  106431. VirtualJoystick.vjCanvasContext.beginPath();
  106432. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106433. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106434. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  106435. VirtualJoystick.vjCanvasContext.stroke();
  106436. VirtualJoystick.vjCanvasContext.closePath();
  106437. VirtualJoystick.vjCanvasContext.beginPath();
  106438. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106439. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  106440. VirtualJoystick.vjCanvasContext.stroke();
  106441. VirtualJoystick.vjCanvasContext.closePath();
  106442. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  106443. }
  106444. else {
  106445. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106446. VirtualJoystick.vjCanvasContext.beginPath();
  106447. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  106448. VirtualJoystick.vjCanvasContext.beginPath();
  106449. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  106450. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106451. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  106452. VirtualJoystick.vjCanvasContext.stroke();
  106453. VirtualJoystick.vjCanvasContext.closePath();
  106454. touch.prevX = touch.x;
  106455. touch.prevY = touch.y;
  106456. }
  106457. });
  106458. }
  106459. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106460. };
  106461. /**
  106462. * Release internal HTML canvas
  106463. */
  106464. VirtualJoystick.prototype.releaseCanvas = function () {
  106465. if (VirtualJoystick.vjCanvas) {
  106466. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  106467. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  106468. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  106469. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  106470. window.removeEventListener("resize", this._onResize);
  106471. document.body.removeChild(VirtualJoystick.vjCanvas);
  106472. VirtualJoystick.vjCanvas = null;
  106473. }
  106474. };
  106475. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  106476. VirtualJoystick._globalJoystickIndex = 0;
  106477. return VirtualJoystick;
  106478. }());
  106479. BABYLON.VirtualJoystick = VirtualJoystick;
  106480. })(BABYLON || (BABYLON = {}));
  106481. //# sourceMappingURL=babylon.virtualJoystick.js.map
  106482. var BABYLON;
  106483. (function (BABYLON) {
  106484. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  106485. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  106486. });
  106487. /**
  106488. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  106489. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106490. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106491. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106492. */
  106493. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  106494. __extends(VirtualJoysticksCamera, _super);
  106495. /**
  106496. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  106497. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106498. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106499. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106500. * @param name Define the name of the camera in the scene
  106501. * @param position Define the start position of the camera in the scene
  106502. * @param scene Define the scene the camera belongs to
  106503. */
  106504. function VirtualJoysticksCamera(name, position, scene) {
  106505. var _this = _super.call(this, name, position, scene) || this;
  106506. _this.inputs.addVirtualJoystick();
  106507. return _this;
  106508. }
  106509. /**
  106510. * Gets the current object class name.
  106511. * @return the class name
  106512. */
  106513. VirtualJoysticksCamera.prototype.getClassName = function () {
  106514. return "VirtualJoysticksCamera";
  106515. };
  106516. return VirtualJoysticksCamera;
  106517. }(BABYLON.FreeCamera));
  106518. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  106519. })(BABYLON || (BABYLON = {}));
  106520. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  106521. var BABYLON;
  106522. (function (BABYLON) {
  106523. /**
  106524. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  106525. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106526. */
  106527. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  106528. function FreeCameraVirtualJoystickInput() {
  106529. }
  106530. /**
  106531. * Gets the left stick of the virtual joystick.
  106532. * @returns The virtual Joystick
  106533. */
  106534. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  106535. return this._leftjoystick;
  106536. };
  106537. /**
  106538. * Gets the right stick of the virtual joystick.
  106539. * @returns The virtual Joystick
  106540. */
  106541. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  106542. return this._rightjoystick;
  106543. };
  106544. /**
  106545. * Update the current camera state depending on the inputs that have been used this frame.
  106546. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106547. */
  106548. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  106549. if (this._leftjoystick) {
  106550. var camera = this.camera;
  106551. var speed = camera._computeLocalCameraSpeed() * 50;
  106552. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  106553. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  106554. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  106555. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  106556. if (!this._leftjoystick.pressed) {
  106557. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  106558. }
  106559. if (!this._rightjoystick.pressed) {
  106560. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  106561. }
  106562. }
  106563. };
  106564. /**
  106565. * Attach the input controls to a specific dom element to get the input from.
  106566. * @param element Defines the element the controls should be listened from
  106567. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106568. */
  106569. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  106570. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  106571. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  106572. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  106573. this._leftjoystick.setJoystickSensibility(0.15);
  106574. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  106575. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  106576. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  106577. this._rightjoystick.reverseUpDown = true;
  106578. this._rightjoystick.setJoystickSensibility(0.05);
  106579. this._rightjoystick.setJoystickColor("yellow");
  106580. };
  106581. /**
  106582. * Detach the current controls from the specified dom element.
  106583. * @param element Defines the element to stop listening the inputs from
  106584. */
  106585. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  106586. this._leftjoystick.releaseCanvas();
  106587. this._rightjoystick.releaseCanvas();
  106588. };
  106589. /**
  106590. * Gets the class name of the current intput.
  106591. * @returns the class name
  106592. */
  106593. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  106594. return "FreeCameraVirtualJoystickInput";
  106595. };
  106596. /**
  106597. * Get the friendly name associated with the input class.
  106598. * @returns the input friendly name
  106599. */
  106600. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  106601. return "virtualJoystick";
  106602. };
  106603. return FreeCameraVirtualJoystickInput;
  106604. }());
  106605. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  106606. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  106607. })(BABYLON || (BABYLON = {}));
  106608. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  106609. var BABYLON;
  106610. (function (BABYLON) {
  106611. /**
  106612. * Class used to specify simplification options
  106613. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106614. */
  106615. var SimplificationSettings = /** @class */ (function () {
  106616. /**
  106617. * Creates a SimplificationSettings
  106618. * @param quality expected quality
  106619. * @param distance distance when this optimized version should be used
  106620. * @param optimizeMesh already optimized mesh
  106621. */
  106622. function SimplificationSettings(
  106623. /** expected quality */
  106624. quality,
  106625. /** distance when this optimized version should be used */
  106626. distance,
  106627. /** already optimized mesh */
  106628. optimizeMesh) {
  106629. this.quality = quality;
  106630. this.distance = distance;
  106631. this.optimizeMesh = optimizeMesh;
  106632. }
  106633. return SimplificationSettings;
  106634. }());
  106635. BABYLON.SimplificationSettings = SimplificationSettings;
  106636. /**
  106637. * Queue used to order the simplification tasks
  106638. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106639. */
  106640. var SimplificationQueue = /** @class */ (function () {
  106641. /**
  106642. * Creates a new queue
  106643. */
  106644. function SimplificationQueue() {
  106645. this.running = false;
  106646. this._simplificationArray = [];
  106647. }
  106648. /**
  106649. * Adds a new simplification task
  106650. * @param task defines a task to add
  106651. */
  106652. SimplificationQueue.prototype.addTask = function (task) {
  106653. this._simplificationArray.push(task);
  106654. };
  106655. /**
  106656. * Execute next task
  106657. */
  106658. SimplificationQueue.prototype.executeNext = function () {
  106659. var task = this._simplificationArray.pop();
  106660. if (task) {
  106661. this.running = true;
  106662. this.runSimplification(task);
  106663. }
  106664. else {
  106665. this.running = false;
  106666. }
  106667. };
  106668. /**
  106669. * Execute a simplification task
  106670. * @param task defines the task to run
  106671. */
  106672. SimplificationQueue.prototype.runSimplification = function (task) {
  106673. var _this = this;
  106674. if (task.parallelProcessing) {
  106675. //parallel simplifier
  106676. task.settings.forEach(function (setting) {
  106677. var simplifier = _this.getSimplifier(task);
  106678. simplifier.simplify(setting, function (newMesh) {
  106679. task.mesh.addLODLevel(setting.distance, newMesh);
  106680. newMesh.isVisible = true;
  106681. //check if it is the last
  106682. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  106683. //all done, run the success callback.
  106684. task.successCallback();
  106685. }
  106686. _this.executeNext();
  106687. });
  106688. });
  106689. }
  106690. else {
  106691. //single simplifier.
  106692. var simplifier = this.getSimplifier(task);
  106693. var runDecimation = function (setting, callback) {
  106694. simplifier.simplify(setting, function (newMesh) {
  106695. task.mesh.addLODLevel(setting.distance, newMesh);
  106696. newMesh.isVisible = true;
  106697. //run the next quality level
  106698. callback();
  106699. });
  106700. };
  106701. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  106702. runDecimation(task.settings[loop.index], function () {
  106703. loop.executeNext();
  106704. });
  106705. }, function () {
  106706. //execution ended, run the success callback.
  106707. if (task.successCallback) {
  106708. task.successCallback();
  106709. }
  106710. _this.executeNext();
  106711. });
  106712. }
  106713. };
  106714. SimplificationQueue.prototype.getSimplifier = function (task) {
  106715. switch (task.simplificationType) {
  106716. case SimplificationType.QUADRATIC:
  106717. default:
  106718. return new QuadraticErrorSimplification(task.mesh);
  106719. }
  106720. };
  106721. return SimplificationQueue;
  106722. }());
  106723. BABYLON.SimplificationQueue = SimplificationQueue;
  106724. /**
  106725. * The implemented types of simplification
  106726. * At the moment only Quadratic Error Decimation is implemented
  106727. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106728. */
  106729. var SimplificationType;
  106730. (function (SimplificationType) {
  106731. /** Quadratic error decimation */
  106732. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  106733. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  106734. var DecimationTriangle = /** @class */ (function () {
  106735. function DecimationTriangle(vertices) {
  106736. this.vertices = vertices;
  106737. this.error = new Array(4);
  106738. this.deleted = false;
  106739. this.isDirty = false;
  106740. this.deletePending = false;
  106741. this.borderFactor = 0;
  106742. }
  106743. return DecimationTriangle;
  106744. }());
  106745. var DecimationVertex = /** @class */ (function () {
  106746. function DecimationVertex(position, id) {
  106747. this.position = position;
  106748. this.id = id;
  106749. this.isBorder = true;
  106750. this.q = new QuadraticMatrix();
  106751. this.triangleCount = 0;
  106752. this.triangleStart = 0;
  106753. this.originalOffsets = [];
  106754. }
  106755. DecimationVertex.prototype.updatePosition = function (newPosition) {
  106756. this.position.copyFrom(newPosition);
  106757. };
  106758. return DecimationVertex;
  106759. }());
  106760. var QuadraticMatrix = /** @class */ (function () {
  106761. function QuadraticMatrix(data) {
  106762. this.data = new Array(10);
  106763. for (var i = 0; i < 10; ++i) {
  106764. if (data && data[i]) {
  106765. this.data[i] = data[i];
  106766. }
  106767. else {
  106768. this.data[i] = 0;
  106769. }
  106770. }
  106771. }
  106772. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  106773. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  106774. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  106775. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  106776. return det;
  106777. };
  106778. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  106779. for (var i = 0; i < 10; ++i) {
  106780. this.data[i] += matrix.data[i];
  106781. }
  106782. };
  106783. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  106784. for (var i = 0; i < 10; ++i) {
  106785. this.data[i] += data[i];
  106786. }
  106787. };
  106788. QuadraticMatrix.prototype.add = function (matrix) {
  106789. var m = new QuadraticMatrix();
  106790. for (var i = 0; i < 10; ++i) {
  106791. m.data[i] = this.data[i] + matrix.data[i];
  106792. }
  106793. return m;
  106794. };
  106795. QuadraticMatrix.FromData = function (a, b, c, d) {
  106796. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  106797. };
  106798. //returning an array to avoid garbage collection
  106799. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  106800. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  106801. };
  106802. return QuadraticMatrix;
  106803. }());
  106804. var Reference = /** @class */ (function () {
  106805. function Reference(vertexId, triangleId) {
  106806. this.vertexId = vertexId;
  106807. this.triangleId = triangleId;
  106808. }
  106809. return Reference;
  106810. }());
  106811. /**
  106812. * An implementation of the Quadratic Error simplification algorithm.
  106813. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  106814. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  106815. * @author RaananW
  106816. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106817. */
  106818. var QuadraticErrorSimplification = /** @class */ (function () {
  106819. function QuadraticErrorSimplification(_mesh) {
  106820. this._mesh = _mesh;
  106821. this.syncIterations = 5000;
  106822. this.aggressiveness = 7;
  106823. this.decimationIterations = 100;
  106824. this.boundingBoxEpsilon = BABYLON.Epsilon;
  106825. }
  106826. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  106827. var _this = this;
  106828. this.initDecimatedMesh();
  106829. //iterating through the submeshes array, one after the other.
  106830. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  106831. _this.initWithMesh(loop.index, function () {
  106832. _this.runDecimation(settings, loop.index, function () {
  106833. loop.executeNext();
  106834. });
  106835. }, settings.optimizeMesh);
  106836. }, function () {
  106837. setTimeout(function () {
  106838. successCallback(_this._reconstructedMesh);
  106839. }, 0);
  106840. });
  106841. };
  106842. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  106843. var _this = this;
  106844. var targetCount = ~~(this.triangles.length * settings.quality);
  106845. var deletedTriangles = 0;
  106846. var triangleCount = this.triangles.length;
  106847. var iterationFunction = function (iteration, callback) {
  106848. setTimeout(function () {
  106849. if (iteration % 5 === 0) {
  106850. _this.updateMesh(iteration === 0);
  106851. }
  106852. for (var i = 0; i < _this.triangles.length; ++i) {
  106853. _this.triangles[i].isDirty = false;
  106854. }
  106855. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  106856. var trianglesIterator = function (i) {
  106857. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  106858. var t = _this.triangles[tIdx];
  106859. if (!t) {
  106860. return;
  106861. }
  106862. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  106863. return;
  106864. }
  106865. for (var j = 0; j < 3; ++j) {
  106866. if (t.error[j] < threshold) {
  106867. var deleted0 = [];
  106868. var deleted1 = [];
  106869. var v0 = t.vertices[j];
  106870. var v1 = t.vertices[(j + 1) % 3];
  106871. if (v0.isBorder || v1.isBorder) {
  106872. continue;
  106873. }
  106874. var p = BABYLON.Vector3.Zero();
  106875. var n = BABYLON.Vector3.Zero();
  106876. var uv = BABYLON.Vector2.Zero();
  106877. var color = new BABYLON.Color4(0, 0, 0, 1);
  106878. _this.calculateError(v0, v1, p, n, uv, color);
  106879. var delTr = new Array();
  106880. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  106881. continue;
  106882. }
  106883. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  106884. continue;
  106885. }
  106886. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  106887. continue;
  106888. }
  106889. var uniqueArray = new Array();
  106890. delTr.forEach(function (deletedT) {
  106891. if (uniqueArray.indexOf(deletedT) === -1) {
  106892. deletedT.deletePending = true;
  106893. uniqueArray.push(deletedT);
  106894. }
  106895. });
  106896. if (uniqueArray.length % 2 !== 0) {
  106897. continue;
  106898. }
  106899. v0.q = v1.q.add(v0.q);
  106900. v0.updatePosition(p);
  106901. var tStart = _this.references.length;
  106902. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  106903. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  106904. var tCount = _this.references.length - tStart;
  106905. if (tCount <= v0.triangleCount) {
  106906. if (tCount) {
  106907. for (var c = 0; c < tCount; c++) {
  106908. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  106909. }
  106910. }
  106911. }
  106912. else {
  106913. v0.triangleStart = tStart;
  106914. }
  106915. v0.triangleCount = tCount;
  106916. break;
  106917. }
  106918. }
  106919. };
  106920. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  106921. }, 0);
  106922. };
  106923. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  106924. if (triangleCount - deletedTriangles <= targetCount) {
  106925. loop.breakLoop();
  106926. }
  106927. else {
  106928. iterationFunction(loop.index, function () {
  106929. loop.executeNext();
  106930. });
  106931. }
  106932. }, function () {
  106933. setTimeout(function () {
  106934. //reconstruct this part of the mesh
  106935. _this.reconstructMesh(submeshIndex);
  106936. successCallback();
  106937. }, 0);
  106938. });
  106939. };
  106940. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  106941. var _this = this;
  106942. this.vertices = [];
  106943. this.triangles = [];
  106944. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106945. var indices = this._mesh.getIndices();
  106946. var submesh = this._mesh.subMeshes[submeshIndex];
  106947. var findInVertices = function (positionToSearch) {
  106948. if (optimizeMesh) {
  106949. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  106950. if (_this.vertices[ii].position.equals(positionToSearch)) {
  106951. return _this.vertices[ii];
  106952. }
  106953. }
  106954. }
  106955. return null;
  106956. };
  106957. var vertexReferences = [];
  106958. var vertexInit = function (i) {
  106959. if (!positionData) {
  106960. return;
  106961. }
  106962. var offset = i + submesh.verticesStart;
  106963. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  106964. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  106965. vertex.originalOffsets.push(offset);
  106966. if (vertex.id === _this.vertices.length) {
  106967. _this.vertices.push(vertex);
  106968. }
  106969. vertexReferences.push(vertex.id);
  106970. };
  106971. //var totalVertices = mesh.getTotalVertices();
  106972. var totalVertices = submesh.verticesCount;
  106973. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  106974. var indicesInit = function (i) {
  106975. if (!indices) {
  106976. return;
  106977. }
  106978. var offset = (submesh.indexStart / 3) + i;
  106979. var pos = (offset * 3);
  106980. var i0 = indices[pos + 0];
  106981. var i1 = indices[pos + 1];
  106982. var i2 = indices[pos + 2];
  106983. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  106984. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  106985. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  106986. var triangle = new DecimationTriangle([v0, v1, v2]);
  106987. triangle.originalOffset = pos;
  106988. _this.triangles.push(triangle);
  106989. };
  106990. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  106991. _this.init(callback);
  106992. });
  106993. });
  106994. };
  106995. QuadraticErrorSimplification.prototype.init = function (callback) {
  106996. var _this = this;
  106997. var triangleInit1 = function (i) {
  106998. var t = _this.triangles[i];
  106999. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  107000. for (var j = 0; j < 3; j++) {
  107001. 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))));
  107002. }
  107003. };
  107004. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  107005. var triangleInit2 = function (i) {
  107006. var t = _this.triangles[i];
  107007. for (var j = 0; j < 3; ++j) {
  107008. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  107009. }
  107010. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  107011. };
  107012. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  107013. callback();
  107014. });
  107015. });
  107016. };
  107017. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  107018. var newTriangles = [];
  107019. var i;
  107020. for (i = 0; i < this.vertices.length; ++i) {
  107021. this.vertices[i].triangleCount = 0;
  107022. }
  107023. var t;
  107024. var j;
  107025. for (i = 0; i < this.triangles.length; ++i) {
  107026. if (!this.triangles[i].deleted) {
  107027. t = this.triangles[i];
  107028. for (j = 0; j < 3; ++j) {
  107029. t.vertices[j].triangleCount = 1;
  107030. }
  107031. newTriangles.push(t);
  107032. }
  107033. }
  107034. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  107035. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  107036. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  107037. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  107038. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  107039. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  107040. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  107041. var vertexCount = 0;
  107042. for (i = 0; i < this.vertices.length; ++i) {
  107043. var vertex = this.vertices[i];
  107044. vertex.id = vertexCount;
  107045. if (vertex.triangleCount) {
  107046. vertex.originalOffsets.forEach(function (originalOffset) {
  107047. if (!normalData) {
  107048. return;
  107049. }
  107050. newPositionData.push(vertex.position.x);
  107051. newPositionData.push(vertex.position.y);
  107052. newPositionData.push(vertex.position.z);
  107053. newNormalData.push(normalData[originalOffset * 3]);
  107054. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  107055. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  107056. if (uvs && uvs.length) {
  107057. newUVsData.push(uvs[(originalOffset * 2)]);
  107058. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  107059. }
  107060. else if (colorsData && colorsData.length) {
  107061. newColorsData.push(colorsData[(originalOffset * 4)]);
  107062. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  107063. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  107064. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  107065. }
  107066. ++vertexCount;
  107067. });
  107068. }
  107069. }
  107070. var startingIndex = this._reconstructedMesh.getTotalIndices();
  107071. var startingVertex = this._reconstructedMesh.getTotalVertices();
  107072. var submeshesArray = this._reconstructedMesh.subMeshes;
  107073. this._reconstructedMesh.subMeshes = [];
  107074. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  107075. var originalIndices = this._mesh.getIndices();
  107076. for (i = 0; i < newTriangles.length; ++i) {
  107077. t = newTriangles[i]; //now get the new referencing point for each vertex
  107078. [0, 1, 2].forEach(function (idx) {
  107079. var id = originalIndices[t.originalOffset + idx];
  107080. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  107081. if (offset < 0) {
  107082. offset = 0;
  107083. }
  107084. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  107085. });
  107086. }
  107087. //overwriting the old vertex buffers and indices.
  107088. this._reconstructedMesh.setIndices(newIndicesArray);
  107089. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  107090. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  107091. if (newUVsData.length > 0) {
  107092. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  107093. }
  107094. if (newColorsData.length > 0) {
  107095. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  107096. }
  107097. //create submesh
  107098. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  107099. if (submeshIndex > 0) {
  107100. this._reconstructedMesh.subMeshes = [];
  107101. submeshesArray.forEach(function (submesh) {
  107102. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  107103. });
  107104. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  107105. }
  107106. };
  107107. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  107108. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  107109. this._reconstructedMesh.material = this._mesh.material;
  107110. this._reconstructedMesh.parent = this._mesh.parent;
  107111. this._reconstructedMesh.isVisible = false;
  107112. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  107113. };
  107114. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  107115. for (var i = 0; i < vertex1.triangleCount; ++i) {
  107116. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  107117. if (t.deleted) {
  107118. continue;
  107119. }
  107120. var s = this.references[vertex1.triangleStart + i].vertexId;
  107121. var v1 = t.vertices[(s + 1) % 3];
  107122. var v2 = t.vertices[(s + 2) % 3];
  107123. if ((v1 === vertex2 || v2 === vertex2)) {
  107124. deletedArray[i] = true;
  107125. delTr.push(t);
  107126. continue;
  107127. }
  107128. var d1 = v1.position.subtract(point);
  107129. d1 = d1.normalize();
  107130. var d2 = v2.position.subtract(point);
  107131. d2 = d2.normalize();
  107132. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  107133. return true;
  107134. }
  107135. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  107136. deletedArray[i] = false;
  107137. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  107138. return true;
  107139. }
  107140. }
  107141. return false;
  107142. };
  107143. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  107144. var newDeleted = deletedTriangles;
  107145. for (var i = 0; i < vertex.triangleCount; ++i) {
  107146. var ref = this.references[vertex.triangleStart + i];
  107147. var t = this.triangles[ref.triangleId];
  107148. if (t.deleted) {
  107149. continue;
  107150. }
  107151. if (deletedArray[i] && t.deletePending) {
  107152. t.deleted = true;
  107153. newDeleted++;
  107154. continue;
  107155. }
  107156. t.vertices[ref.vertexId] = origVertex;
  107157. t.isDirty = true;
  107158. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  107159. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  107160. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  107161. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  107162. this.references.push(ref);
  107163. }
  107164. return newDeleted;
  107165. };
  107166. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  107167. for (var i = 0; i < this.vertices.length; ++i) {
  107168. var vCount = [];
  107169. var vId = [];
  107170. var v = this.vertices[i];
  107171. var j;
  107172. for (j = 0; j < v.triangleCount; ++j) {
  107173. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  107174. for (var ii = 0; ii < 3; ii++) {
  107175. var ofs = 0;
  107176. var vv = triangle.vertices[ii];
  107177. while (ofs < vCount.length) {
  107178. if (vId[ofs] === vv.id) {
  107179. break;
  107180. }
  107181. ++ofs;
  107182. }
  107183. if (ofs === vCount.length) {
  107184. vCount.push(1);
  107185. vId.push(vv.id);
  107186. }
  107187. else {
  107188. vCount[ofs]++;
  107189. }
  107190. }
  107191. }
  107192. for (j = 0; j < vCount.length; ++j) {
  107193. if (vCount[j] === 1) {
  107194. this.vertices[vId[j]].isBorder = true;
  107195. }
  107196. else {
  107197. this.vertices[vId[j]].isBorder = false;
  107198. }
  107199. }
  107200. }
  107201. };
  107202. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  107203. if (identifyBorders === void 0) { identifyBorders = false; }
  107204. var i;
  107205. if (!identifyBorders) {
  107206. var newTrianglesVector = [];
  107207. for (i = 0; i < this.triangles.length; ++i) {
  107208. if (!this.triangles[i].deleted) {
  107209. newTrianglesVector.push(this.triangles[i]);
  107210. }
  107211. }
  107212. this.triangles = newTrianglesVector;
  107213. }
  107214. for (i = 0; i < this.vertices.length; ++i) {
  107215. this.vertices[i].triangleCount = 0;
  107216. this.vertices[i].triangleStart = 0;
  107217. }
  107218. var t;
  107219. var j;
  107220. var v;
  107221. for (i = 0; i < this.triangles.length; ++i) {
  107222. t = this.triangles[i];
  107223. for (j = 0; j < 3; ++j) {
  107224. v = t.vertices[j];
  107225. v.triangleCount++;
  107226. }
  107227. }
  107228. var tStart = 0;
  107229. for (i = 0; i < this.vertices.length; ++i) {
  107230. this.vertices[i].triangleStart = tStart;
  107231. tStart += this.vertices[i].triangleCount;
  107232. this.vertices[i].triangleCount = 0;
  107233. }
  107234. var newReferences = new Array(this.triangles.length * 3);
  107235. for (i = 0; i < this.triangles.length; ++i) {
  107236. t = this.triangles[i];
  107237. for (j = 0; j < 3; ++j) {
  107238. v = t.vertices[j];
  107239. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  107240. v.triangleCount++;
  107241. }
  107242. }
  107243. this.references = newReferences;
  107244. if (identifyBorders) {
  107245. this.identifyBorder();
  107246. }
  107247. };
  107248. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  107249. var x = point.x;
  107250. var y = point.y;
  107251. var z = point.z;
  107252. 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
  107253. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  107254. };
  107255. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  107256. var q = vertex1.q.add(vertex2.q);
  107257. var border = vertex1.isBorder && vertex2.isBorder;
  107258. var error = 0;
  107259. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  107260. if (qDet !== 0 && !border) {
  107261. if (!pointResult) {
  107262. pointResult = BABYLON.Vector3.Zero();
  107263. }
  107264. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  107265. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  107266. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  107267. error = this.vertexError(q, pointResult);
  107268. }
  107269. else {
  107270. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  107271. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  107272. var error1 = this.vertexError(q, vertex1.position);
  107273. var error2 = this.vertexError(q, vertex2.position);
  107274. var error3 = this.vertexError(q, p3);
  107275. error = Math.min(error1, error2, error3);
  107276. if (error === error1) {
  107277. if (pointResult) {
  107278. pointResult.copyFrom(vertex1.position);
  107279. }
  107280. }
  107281. else if (error === error2) {
  107282. if (pointResult) {
  107283. pointResult.copyFrom(vertex2.position);
  107284. }
  107285. }
  107286. else {
  107287. if (pointResult) {
  107288. pointResult.copyFrom(p3);
  107289. }
  107290. }
  107291. }
  107292. return error;
  107293. };
  107294. return QuadraticErrorSimplification;
  107295. }());
  107296. })(BABYLON || (BABYLON = {}));
  107297. //# sourceMappingURL=babylon.meshSimplification.js.map
  107298. var BABYLON;
  107299. (function (BABYLON) {
  107300. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  107301. get: function () {
  107302. if (!this._simplificationQueue) {
  107303. this._simplificationQueue = new BABYLON.SimplificationQueue();
  107304. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  107305. if (!component) {
  107306. component = new SimplicationQueueSceneComponent(this);
  107307. this._addComponent(component);
  107308. }
  107309. }
  107310. return this._simplificationQueue;
  107311. },
  107312. set: function (value) {
  107313. this._simplificationQueue = value;
  107314. },
  107315. enumerable: true,
  107316. configurable: true
  107317. });
  107318. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  107319. if (parallelProcessing === void 0) { parallelProcessing = true; }
  107320. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  107321. this.getScene().simplificationQueue.addTask({
  107322. settings: settings,
  107323. parallelProcessing: parallelProcessing,
  107324. mesh: this,
  107325. simplificationType: simplificationType,
  107326. successCallback: successCallback
  107327. });
  107328. return this;
  107329. };
  107330. /**
  107331. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  107332. * created in a scene
  107333. */
  107334. var SimplicationQueueSceneComponent = /** @class */ (function () {
  107335. /**
  107336. * Creates a new instance of the component for the given scene
  107337. * @param scene Defines the scene to register the component in
  107338. */
  107339. function SimplicationQueueSceneComponent(scene) {
  107340. /**
  107341. * The component name helpfull to identify the component in the list of scene components.
  107342. */
  107343. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  107344. this.scene = scene;
  107345. }
  107346. /**
  107347. * Registers the component in a given scene
  107348. */
  107349. SimplicationQueueSceneComponent.prototype.register = function () {
  107350. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  107351. };
  107352. /**
  107353. * Rebuilds the elements related to this component in case of
  107354. * context lost for instance.
  107355. */
  107356. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  107357. // Nothing to do for this component
  107358. };
  107359. /**
  107360. * Disposes the component and the associated ressources
  107361. */
  107362. SimplicationQueueSceneComponent.prototype.dispose = function () {
  107363. // Nothing to do for this component
  107364. };
  107365. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  107366. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  107367. this.scene._simplificationQueue.executeNext();
  107368. }
  107369. };
  107370. return SimplicationQueueSceneComponent;
  107371. }());
  107372. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  107373. })(BABYLON || (BABYLON = {}));
  107374. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  107375. var BABYLON;
  107376. (function (BABYLON) {
  107377. /**
  107378. * Class used to represent a specific level of detail of a mesh
  107379. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  107380. */
  107381. var MeshLODLevel = /** @class */ (function () {
  107382. /**
  107383. * Creates a new LOD level
  107384. * @param distance defines the distance where this level should star being displayed
  107385. * @param mesh defines the mesh to use to render this level
  107386. */
  107387. function MeshLODLevel(
  107388. /** Defines the distance where this level should star being displayed */
  107389. distance,
  107390. /** Defines the mesh to use to render this level */
  107391. mesh) {
  107392. this.distance = distance;
  107393. this.mesh = mesh;
  107394. }
  107395. return MeshLODLevel;
  107396. }());
  107397. BABYLON.MeshLODLevel = MeshLODLevel;
  107398. })(BABYLON || (BABYLON = {}));
  107399. //# sourceMappingURL=babylon.meshLODLevel.js.map
  107400. var BABYLON;
  107401. (function (BABYLON) {
  107402. /**
  107403. * Defines the root class used to create scene optimization to use with SceneOptimizer
  107404. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107405. */
  107406. var SceneOptimization = /** @class */ (function () {
  107407. /**
  107408. * Creates the SceneOptimization object
  107409. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107410. * @param desc defines the description associated with the optimization
  107411. */
  107412. function SceneOptimization(
  107413. /**
  107414. * Defines the priority of this optimization (0 by default which means first in the list)
  107415. */
  107416. priority) {
  107417. if (priority === void 0) { priority = 0; }
  107418. this.priority = priority;
  107419. }
  107420. /**
  107421. * Gets a string describing the action executed by the current optimization
  107422. * @returns description string
  107423. */
  107424. SceneOptimization.prototype.getDescription = function () {
  107425. return "";
  107426. };
  107427. /**
  107428. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107429. * @param scene defines the current scene where to apply this optimization
  107430. * @param optimizer defines the current optimizer
  107431. * @returns true if everything that can be done was applied
  107432. */
  107433. SceneOptimization.prototype.apply = function (scene, optimizer) {
  107434. return true;
  107435. };
  107436. return SceneOptimization;
  107437. }());
  107438. BABYLON.SceneOptimization = SceneOptimization;
  107439. /**
  107440. * Defines an optimization used to reduce the size of render target textures
  107441. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107442. */
  107443. var TextureOptimization = /** @class */ (function (_super) {
  107444. __extends(TextureOptimization, _super);
  107445. /**
  107446. * Creates the TextureOptimization object
  107447. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107448. * @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
  107449. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107450. */
  107451. function TextureOptimization(
  107452. /**
  107453. * Defines the priority of this optimization (0 by default which means first in the list)
  107454. */
  107455. priority,
  107456. /**
  107457. * 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
  107458. */
  107459. maximumSize,
  107460. /**
  107461. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107462. */
  107463. step) {
  107464. if (priority === void 0) { priority = 0; }
  107465. if (maximumSize === void 0) { maximumSize = 1024; }
  107466. if (step === void 0) { step = 0.5; }
  107467. var _this = _super.call(this, priority) || this;
  107468. _this.priority = priority;
  107469. _this.maximumSize = maximumSize;
  107470. _this.step = step;
  107471. return _this;
  107472. }
  107473. /**
  107474. * Gets a string describing the action executed by the current optimization
  107475. * @returns description string
  107476. */
  107477. TextureOptimization.prototype.getDescription = function () {
  107478. return "Reducing render target texture size to " + this.maximumSize;
  107479. };
  107480. /**
  107481. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107482. * @param scene defines the current scene where to apply this optimization
  107483. * @param optimizer defines the current optimizer
  107484. * @returns true if everything that can be done was applied
  107485. */
  107486. TextureOptimization.prototype.apply = function (scene, optimizer) {
  107487. var allDone = true;
  107488. for (var index = 0; index < scene.textures.length; index++) {
  107489. var texture = scene.textures[index];
  107490. if (!texture.canRescale || texture.getContext) {
  107491. continue;
  107492. }
  107493. var currentSize = texture.getSize();
  107494. var maxDimension = Math.max(currentSize.width, currentSize.height);
  107495. if (maxDimension > this.maximumSize) {
  107496. texture.scale(this.step);
  107497. allDone = false;
  107498. }
  107499. }
  107500. return allDone;
  107501. };
  107502. return TextureOptimization;
  107503. }(SceneOptimization));
  107504. BABYLON.TextureOptimization = TextureOptimization;
  107505. /**
  107506. * Defines an optimization used to increase or decrease the rendering resolution
  107507. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107508. */
  107509. var HardwareScalingOptimization = /** @class */ (function (_super) {
  107510. __extends(HardwareScalingOptimization, _super);
  107511. /**
  107512. * Creates the HardwareScalingOptimization object
  107513. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107514. * @param maximumScale defines the maximum scale to use (2 by default)
  107515. * @param step defines the step to use between two passes (0.5 by default)
  107516. */
  107517. function HardwareScalingOptimization(
  107518. /**
  107519. * Defines the priority of this optimization (0 by default which means first in the list)
  107520. */
  107521. priority,
  107522. /**
  107523. * Defines the maximum scale to use (2 by default)
  107524. */
  107525. maximumScale,
  107526. /**
  107527. * Defines the step to use between two passes (0.5 by default)
  107528. */
  107529. step) {
  107530. if (priority === void 0) { priority = 0; }
  107531. if (maximumScale === void 0) { maximumScale = 2; }
  107532. if (step === void 0) { step = 0.25; }
  107533. var _this = _super.call(this, priority) || this;
  107534. _this.priority = priority;
  107535. _this.maximumScale = maximumScale;
  107536. _this.step = step;
  107537. _this._currentScale = -1;
  107538. _this._directionOffset = 1;
  107539. return _this;
  107540. }
  107541. /**
  107542. * Gets a string describing the action executed by the current optimization
  107543. * @return description string
  107544. */
  107545. HardwareScalingOptimization.prototype.getDescription = function () {
  107546. return "Setting hardware scaling level to " + this._currentScale;
  107547. };
  107548. /**
  107549. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107550. * @param scene defines the current scene where to apply this optimization
  107551. * @param optimizer defines the current optimizer
  107552. * @returns true if everything that can be done was applied
  107553. */
  107554. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  107555. if (this._currentScale === -1) {
  107556. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  107557. if (this._currentScale > this.maximumScale) {
  107558. this._directionOffset = -1;
  107559. }
  107560. }
  107561. this._currentScale += this._directionOffset * this.step;
  107562. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  107563. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  107564. };
  107565. return HardwareScalingOptimization;
  107566. }(SceneOptimization));
  107567. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  107568. /**
  107569. * Defines an optimization used to remove shadows
  107570. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107571. */
  107572. var ShadowsOptimization = /** @class */ (function (_super) {
  107573. __extends(ShadowsOptimization, _super);
  107574. function ShadowsOptimization() {
  107575. return _super !== null && _super.apply(this, arguments) || this;
  107576. }
  107577. /**
  107578. * Gets a string describing the action executed by the current optimization
  107579. * @return description string
  107580. */
  107581. ShadowsOptimization.prototype.getDescription = function () {
  107582. return "Turning shadows on/off";
  107583. };
  107584. /**
  107585. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107586. * @param scene defines the current scene where to apply this optimization
  107587. * @param optimizer defines the current optimizer
  107588. * @returns true if everything that can be done was applied
  107589. */
  107590. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  107591. scene.shadowsEnabled = optimizer.isInImprovementMode;
  107592. return true;
  107593. };
  107594. return ShadowsOptimization;
  107595. }(SceneOptimization));
  107596. BABYLON.ShadowsOptimization = ShadowsOptimization;
  107597. /**
  107598. * Defines an optimization used to turn post-processes off
  107599. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107600. */
  107601. var PostProcessesOptimization = /** @class */ (function (_super) {
  107602. __extends(PostProcessesOptimization, _super);
  107603. function PostProcessesOptimization() {
  107604. return _super !== null && _super.apply(this, arguments) || this;
  107605. }
  107606. /**
  107607. * Gets a string describing the action executed by the current optimization
  107608. * @return description string
  107609. */
  107610. PostProcessesOptimization.prototype.getDescription = function () {
  107611. return "Turning post-processes on/off";
  107612. };
  107613. /**
  107614. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107615. * @param scene defines the current scene where to apply this optimization
  107616. * @param optimizer defines the current optimizer
  107617. * @returns true if everything that can be done was applied
  107618. */
  107619. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  107620. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  107621. return true;
  107622. };
  107623. return PostProcessesOptimization;
  107624. }(SceneOptimization));
  107625. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  107626. /**
  107627. * Defines an optimization used to turn lens flares off
  107628. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107629. */
  107630. var LensFlaresOptimization = /** @class */ (function (_super) {
  107631. __extends(LensFlaresOptimization, _super);
  107632. function LensFlaresOptimization() {
  107633. return _super !== null && _super.apply(this, arguments) || this;
  107634. }
  107635. /**
  107636. * Gets a string describing the action executed by the current optimization
  107637. * @return description string
  107638. */
  107639. LensFlaresOptimization.prototype.getDescription = function () {
  107640. return "Turning lens flares on/off";
  107641. };
  107642. /**
  107643. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107644. * @param scene defines the current scene where to apply this optimization
  107645. * @param optimizer defines the current optimizer
  107646. * @returns true if everything that can be done was applied
  107647. */
  107648. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  107649. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  107650. return true;
  107651. };
  107652. return LensFlaresOptimization;
  107653. }(SceneOptimization));
  107654. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  107655. /**
  107656. * Defines an optimization based on user defined callback.
  107657. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107658. */
  107659. var CustomOptimization = /** @class */ (function (_super) {
  107660. __extends(CustomOptimization, _super);
  107661. function CustomOptimization() {
  107662. return _super !== null && _super.apply(this, arguments) || this;
  107663. }
  107664. /**
  107665. * Gets a string describing the action executed by the current optimization
  107666. * @returns description string
  107667. */
  107668. CustomOptimization.prototype.getDescription = function () {
  107669. if (this.onGetDescription) {
  107670. return this.onGetDescription();
  107671. }
  107672. return "Running user defined callback";
  107673. };
  107674. /**
  107675. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107676. * @param scene defines the current scene where to apply this optimization
  107677. * @param optimizer defines the current optimizer
  107678. * @returns true if everything that can be done was applied
  107679. */
  107680. CustomOptimization.prototype.apply = function (scene, optimizer) {
  107681. if (this.onApply) {
  107682. return this.onApply(scene, optimizer);
  107683. }
  107684. return true;
  107685. };
  107686. return CustomOptimization;
  107687. }(SceneOptimization));
  107688. BABYLON.CustomOptimization = CustomOptimization;
  107689. /**
  107690. * Defines an optimization used to turn particles off
  107691. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107692. */
  107693. var ParticlesOptimization = /** @class */ (function (_super) {
  107694. __extends(ParticlesOptimization, _super);
  107695. function ParticlesOptimization() {
  107696. return _super !== null && _super.apply(this, arguments) || this;
  107697. }
  107698. /**
  107699. * Gets a string describing the action executed by the current optimization
  107700. * @return description string
  107701. */
  107702. ParticlesOptimization.prototype.getDescription = function () {
  107703. return "Turning particles on/off";
  107704. };
  107705. /**
  107706. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107707. * @param scene defines the current scene where to apply this optimization
  107708. * @param optimizer defines the current optimizer
  107709. * @returns true if everything that can be done was applied
  107710. */
  107711. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  107712. scene.particlesEnabled = optimizer.isInImprovementMode;
  107713. return true;
  107714. };
  107715. return ParticlesOptimization;
  107716. }(SceneOptimization));
  107717. BABYLON.ParticlesOptimization = ParticlesOptimization;
  107718. /**
  107719. * Defines an optimization used to turn render targets off
  107720. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107721. */
  107722. var RenderTargetsOptimization = /** @class */ (function (_super) {
  107723. __extends(RenderTargetsOptimization, _super);
  107724. function RenderTargetsOptimization() {
  107725. return _super !== null && _super.apply(this, arguments) || this;
  107726. }
  107727. /**
  107728. * Gets a string describing the action executed by the current optimization
  107729. * @return description string
  107730. */
  107731. RenderTargetsOptimization.prototype.getDescription = function () {
  107732. return "Turning render targets off";
  107733. };
  107734. /**
  107735. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107736. * @param scene defines the current scene where to apply this optimization
  107737. * @param optimizer defines the current optimizer
  107738. * @returns true if everything that can be done was applied
  107739. */
  107740. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  107741. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  107742. return true;
  107743. };
  107744. return RenderTargetsOptimization;
  107745. }(SceneOptimization));
  107746. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  107747. /**
  107748. * Defines an optimization used to merge meshes with compatible materials
  107749. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107750. */
  107751. var MergeMeshesOptimization = /** @class */ (function (_super) {
  107752. __extends(MergeMeshesOptimization, _super);
  107753. function MergeMeshesOptimization() {
  107754. var _this = _super !== null && _super.apply(this, arguments) || this;
  107755. _this._canBeMerged = function (abstractMesh) {
  107756. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  107757. return false;
  107758. }
  107759. var mesh = abstractMesh;
  107760. if (mesh.isDisposed()) {
  107761. return false;
  107762. }
  107763. if (!mesh.isVisible || !mesh.isEnabled()) {
  107764. return false;
  107765. }
  107766. if (mesh.instances.length > 0) {
  107767. return false;
  107768. }
  107769. if (mesh.skeleton || mesh.hasLODLevels) {
  107770. return false;
  107771. }
  107772. return true;
  107773. };
  107774. return _this;
  107775. }
  107776. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  107777. /**
  107778. * Gets or sets a boolean which defines if optimization octree has to be updated
  107779. */
  107780. get: function () {
  107781. return MergeMeshesOptimization._UpdateSelectionTree;
  107782. },
  107783. /**
  107784. * Gets or sets a boolean which defines if optimization octree has to be updated
  107785. */
  107786. set: function (value) {
  107787. MergeMeshesOptimization._UpdateSelectionTree = value;
  107788. },
  107789. enumerable: true,
  107790. configurable: true
  107791. });
  107792. /**
  107793. * Gets a string describing the action executed by the current optimization
  107794. * @return description string
  107795. */
  107796. MergeMeshesOptimization.prototype.getDescription = function () {
  107797. return "Merging similar meshes together";
  107798. };
  107799. /**
  107800. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107801. * @param scene defines the current scene where to apply this optimization
  107802. * @param optimizer defines the current optimizer
  107803. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  107804. * @returns true if everything that can be done was applied
  107805. */
  107806. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  107807. var globalPool = scene.meshes.slice(0);
  107808. var globalLength = globalPool.length;
  107809. for (var index = 0; index < globalLength; index++) {
  107810. var currentPool = new Array();
  107811. var current = globalPool[index];
  107812. // Checks
  107813. if (!this._canBeMerged(current)) {
  107814. continue;
  107815. }
  107816. currentPool.push(current);
  107817. // Find compatible meshes
  107818. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  107819. var otherMesh = globalPool[subIndex];
  107820. if (!this._canBeMerged(otherMesh)) {
  107821. continue;
  107822. }
  107823. if (otherMesh.material !== current.material) {
  107824. continue;
  107825. }
  107826. if (otherMesh.checkCollisions !== current.checkCollisions) {
  107827. continue;
  107828. }
  107829. currentPool.push(otherMesh);
  107830. globalLength--;
  107831. globalPool.splice(subIndex, 1);
  107832. subIndex--;
  107833. }
  107834. if (currentPool.length < 2) {
  107835. continue;
  107836. }
  107837. // Merge meshes
  107838. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  107839. }
  107840. // Call the octree system optimization if it is defined.
  107841. var sceneAsAny = scene;
  107842. if (sceneAsAny.createOrUpdateSelectionOctree) {
  107843. if (updateSelectionTree != undefined) {
  107844. if (updateSelectionTree) {
  107845. sceneAsAny.createOrUpdateSelectionOctree();
  107846. }
  107847. }
  107848. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  107849. sceneAsAny.createOrUpdateSelectionOctree();
  107850. }
  107851. }
  107852. return true;
  107853. };
  107854. MergeMeshesOptimization._UpdateSelectionTree = false;
  107855. return MergeMeshesOptimization;
  107856. }(SceneOptimization));
  107857. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  107858. /**
  107859. * Defines a list of options used by SceneOptimizer
  107860. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107861. */
  107862. var SceneOptimizerOptions = /** @class */ (function () {
  107863. /**
  107864. * Creates a new list of options used by SceneOptimizer
  107865. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  107866. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  107867. */
  107868. function SceneOptimizerOptions(
  107869. /**
  107870. * Defines the target frame rate to reach (60 by default)
  107871. */
  107872. targetFrameRate,
  107873. /**
  107874. * Defines the interval between two checkes (2000ms by default)
  107875. */
  107876. trackerDuration) {
  107877. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  107878. if (trackerDuration === void 0) { trackerDuration = 2000; }
  107879. this.targetFrameRate = targetFrameRate;
  107880. this.trackerDuration = trackerDuration;
  107881. /**
  107882. * Gets the list of optimizations to apply
  107883. */
  107884. this.optimizations = new Array();
  107885. }
  107886. /**
  107887. * Add a new optimization
  107888. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  107889. * @returns the current SceneOptimizerOptions
  107890. */
  107891. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  107892. this.optimizations.push(optimization);
  107893. return this;
  107894. };
  107895. /**
  107896. * Add a new custom optimization
  107897. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  107898. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  107899. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107900. * @returns the current SceneOptimizerOptions
  107901. */
  107902. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  107903. if (priority === void 0) { priority = 0; }
  107904. var optimization = new CustomOptimization(priority);
  107905. optimization.onApply = onApply;
  107906. optimization.onGetDescription = onGetDescription;
  107907. this.optimizations.push(optimization);
  107908. return this;
  107909. };
  107910. /**
  107911. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  107912. * @param targetFrameRate defines the target frame rate (60 by default)
  107913. * @returns a SceneOptimizerOptions object
  107914. */
  107915. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  107916. var result = new SceneOptimizerOptions(targetFrameRate);
  107917. var priority = 0;
  107918. result.addOptimization(new MergeMeshesOptimization(priority));
  107919. result.addOptimization(new ShadowsOptimization(priority));
  107920. result.addOptimization(new LensFlaresOptimization(priority));
  107921. // Next priority
  107922. priority++;
  107923. result.addOptimization(new PostProcessesOptimization(priority));
  107924. result.addOptimization(new ParticlesOptimization(priority));
  107925. // Next priority
  107926. priority++;
  107927. result.addOptimization(new TextureOptimization(priority, 1024));
  107928. return result;
  107929. };
  107930. /**
  107931. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  107932. * @param targetFrameRate defines the target frame rate (60 by default)
  107933. * @returns a SceneOptimizerOptions object
  107934. */
  107935. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  107936. var result = new SceneOptimizerOptions(targetFrameRate);
  107937. var priority = 0;
  107938. result.addOptimization(new MergeMeshesOptimization(priority));
  107939. result.addOptimization(new ShadowsOptimization(priority));
  107940. result.addOptimization(new LensFlaresOptimization(priority));
  107941. // Next priority
  107942. priority++;
  107943. result.addOptimization(new PostProcessesOptimization(priority));
  107944. result.addOptimization(new ParticlesOptimization(priority));
  107945. // Next priority
  107946. priority++;
  107947. result.addOptimization(new TextureOptimization(priority, 512));
  107948. // Next priority
  107949. priority++;
  107950. result.addOptimization(new RenderTargetsOptimization(priority));
  107951. // Next priority
  107952. priority++;
  107953. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  107954. return result;
  107955. };
  107956. /**
  107957. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  107958. * @param targetFrameRate defines the target frame rate (60 by default)
  107959. * @returns a SceneOptimizerOptions object
  107960. */
  107961. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  107962. var result = new SceneOptimizerOptions(targetFrameRate);
  107963. var priority = 0;
  107964. result.addOptimization(new MergeMeshesOptimization(priority));
  107965. result.addOptimization(new ShadowsOptimization(priority));
  107966. result.addOptimization(new LensFlaresOptimization(priority));
  107967. // Next priority
  107968. priority++;
  107969. result.addOptimization(new PostProcessesOptimization(priority));
  107970. result.addOptimization(new ParticlesOptimization(priority));
  107971. // Next priority
  107972. priority++;
  107973. result.addOptimization(new TextureOptimization(priority, 256));
  107974. // Next priority
  107975. priority++;
  107976. result.addOptimization(new RenderTargetsOptimization(priority));
  107977. // Next priority
  107978. priority++;
  107979. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  107980. return result;
  107981. };
  107982. return SceneOptimizerOptions;
  107983. }());
  107984. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  107985. /**
  107986. * Class used to run optimizations in order to reach a target frame rate
  107987. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107988. */
  107989. var SceneOptimizer = /** @class */ (function () {
  107990. /**
  107991. * Creates a new SceneOptimizer
  107992. * @param scene defines the scene to work on
  107993. * @param options defines the options to use with the SceneOptimizer
  107994. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  107995. * @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)
  107996. */
  107997. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  107998. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  107999. if (improvementMode === void 0) { improvementMode = false; }
  108000. var _this = this;
  108001. this._isRunning = false;
  108002. this._currentPriorityLevel = 0;
  108003. this._targetFrameRate = 60;
  108004. this._trackerDuration = 2000;
  108005. this._currentFrameRate = 0;
  108006. this._improvementMode = false;
  108007. /**
  108008. * Defines an observable called when the optimizer reaches the target frame rate
  108009. */
  108010. this.onSuccessObservable = new BABYLON.Observable();
  108011. /**
  108012. * Defines an observable called when the optimizer enables an optimization
  108013. */
  108014. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  108015. /**
  108016. * Defines an observable called when the optimizer is not able to reach the target frame rate
  108017. */
  108018. this.onFailureObservable = new BABYLON.Observable();
  108019. if (!options) {
  108020. this._options = new SceneOptimizerOptions();
  108021. }
  108022. else {
  108023. this._options = options;
  108024. }
  108025. if (this._options.targetFrameRate) {
  108026. this._targetFrameRate = this._options.targetFrameRate;
  108027. }
  108028. if (this._options.trackerDuration) {
  108029. this._trackerDuration = this._options.trackerDuration;
  108030. }
  108031. if (autoGeneratePriorities) {
  108032. var priority = 0;
  108033. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  108034. var optim = _a[_i];
  108035. optim.priority = priority++;
  108036. }
  108037. }
  108038. this._improvementMode = improvementMode;
  108039. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  108040. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  108041. _this._sceneDisposeObserver = null;
  108042. _this.dispose();
  108043. });
  108044. }
  108045. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  108046. /**
  108047. * Gets a boolean indicating if the optimizer is in improvement mode
  108048. */
  108049. get: function () {
  108050. return this._improvementMode;
  108051. },
  108052. enumerable: true,
  108053. configurable: true
  108054. });
  108055. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  108056. /**
  108057. * Gets the current priority level (0 at start)
  108058. */
  108059. get: function () {
  108060. return this._currentPriorityLevel;
  108061. },
  108062. enumerable: true,
  108063. configurable: true
  108064. });
  108065. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  108066. /**
  108067. * Gets the current frame rate checked by the SceneOptimizer
  108068. */
  108069. get: function () {
  108070. return this._currentFrameRate;
  108071. },
  108072. enumerable: true,
  108073. configurable: true
  108074. });
  108075. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  108076. /**
  108077. * Gets or sets the current target frame rate (60 by default)
  108078. */
  108079. get: function () {
  108080. return this._targetFrameRate;
  108081. },
  108082. /**
  108083. * Gets or sets the current target frame rate (60 by default)
  108084. */
  108085. set: function (value) {
  108086. this._targetFrameRate = value;
  108087. },
  108088. enumerable: true,
  108089. configurable: true
  108090. });
  108091. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  108092. /**
  108093. * Gets or sets the current interval between two checks (every 2000ms by default)
  108094. */
  108095. get: function () {
  108096. return this._trackerDuration;
  108097. },
  108098. /**
  108099. * Gets or sets the current interval between two checks (every 2000ms by default)
  108100. */
  108101. set: function (value) {
  108102. this._trackerDuration = value;
  108103. },
  108104. enumerable: true,
  108105. configurable: true
  108106. });
  108107. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  108108. /**
  108109. * Gets the list of active optimizations
  108110. */
  108111. get: function () {
  108112. return this._options.optimizations;
  108113. },
  108114. enumerable: true,
  108115. configurable: true
  108116. });
  108117. /**
  108118. * Stops the current optimizer
  108119. */
  108120. SceneOptimizer.prototype.stop = function () {
  108121. this._isRunning = false;
  108122. };
  108123. /**
  108124. * Reset the optimizer to initial step (current priority level = 0)
  108125. */
  108126. SceneOptimizer.prototype.reset = function () {
  108127. this._currentPriorityLevel = 0;
  108128. };
  108129. /**
  108130. * Start the optimizer. By default it will try to reach a specific framerate
  108131. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  108132. */
  108133. SceneOptimizer.prototype.start = function () {
  108134. var _this = this;
  108135. if (this._isRunning) {
  108136. return;
  108137. }
  108138. this._isRunning = true;
  108139. // Let's wait for the scene to be ready before running our check
  108140. this._scene.executeWhenReady(function () {
  108141. setTimeout(function () {
  108142. _this._checkCurrentState();
  108143. }, _this._trackerDuration);
  108144. });
  108145. };
  108146. SceneOptimizer.prototype._checkCurrentState = function () {
  108147. var _this = this;
  108148. if (!this._isRunning) {
  108149. return;
  108150. }
  108151. var scene = this._scene;
  108152. var options = this._options;
  108153. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  108154. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  108155. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  108156. this._isRunning = false;
  108157. this.onSuccessObservable.notifyObservers(this);
  108158. return;
  108159. }
  108160. // Apply current level of optimizations
  108161. var allDone = true;
  108162. var noOptimizationApplied = true;
  108163. for (var index = 0; index < options.optimizations.length; index++) {
  108164. var optimization = options.optimizations[index];
  108165. if (optimization.priority === this._currentPriorityLevel) {
  108166. noOptimizationApplied = false;
  108167. allDone = allDone && optimization.apply(scene, this);
  108168. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  108169. }
  108170. }
  108171. // If no optimization was applied, this is a failure :(
  108172. if (noOptimizationApplied) {
  108173. this._isRunning = false;
  108174. this.onFailureObservable.notifyObservers(this);
  108175. return;
  108176. }
  108177. // If all optimizations were done, move to next level
  108178. if (allDone) {
  108179. this._currentPriorityLevel++;
  108180. }
  108181. // Let's the system running for a specific amount of time before checking FPS
  108182. scene.executeWhenReady(function () {
  108183. setTimeout(function () {
  108184. _this._checkCurrentState();
  108185. }, _this._trackerDuration);
  108186. });
  108187. };
  108188. /**
  108189. * Release all resources
  108190. */
  108191. SceneOptimizer.prototype.dispose = function () {
  108192. this.stop();
  108193. this.onSuccessObservable.clear();
  108194. this.onFailureObservable.clear();
  108195. this.onNewOptimizationAppliedObservable.clear();
  108196. if (this._sceneDisposeObserver) {
  108197. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  108198. }
  108199. };
  108200. /**
  108201. * Helper function to create a SceneOptimizer with one single line of code
  108202. * @param scene defines the scene to work on
  108203. * @param options defines the options to use with the SceneOptimizer
  108204. * @param onSuccess defines a callback to call on success
  108205. * @param onFailure defines a callback to call on failure
  108206. * @returns the new SceneOptimizer object
  108207. */
  108208. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  108209. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  108210. if (onSuccess) {
  108211. optimizer.onSuccessObservable.add(function () {
  108212. onSuccess();
  108213. });
  108214. }
  108215. if (onFailure) {
  108216. optimizer.onFailureObservable.add(function () {
  108217. onFailure();
  108218. });
  108219. }
  108220. optimizer.start();
  108221. return optimizer;
  108222. };
  108223. return SceneOptimizer;
  108224. }());
  108225. BABYLON.SceneOptimizer = SceneOptimizer;
  108226. })(BABYLON || (BABYLON = {}));
  108227. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  108228. var BABYLON;
  108229. (function (BABYLON) {
  108230. /**
  108231. * Gets the outline renderer associated with the scene
  108232. * @returns a OutlineRenderer
  108233. */
  108234. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  108235. if (!this._outlineRenderer) {
  108236. this._outlineRenderer = new OutlineRenderer(this);
  108237. }
  108238. return this._outlineRenderer;
  108239. };
  108240. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  108241. get: function () {
  108242. return this._renderOutline;
  108243. },
  108244. set: function (value) {
  108245. if (value) {
  108246. // Lazy Load the component.
  108247. this.getScene().getOutlineRenderer();
  108248. }
  108249. this._renderOutline = value;
  108250. },
  108251. enumerable: true,
  108252. configurable: true
  108253. });
  108254. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  108255. get: function () {
  108256. return this._renderOverlay;
  108257. },
  108258. set: function (value) {
  108259. if (value) {
  108260. // Lazy Load the component.
  108261. this.getScene().getOutlineRenderer();
  108262. }
  108263. this._renderOverlay = value;
  108264. },
  108265. enumerable: true,
  108266. configurable: true
  108267. });
  108268. /**
  108269. * This class is responsible to draw bothe outline/overlay of meshes.
  108270. * It should not be used directly but through the available method on mesh.
  108271. */
  108272. var OutlineRenderer = /** @class */ (function () {
  108273. /**
  108274. * Instantiates a new outline renderer. (There could be only one per scene).
  108275. * @param scene Defines the scene it belongs to
  108276. */
  108277. function OutlineRenderer(scene) {
  108278. /**
  108279. * The name of the component. Each component must have a unique name.
  108280. */
  108281. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  108282. /**
  108283. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  108284. */
  108285. this.zOffset = 1;
  108286. this.scene = scene;
  108287. this._engine = scene.getEngine();
  108288. this.scene._addComponent(this);
  108289. }
  108290. /**
  108291. * Register the component to one instance of a scene.
  108292. */
  108293. OutlineRenderer.prototype.register = function () {
  108294. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  108295. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  108296. };
  108297. /**
  108298. * Rebuilds the elements related to this component in case of
  108299. * context lost for instance.
  108300. */
  108301. OutlineRenderer.prototype.rebuild = function () {
  108302. // Nothing to do here.
  108303. };
  108304. /**
  108305. * Disposes the component and the associated ressources.
  108306. */
  108307. OutlineRenderer.prototype.dispose = function () {
  108308. // Nothing to do here.
  108309. };
  108310. /**
  108311. * Renders the outline in the canvas.
  108312. * @param subMesh Defines the sumesh to render
  108313. * @param batch Defines the batch of meshes in case of instances
  108314. * @param useOverlay Defines if the rendering is for the overlay or the outline
  108315. */
  108316. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  108317. var _this = this;
  108318. if (useOverlay === void 0) { useOverlay = false; }
  108319. var scene = this.scene;
  108320. var engine = scene.getEngine();
  108321. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  108322. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  108323. return;
  108324. }
  108325. var mesh = subMesh.getRenderingMesh();
  108326. var material = subMesh.getMaterial();
  108327. if (!material || !scene.activeCamera) {
  108328. return;
  108329. }
  108330. engine.enableEffect(this._effect);
  108331. // Logarithmic depth
  108332. if (material.useLogarithmicDepth) {
  108333. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  108334. }
  108335. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  108336. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  108337. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  108338. // Bones
  108339. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  108340. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  108341. }
  108342. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  108343. // Alpha test
  108344. if (material && material.needAlphaTesting()) {
  108345. var alphaTexture = material.getAlphaTestTexture();
  108346. if (alphaTexture) {
  108347. this._effect.setTexture("diffuseSampler", alphaTexture);
  108348. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  108349. }
  108350. }
  108351. engine.setZOffset(-this.zOffset);
  108352. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  108353. engine.setZOffset(0);
  108354. };
  108355. /**
  108356. * Returns whether or not the outline renderer is ready for a given submesh.
  108357. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  108358. * @param subMesh Defines the submesh to check readyness for
  108359. * @param useInstances Defines wheter wee are trying to render instances or not
  108360. * @returns true if ready otherwise false
  108361. */
  108362. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  108363. var defines = [];
  108364. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  108365. var mesh = subMesh.getMesh();
  108366. var material = subMesh.getMaterial();
  108367. if (material) {
  108368. // Alpha test
  108369. if (material.needAlphaTesting()) {
  108370. defines.push("#define ALPHATEST");
  108371. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  108372. attribs.push(BABYLON.VertexBuffer.UVKind);
  108373. defines.push("#define UV1");
  108374. }
  108375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  108376. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108377. defines.push("#define UV2");
  108378. }
  108379. }
  108380. //Logarithmic depth
  108381. if (material.useLogarithmicDepth) {
  108382. defines.push("#define LOGARITHMICDEPTH");
  108383. }
  108384. }
  108385. // Bones
  108386. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  108387. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  108388. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  108389. if (mesh.numBoneInfluencers > 4) {
  108390. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  108391. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  108392. }
  108393. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  108394. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  108395. }
  108396. else {
  108397. defines.push("#define NUM_BONE_INFLUENCERS 0");
  108398. }
  108399. // Instances
  108400. if (useInstances) {
  108401. defines.push("#define INSTANCES");
  108402. attribs.push("world0");
  108403. attribs.push("world1");
  108404. attribs.push("world2");
  108405. attribs.push("world3");
  108406. }
  108407. // Get correct effect
  108408. var join = defines.join("\n");
  108409. if (this._cachedDefines !== join) {
  108410. this._cachedDefines = join;
  108411. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  108412. }
  108413. return this._effect.isReady();
  108414. };
  108415. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  108416. // Outline - step 1
  108417. this._savedDepthWrite = this._engine.getDepthWrite();
  108418. if (mesh.renderOutline) {
  108419. this._engine.setDepthWrite(false);
  108420. this.render(subMesh, batch);
  108421. this._engine.setDepthWrite(this._savedDepthWrite);
  108422. }
  108423. };
  108424. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  108425. // Outline - step 2
  108426. if (mesh.renderOutline && this._savedDepthWrite) {
  108427. this._engine.setDepthWrite(true);
  108428. this._engine.setColorWrite(false);
  108429. this.render(subMesh, batch);
  108430. this._engine.setColorWrite(true);
  108431. }
  108432. // Overlay
  108433. if (mesh.renderOverlay) {
  108434. var currentMode = this._engine.getAlphaMode();
  108435. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108436. this.render(subMesh, batch, true);
  108437. this._engine.setAlphaMode(currentMode);
  108438. }
  108439. };
  108440. return OutlineRenderer;
  108441. }());
  108442. BABYLON.OutlineRenderer = OutlineRenderer;
  108443. })(BABYLON || (BABYLON = {}));
  108444. //# sourceMappingURL=babylon.outlineRenderer.js.map
  108445. var BABYLON;
  108446. (function (BABYLON) {
  108447. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  108448. if (this._edgesRenderer) {
  108449. this._edgesRenderer.dispose();
  108450. this._edgesRenderer = null;
  108451. }
  108452. return this;
  108453. };
  108454. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108455. if (epsilon === void 0) { epsilon = 0.95; }
  108456. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108457. this.disableEdgesRendering();
  108458. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108459. return this;
  108460. };
  108461. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  108462. get: function () {
  108463. return this._edgesRenderer;
  108464. },
  108465. enumerable: true,
  108466. configurable: true
  108467. });
  108468. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108469. if (epsilon === void 0) { epsilon = 0.95; }
  108470. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108471. this.disableEdgesRendering();
  108472. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108473. return this;
  108474. };
  108475. /**
  108476. * FaceAdjacencies Helper class to generate edges
  108477. */
  108478. var FaceAdjacencies = /** @class */ (function () {
  108479. function FaceAdjacencies() {
  108480. this.edges = new Array();
  108481. this.edgesConnectedCount = 0;
  108482. }
  108483. return FaceAdjacencies;
  108484. }());
  108485. /**
  108486. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  108487. */
  108488. var EdgesRenderer = /** @class */ (function () {
  108489. /**
  108490. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  108491. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  108492. * @param source Mesh used to create edges
  108493. * @param epsilon sum of angles in adjacency to check for edge
  108494. * @param checkVerticesInsteadOfIndices
  108495. * @param generateEdgesLines - should generate Lines or only prepare resources.
  108496. */
  108497. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  108498. if (epsilon === void 0) { epsilon = 0.95; }
  108499. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108500. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  108501. var _this = this;
  108502. /**
  108503. * Define the size of the edges with an orthographic camera
  108504. */
  108505. this.edgesWidthScalerForOrthographic = 1000.0;
  108506. /**
  108507. * Define the size of the edges with a perspective camera
  108508. */
  108509. this.edgesWidthScalerForPerspective = 50.0;
  108510. this._linesPositions = new Array();
  108511. this._linesNormals = new Array();
  108512. this._linesIndices = new Array();
  108513. this._buffers = {};
  108514. this._checkVerticesInsteadOfIndices = false;
  108515. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  108516. this.isEnabled = true;
  108517. this._source = source;
  108518. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  108519. this._epsilon = epsilon;
  108520. this._prepareRessources();
  108521. if (generateEdgesLines) {
  108522. this._generateEdgesLines();
  108523. }
  108524. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  108525. _this._rebuild();
  108526. });
  108527. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  108528. _this.dispose();
  108529. });
  108530. }
  108531. EdgesRenderer.prototype._prepareRessources = function () {
  108532. if (this._lineShader) {
  108533. return;
  108534. }
  108535. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  108536. attributes: ["position", "normal"],
  108537. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  108538. });
  108539. this._lineShader.disableDepthWrite = true;
  108540. this._lineShader.backFaceCulling = false;
  108541. };
  108542. /** @hidden */
  108543. EdgesRenderer.prototype._rebuild = function () {
  108544. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108545. if (buffer) {
  108546. buffer._rebuild();
  108547. }
  108548. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108549. if (buffer) {
  108550. buffer._rebuild();
  108551. }
  108552. var scene = this._source.getScene();
  108553. var engine = scene.getEngine();
  108554. this._ib = engine.createIndexBuffer(this._linesIndices);
  108555. };
  108556. /**
  108557. * Releases the required resources for the edges renderer
  108558. */
  108559. EdgesRenderer.prototype.dispose = function () {
  108560. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  108561. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  108562. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108563. if (buffer) {
  108564. buffer.dispose();
  108565. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  108566. }
  108567. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108568. if (buffer) {
  108569. buffer.dispose();
  108570. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  108571. }
  108572. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  108573. this._lineShader.dispose();
  108574. };
  108575. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  108576. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  108577. return 0;
  108578. }
  108579. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  108580. return 1;
  108581. }
  108582. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  108583. return 2;
  108584. }
  108585. return -1;
  108586. };
  108587. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  108588. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  108589. return 0;
  108590. }
  108591. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  108592. return 1;
  108593. }
  108594. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  108595. return 2;
  108596. }
  108597. return -1;
  108598. };
  108599. /**
  108600. * Checks if the pair of p0 and p1 is en edge
  108601. * @param faceIndex
  108602. * @param edge
  108603. * @param faceNormals
  108604. * @param p0
  108605. * @param p1
  108606. * @private
  108607. */
  108608. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108609. var needToCreateLine;
  108610. if (edge === undefined) {
  108611. needToCreateLine = true;
  108612. }
  108613. else {
  108614. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  108615. needToCreateLine = dotProduct < this._epsilon;
  108616. }
  108617. if (needToCreateLine) {
  108618. var offset = this._linesPositions.length / 3;
  108619. var normal = p0.subtract(p1);
  108620. normal.normalize();
  108621. // Positions
  108622. this._linesPositions.push(p0.x);
  108623. this._linesPositions.push(p0.y);
  108624. this._linesPositions.push(p0.z);
  108625. this._linesPositions.push(p0.x);
  108626. this._linesPositions.push(p0.y);
  108627. this._linesPositions.push(p0.z);
  108628. this._linesPositions.push(p1.x);
  108629. this._linesPositions.push(p1.y);
  108630. this._linesPositions.push(p1.z);
  108631. this._linesPositions.push(p1.x);
  108632. this._linesPositions.push(p1.y);
  108633. this._linesPositions.push(p1.z);
  108634. // Normals
  108635. this._linesNormals.push(p1.x);
  108636. this._linesNormals.push(p1.y);
  108637. this._linesNormals.push(p1.z);
  108638. this._linesNormals.push(-1);
  108639. this._linesNormals.push(p1.x);
  108640. this._linesNormals.push(p1.y);
  108641. this._linesNormals.push(p1.z);
  108642. this._linesNormals.push(1);
  108643. this._linesNormals.push(p0.x);
  108644. this._linesNormals.push(p0.y);
  108645. this._linesNormals.push(p0.z);
  108646. this._linesNormals.push(-1);
  108647. this._linesNormals.push(p0.x);
  108648. this._linesNormals.push(p0.y);
  108649. this._linesNormals.push(p0.z);
  108650. this._linesNormals.push(1);
  108651. // Indices
  108652. this._linesIndices.push(offset);
  108653. this._linesIndices.push(offset + 1);
  108654. this._linesIndices.push(offset + 2);
  108655. this._linesIndices.push(offset);
  108656. this._linesIndices.push(offset + 2);
  108657. this._linesIndices.push(offset + 3);
  108658. }
  108659. };
  108660. /**
  108661. * Generates lines edges from adjacencjes
  108662. * @private
  108663. */
  108664. EdgesRenderer.prototype._generateEdgesLines = function () {
  108665. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108666. var indices = this._source.getIndices();
  108667. if (!indices || !positions) {
  108668. return;
  108669. }
  108670. // First let's find adjacencies
  108671. var adjacencies = new Array();
  108672. var faceNormals = new Array();
  108673. var index;
  108674. var faceAdjacencies;
  108675. // Prepare faces
  108676. for (index = 0; index < indices.length; index += 3) {
  108677. faceAdjacencies = new FaceAdjacencies();
  108678. var p0Index = indices[index];
  108679. var p1Index = indices[index + 1];
  108680. var p2Index = indices[index + 2];
  108681. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  108682. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  108683. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  108684. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  108685. faceNormal.normalize();
  108686. faceNormals.push(faceNormal);
  108687. adjacencies.push(faceAdjacencies);
  108688. }
  108689. // Scan
  108690. for (index = 0; index < adjacencies.length; index++) {
  108691. faceAdjacencies = adjacencies[index];
  108692. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  108693. var otherFaceAdjacencies = adjacencies[otherIndex];
  108694. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  108695. break;
  108696. }
  108697. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  108698. continue;
  108699. }
  108700. var otherP0 = indices[otherIndex * 3];
  108701. var otherP1 = indices[otherIndex * 3 + 1];
  108702. var otherP2 = indices[otherIndex * 3 + 2];
  108703. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  108704. var otherEdgeIndex = 0;
  108705. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  108706. continue;
  108707. }
  108708. switch (edgeIndex) {
  108709. case 0:
  108710. if (this._checkVerticesInsteadOfIndices) {
  108711. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108712. }
  108713. else {
  108714. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  108715. }
  108716. break;
  108717. case 1:
  108718. if (this._checkVerticesInsteadOfIndices) {
  108719. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108720. }
  108721. else {
  108722. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  108723. }
  108724. break;
  108725. case 2:
  108726. if (this._checkVerticesInsteadOfIndices) {
  108727. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108728. }
  108729. else {
  108730. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  108731. }
  108732. break;
  108733. }
  108734. if (otherEdgeIndex === -1) {
  108735. continue;
  108736. }
  108737. faceAdjacencies.edges[edgeIndex] = otherIndex;
  108738. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  108739. faceAdjacencies.edgesConnectedCount++;
  108740. otherFaceAdjacencies.edgesConnectedCount++;
  108741. if (faceAdjacencies.edgesConnectedCount === 3) {
  108742. break;
  108743. }
  108744. }
  108745. }
  108746. }
  108747. // Create lines
  108748. for (index = 0; index < adjacencies.length; index++) {
  108749. // 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
  108750. var current = adjacencies[index];
  108751. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108752. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  108753. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  108754. }
  108755. // Merge into a single mesh
  108756. var engine = this._source.getScene().getEngine();
  108757. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108758. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108759. this._ib = engine.createIndexBuffer(this._linesIndices);
  108760. this._indicesCount = this._linesIndices.length;
  108761. };
  108762. /**
  108763. * Checks wether or not the edges renderer is ready to render.
  108764. * @return true if ready, otherwise false.
  108765. */
  108766. EdgesRenderer.prototype.isReady = function () {
  108767. return this._lineShader.isReady();
  108768. };
  108769. /**
  108770. * Renders the edges of the attached mesh,
  108771. */
  108772. EdgesRenderer.prototype.render = function () {
  108773. var scene = this._source.getScene();
  108774. if (!this.isReady() || !scene.activeCamera) {
  108775. return;
  108776. }
  108777. var engine = scene.getEngine();
  108778. this._lineShader._preBind();
  108779. if (this._source.edgesColor.a !== 1) {
  108780. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108781. }
  108782. else {
  108783. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108784. }
  108785. // VBOs
  108786. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  108787. scene.resetCachedMaterial();
  108788. this._lineShader.setColor4("color", this._source.edgesColor);
  108789. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  108790. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  108791. }
  108792. else {
  108793. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  108794. }
  108795. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  108796. this._lineShader.bind(this._source.getWorldMatrix());
  108797. // Draw order
  108798. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  108799. this._lineShader.unbind();
  108800. };
  108801. return EdgesRenderer;
  108802. }());
  108803. BABYLON.EdgesRenderer = EdgesRenderer;
  108804. })(BABYLON || (BABYLON = {}));
  108805. //# sourceMappingURL=babylon.edgesRenderer.js.map
  108806. var BABYLON;
  108807. (function (BABYLON) {
  108808. /**
  108809. * FaceAdjacencies Helper class to generate edges
  108810. */
  108811. var FaceAdjacencies = /** @class */ (function () {
  108812. function FaceAdjacencies() {
  108813. this.edges = new Array();
  108814. this.edgesConnectedCount = 0;
  108815. }
  108816. return FaceAdjacencies;
  108817. }());
  108818. /**
  108819. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  108820. */
  108821. var LineEdgesRenderer = /** @class */ (function (_super) {
  108822. __extends(LineEdgesRenderer, _super);
  108823. /**
  108824. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  108825. * @param source LineMesh used to generate edges
  108826. * @param epsilon not important (specified angle for edge detection)
  108827. * @param checkVerticesInsteadOfIndices not important for LineMesh
  108828. */
  108829. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  108830. if (epsilon === void 0) { epsilon = 0.95; }
  108831. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108832. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  108833. _this._generateEdgesLines();
  108834. return _this;
  108835. }
  108836. /**
  108837. * Always create the edge since its a line so only important things are p0 and p1
  108838. * @param faceIndex not important for LineMesh
  108839. * @param edge not important for LineMesh
  108840. * @param faceNormals not important for LineMesh
  108841. * @param p0 beginnig of line
  108842. * @param p1 end of line
  108843. */
  108844. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108845. var offset = this._linesPositions.length / 3;
  108846. var normal = p0.subtract(p1);
  108847. normal.normalize();
  108848. // Positions
  108849. this._linesPositions.push(p0.x);
  108850. this._linesPositions.push(p0.y);
  108851. this._linesPositions.push(p0.z);
  108852. this._linesPositions.push(p0.x);
  108853. this._linesPositions.push(p0.y);
  108854. this._linesPositions.push(p0.z);
  108855. this._linesPositions.push(p1.x);
  108856. this._linesPositions.push(p1.y);
  108857. this._linesPositions.push(p1.z);
  108858. this._linesPositions.push(p1.x);
  108859. this._linesPositions.push(p1.y);
  108860. this._linesPositions.push(p1.z);
  108861. // Normals
  108862. this._linesNormals.push(p1.x);
  108863. this._linesNormals.push(p1.y);
  108864. this._linesNormals.push(p1.z);
  108865. this._linesNormals.push(-1);
  108866. this._linesNormals.push(p1.x);
  108867. this._linesNormals.push(p1.y);
  108868. this._linesNormals.push(p1.z);
  108869. this._linesNormals.push(1);
  108870. this._linesNormals.push(p0.x);
  108871. this._linesNormals.push(p0.y);
  108872. this._linesNormals.push(p0.z);
  108873. this._linesNormals.push(-1);
  108874. this._linesNormals.push(p0.x);
  108875. this._linesNormals.push(p0.y);
  108876. this._linesNormals.push(p0.z);
  108877. this._linesNormals.push(1);
  108878. // Indices
  108879. this._linesIndices.push(offset);
  108880. this._linesIndices.push(offset + 1);
  108881. this._linesIndices.push(offset + 2);
  108882. this._linesIndices.push(offset);
  108883. this._linesIndices.push(offset + 2);
  108884. this._linesIndices.push(offset + 3);
  108885. };
  108886. /**
  108887. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  108888. */
  108889. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  108890. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108891. var indices = this._source.getIndices();
  108892. if (!indices || !positions) {
  108893. return;
  108894. }
  108895. // First let's find adjacencies
  108896. var adjacencies = new Array();
  108897. var faceNormals = new Array();
  108898. var index;
  108899. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  108900. var currentAdjecancy = new FaceAdjacencies();
  108901. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  108902. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  108903. adjacencies.push(currentAdjecancy);
  108904. }
  108905. // Create lines
  108906. for (index = 0; index < adjacencies.length; index++) {
  108907. // 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
  108908. var current = adjacencies[index];
  108909. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108910. }
  108911. // Merge into a single mesh
  108912. var engine = this._source.getScene().getEngine();
  108913. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108914. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108915. this._ib = engine.createIndexBuffer(this._linesIndices);
  108916. this._indicesCount = this._linesIndices.length;
  108917. };
  108918. return LineEdgesRenderer;
  108919. }(BABYLON.EdgesRenderer));
  108920. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  108921. })(BABYLON || (BABYLON = {}));
  108922. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  108923. var BABYLON;
  108924. (function (BABYLON) {
  108925. // Adds the parser to the scene parsers.
  108926. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  108927. if (parsedData.effectLayers) {
  108928. if (!container.effectLayers) {
  108929. container.effectLayers = new Array();
  108930. }
  108931. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  108932. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  108933. container.effectLayers.push(effectLayer);
  108934. }
  108935. }
  108936. });
  108937. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  108938. var index = this.effectLayers.indexOf(toRemove);
  108939. if (index !== -1) {
  108940. this.effectLayers.splice(index, 1);
  108941. }
  108942. return index;
  108943. };
  108944. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  108945. this.effectLayers.push(newEffectLayer);
  108946. };
  108947. /**
  108948. * Defines the layer scene component responsible to manage any effect layers
  108949. * in a given scene.
  108950. */
  108951. var EffectLayerSceneComponent = /** @class */ (function () {
  108952. /**
  108953. * Creates a new instance of the component for the given scene
  108954. * @param scene Defines the scene to register the component in
  108955. */
  108956. function EffectLayerSceneComponent(scene) {
  108957. /**
  108958. * The component name helpfull to identify the component in the list of scene components.
  108959. */
  108960. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  108961. this._renderEffects = false;
  108962. this._needStencil = false;
  108963. this._previousStencilState = false;
  108964. this.scene = scene;
  108965. this._engine = scene.getEngine();
  108966. scene.effectLayers = new Array();
  108967. }
  108968. /**
  108969. * Registers the component in a given scene
  108970. */
  108971. EffectLayerSceneComponent.prototype.register = function () {
  108972. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  108973. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  108974. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  108975. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  108976. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  108977. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  108978. };
  108979. /**
  108980. * Rebuilds the elements related to this component in case of
  108981. * context lost for instance.
  108982. */
  108983. EffectLayerSceneComponent.prototype.rebuild = function () {
  108984. var layers = this.scene.effectLayers;
  108985. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  108986. var effectLayer = layers_1[_i];
  108987. effectLayer._rebuild();
  108988. }
  108989. };
  108990. /**
  108991. * Serializes the component data to the specified json object
  108992. * @param serializationObject The object to serialize to
  108993. */
  108994. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  108995. // Effect layers
  108996. serializationObject.effectLayers = [];
  108997. var layers = this.scene.effectLayers;
  108998. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  108999. var effectLayer = layers_2[_i];
  109000. if (effectLayer.serialize) {
  109001. serializationObject.effectLayers.push(effectLayer.serialize());
  109002. }
  109003. }
  109004. };
  109005. /**
  109006. * Adds all the element from the container to the scene
  109007. * @param container the container holding the elements
  109008. */
  109009. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  109010. var _this = this;
  109011. if (!container.effectLayers) {
  109012. return;
  109013. }
  109014. container.effectLayers.forEach(function (o) {
  109015. _this.scene.addEffectLayer(o);
  109016. });
  109017. };
  109018. /**
  109019. * Removes all the elements in the container from the scene
  109020. * @param container contains the elements to remove
  109021. */
  109022. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  109023. var _this = this;
  109024. if (!container.effectLayers) {
  109025. return;
  109026. }
  109027. container.effectLayers.forEach(function (o) {
  109028. _this.scene.removeEffectLayer(o);
  109029. });
  109030. };
  109031. /**
  109032. * Disposes the component and the associated ressources.
  109033. */
  109034. EffectLayerSceneComponent.prototype.dispose = function () {
  109035. var layers = this.scene.effectLayers;
  109036. while (layers.length) {
  109037. layers[0].dispose();
  109038. }
  109039. };
  109040. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  109041. var layers = this.scene.effectLayers;
  109042. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  109043. var layer = layers_3[_i];
  109044. if (!layer.hasMesh(mesh)) {
  109045. continue;
  109046. }
  109047. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  109048. var subMesh = _b[_a];
  109049. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  109050. return false;
  109051. }
  109052. }
  109053. }
  109054. return true;
  109055. };
  109056. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  109057. this._renderEffects = false;
  109058. this._needStencil = false;
  109059. var layers = this.scene.effectLayers;
  109060. if (layers && layers.length > 0) {
  109061. this._previousStencilState = this._engine.getStencilBuffer();
  109062. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  109063. var effectLayer = layers_4[_i];
  109064. if (effectLayer.shouldRender() &&
  109065. (!effectLayer.camera ||
  109066. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  109067. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  109068. this._renderEffects = true;
  109069. this._needStencil = this._needStencil || effectLayer.needStencil();
  109070. var renderTarget = effectLayer._mainTexture;
  109071. if (renderTarget._shouldRender()) {
  109072. this.scene.incrementRenderId();
  109073. renderTarget.render(false, false);
  109074. }
  109075. }
  109076. }
  109077. this.scene.incrementRenderId();
  109078. }
  109079. };
  109080. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  109081. // Activate effect Layer stencil
  109082. if (this._needStencil) {
  109083. this._engine.setStencilBuffer(true);
  109084. }
  109085. };
  109086. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  109087. // Restore effect Layer stencil
  109088. if (this._needStencil) {
  109089. this._engine.setStencilBuffer(this._previousStencilState);
  109090. }
  109091. };
  109092. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  109093. if (this._renderEffects) {
  109094. this._engine.setDepthBuffer(false);
  109095. var layers = this.scene.effectLayers;
  109096. for (var i = 0; i < layers.length; i++) {
  109097. var effectLayer = layers[i];
  109098. if (effectLayer.renderingGroupId === renderingGroupId) {
  109099. if (effectLayer.shouldRender()) {
  109100. effectLayer.render();
  109101. }
  109102. }
  109103. }
  109104. this._engine.setDepthBuffer(true);
  109105. }
  109106. };
  109107. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  109108. if (this._renderEffects) {
  109109. this._draw(-1);
  109110. }
  109111. };
  109112. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  109113. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  109114. this._draw(index);
  109115. }
  109116. };
  109117. return EffectLayerSceneComponent;
  109118. }());
  109119. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  109120. })(BABYLON || (BABYLON = {}));
  109121. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  109122. var __assign = (this && this.__assign) || function () {
  109123. __assign = Object.assign || function(t) {
  109124. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109125. s = arguments[i];
  109126. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109127. t[p] = s[p];
  109128. }
  109129. return t;
  109130. };
  109131. return __assign.apply(this, arguments);
  109132. };
  109133. var BABYLON;
  109134. (function (BABYLON) {
  109135. /**
  109136. * The effect layer Helps adding post process effect blended with the main pass.
  109137. *
  109138. * This can be for instance use to generate glow or higlight effects on the scene.
  109139. *
  109140. * The effect layer class can not be used directly and is intented to inherited from to be
  109141. * customized per effects.
  109142. */
  109143. var EffectLayer = /** @class */ (function () {
  109144. /**
  109145. * Instantiates a new effect Layer and references it in the scene.
  109146. * @param name The name of the layer
  109147. * @param scene The scene to use the layer in
  109148. */
  109149. function EffectLayer(
  109150. /** The Friendly of the effect in the scene */
  109151. name, scene) {
  109152. this._vertexBuffers = {};
  109153. this._maxSize = 0;
  109154. this._mainTextureDesiredSize = { width: 0, height: 0 };
  109155. this._shouldRender = true;
  109156. this._postProcesses = [];
  109157. this._textures = [];
  109158. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  109159. /**
  109160. * The clear color of the texture used to generate the glow map.
  109161. */
  109162. this.neutralColor = new BABYLON.Color4();
  109163. /**
  109164. * Specifies wether the highlight layer is enabled or not.
  109165. */
  109166. this.isEnabled = true;
  109167. /**
  109168. * An event triggered when the effect layer has been disposed.
  109169. */
  109170. this.onDisposeObservable = new BABYLON.Observable();
  109171. /**
  109172. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  109173. */
  109174. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  109175. /**
  109176. * An event triggered when the generated texture is being merged in the scene.
  109177. */
  109178. this.onBeforeComposeObservable = new BABYLON.Observable();
  109179. /**
  109180. * An event triggered when the generated texture has been merged in the scene.
  109181. */
  109182. this.onAfterComposeObservable = new BABYLON.Observable();
  109183. /**
  109184. * An event triggered when the efffect layer changes its size.
  109185. */
  109186. this.onSizeChangedObservable = new BABYLON.Observable();
  109187. this.name = name;
  109188. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  109189. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  109190. if (!component) {
  109191. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  109192. this._scene._addComponent(component);
  109193. }
  109194. this._engine = this._scene.getEngine();
  109195. this._maxSize = this._engine.getCaps().maxTextureSize;
  109196. this._scene.effectLayers.push(this);
  109197. // Generate Buffers
  109198. this._generateIndexBuffer();
  109199. this._genrateVertexBuffer();
  109200. }
  109201. Object.defineProperty(EffectLayer.prototype, "camera", {
  109202. /**
  109203. * Gets the camera attached to the layer.
  109204. */
  109205. get: function () {
  109206. return this._effectLayerOptions.camera;
  109207. },
  109208. enumerable: true,
  109209. configurable: true
  109210. });
  109211. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  109212. /**
  109213. * Gets the rendering group id the layer should render in.
  109214. */
  109215. get: function () {
  109216. return this._effectLayerOptions.renderingGroupId;
  109217. },
  109218. enumerable: true,
  109219. configurable: true
  109220. });
  109221. /**
  109222. * Initializes the effect layer with the required options.
  109223. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  109224. */
  109225. EffectLayer.prototype._init = function (options) {
  109226. // Adapt options
  109227. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  109228. this._setMainTextureSize();
  109229. this._createMainTexture();
  109230. this._createTextureAndPostProcesses();
  109231. this._mergeEffect = this._createMergeEffect();
  109232. };
  109233. /**
  109234. * Generates the index buffer of the full screen quad blending to the main canvas.
  109235. */
  109236. EffectLayer.prototype._generateIndexBuffer = function () {
  109237. // Indices
  109238. var indices = [];
  109239. indices.push(0);
  109240. indices.push(1);
  109241. indices.push(2);
  109242. indices.push(0);
  109243. indices.push(2);
  109244. indices.push(3);
  109245. this._indexBuffer = this._engine.createIndexBuffer(indices);
  109246. };
  109247. /**
  109248. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  109249. */
  109250. EffectLayer.prototype._genrateVertexBuffer = function () {
  109251. // VBO
  109252. var vertices = [];
  109253. vertices.push(1, 1);
  109254. vertices.push(-1, 1);
  109255. vertices.push(-1, -1);
  109256. vertices.push(1, -1);
  109257. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  109258. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  109259. };
  109260. /**
  109261. * Sets the main texture desired size which is the closest power of two
  109262. * of the engine canvas size.
  109263. */
  109264. EffectLayer.prototype._setMainTextureSize = function () {
  109265. if (this._effectLayerOptions.mainTextureFixedSize) {
  109266. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  109267. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  109268. }
  109269. else {
  109270. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  109271. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  109272. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  109273. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  109274. }
  109275. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  109276. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  109277. };
  109278. /**
  109279. * Creates the main texture for the effect layer.
  109280. */
  109281. EffectLayer.prototype._createMainTexture = function () {
  109282. var _this = this;
  109283. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  109284. width: this._mainTextureDesiredSize.width,
  109285. height: this._mainTextureDesiredSize.height
  109286. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  109287. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  109288. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109289. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109290. this._mainTexture.anisotropicFilteringLevel = 1;
  109291. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  109292. this._mainTexture.renderParticles = false;
  109293. this._mainTexture.renderList = null;
  109294. this._mainTexture.ignoreCameraViewport = true;
  109295. // Custom render function
  109296. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  109297. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  109298. var index;
  109299. var engine = _this._scene.getEngine();
  109300. if (depthOnlySubMeshes.length) {
  109301. engine.setColorWrite(false);
  109302. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  109303. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  109304. }
  109305. engine.setColorWrite(true);
  109306. }
  109307. for (index = 0; index < opaqueSubMeshes.length; index++) {
  109308. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  109309. }
  109310. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  109311. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  109312. }
  109313. for (index = 0; index < transparentSubMeshes.length; index++) {
  109314. _this._renderSubMesh(transparentSubMeshes.data[index]);
  109315. }
  109316. };
  109317. this._mainTexture.onClearObservable.add(function (engine) {
  109318. engine.clear(_this.neutralColor, true, true, true);
  109319. });
  109320. };
  109321. /**
  109322. * Checks for the readiness of the element composing the layer.
  109323. * @param subMesh the mesh to check for
  109324. * @param useInstances specify wether or not to use instances to render the mesh
  109325. * @param emissiveTexture the associated emissive texture used to generate the glow
  109326. * @return true if ready otherwise, false
  109327. */
  109328. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  109329. var material = subMesh.getMaterial();
  109330. if (!material) {
  109331. return false;
  109332. }
  109333. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  109334. return false;
  109335. }
  109336. var defines = [];
  109337. var attribs = [BABYLON.VertexBuffer.PositionKind];
  109338. var mesh = subMesh.getMesh();
  109339. var uv1 = false;
  109340. var uv2 = false;
  109341. // Alpha test
  109342. if (material && material.needAlphaTesting()) {
  109343. var alphaTexture = material.getAlphaTestTexture();
  109344. if (alphaTexture) {
  109345. defines.push("#define ALPHATEST");
  109346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109347. alphaTexture.coordinatesIndex === 1) {
  109348. defines.push("#define DIFFUSEUV2");
  109349. uv2 = true;
  109350. }
  109351. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109352. defines.push("#define DIFFUSEUV1");
  109353. uv1 = true;
  109354. }
  109355. }
  109356. }
  109357. // Emissive
  109358. if (emissiveTexture) {
  109359. defines.push("#define EMISSIVE");
  109360. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109361. emissiveTexture.coordinatesIndex === 1) {
  109362. defines.push("#define EMISSIVEUV2");
  109363. uv2 = true;
  109364. }
  109365. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109366. defines.push("#define EMISSIVEUV1");
  109367. uv1 = true;
  109368. }
  109369. }
  109370. if (uv1) {
  109371. attribs.push(BABYLON.VertexBuffer.UVKind);
  109372. defines.push("#define UV1");
  109373. }
  109374. if (uv2) {
  109375. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109376. defines.push("#define UV2");
  109377. }
  109378. // Bones
  109379. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109380. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109381. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109382. if (mesh.numBoneInfluencers > 4) {
  109383. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109384. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109385. }
  109386. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109387. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  109388. }
  109389. else {
  109390. defines.push("#define NUM_BONE_INFLUENCERS 0");
  109391. }
  109392. // Morph targets
  109393. var manager = mesh.morphTargetManager;
  109394. var morphInfluencers = 0;
  109395. if (manager) {
  109396. if (manager.numInfluencers > 0) {
  109397. defines.push("#define MORPHTARGETS");
  109398. morphInfluencers = manager.numInfluencers;
  109399. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  109400. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  109401. }
  109402. }
  109403. // Instances
  109404. if (useInstances) {
  109405. defines.push("#define INSTANCES");
  109406. attribs.push("world0");
  109407. attribs.push("world1");
  109408. attribs.push("world2");
  109409. attribs.push("world3");
  109410. }
  109411. // Get correct effect
  109412. var join = defines.join("\n");
  109413. if (this._cachedDefines !== join) {
  109414. this._cachedDefines = join;
  109415. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  109416. }
  109417. return this._effectLayerMapGenerationEffect.isReady();
  109418. };
  109419. /**
  109420. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  109421. */
  109422. EffectLayer.prototype.render = function () {
  109423. var currentEffect = this._mergeEffect;
  109424. // Check
  109425. if (!currentEffect.isReady()) {
  109426. return;
  109427. }
  109428. for (var i = 0; i < this._postProcesses.length; i++) {
  109429. if (!this._postProcesses[i].isReady()) {
  109430. return;
  109431. }
  109432. }
  109433. var engine = this._scene.getEngine();
  109434. this.onBeforeComposeObservable.notifyObservers(this);
  109435. // Render
  109436. engine.enableEffect(currentEffect);
  109437. engine.setState(false);
  109438. // VBOs
  109439. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109440. // Cache
  109441. var previousAlphaMode = engine.getAlphaMode();
  109442. // Go Blend.
  109443. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  109444. // Blends the map on the main canvas.
  109445. this._internalRender(currentEffect);
  109446. // Restore Alpha
  109447. engine.setAlphaMode(previousAlphaMode);
  109448. this.onAfterComposeObservable.notifyObservers(this);
  109449. // Handle size changes.
  109450. var size = this._mainTexture.getSize();
  109451. this._setMainTextureSize();
  109452. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  109453. // Recreate RTT and post processes on size change.
  109454. this.onSizeChangedObservable.notifyObservers(this);
  109455. this._disposeTextureAndPostProcesses();
  109456. this._createMainTexture();
  109457. this._createTextureAndPostProcesses();
  109458. }
  109459. };
  109460. /**
  109461. * Determine if a given mesh will be used in the current effect.
  109462. * @param mesh mesh to test
  109463. * @returns true if the mesh will be used
  109464. */
  109465. EffectLayer.prototype.hasMesh = function (mesh) {
  109466. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  109467. return true;
  109468. }
  109469. return false;
  109470. };
  109471. /**
  109472. * Returns true if the layer contains information to display, otherwise false.
  109473. * @returns true if the glow layer should be rendered
  109474. */
  109475. EffectLayer.prototype.shouldRender = function () {
  109476. return this.isEnabled && this._shouldRender;
  109477. };
  109478. /**
  109479. * Returns true if the mesh should render, otherwise false.
  109480. * @param mesh The mesh to render
  109481. * @returns true if it should render otherwise false
  109482. */
  109483. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  109484. return true;
  109485. };
  109486. /**
  109487. * Returns true if the mesh should render, otherwise false.
  109488. * @param mesh The mesh to render
  109489. * @returns true if it should render otherwise false
  109490. */
  109491. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  109492. return true;
  109493. };
  109494. /**
  109495. * Renders the submesh passed in parameter to the generation map.
  109496. */
  109497. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  109498. var _this = this;
  109499. if (!this.shouldRender()) {
  109500. return;
  109501. }
  109502. var material = subMesh.getMaterial();
  109503. var mesh = subMesh.getRenderingMesh();
  109504. var scene = this._scene;
  109505. var engine = scene.getEngine();
  109506. if (!material) {
  109507. return;
  109508. }
  109509. // Do not block in blend mode.
  109510. if (material.needAlphaBlendingForMesh(mesh)) {
  109511. return;
  109512. }
  109513. // Culling
  109514. engine.setState(material.backFaceCulling);
  109515. // Managing instances
  109516. var batch = mesh._getInstancesRenderList(subMesh._id);
  109517. if (batch.mustReturn) {
  109518. return;
  109519. }
  109520. // Early Exit per mesh
  109521. if (!this._shouldRenderMesh(mesh)) {
  109522. return;
  109523. }
  109524. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109525. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  109526. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  109527. engine.enableEffect(this._effectLayerMapGenerationEffect);
  109528. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  109529. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  109530. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  109531. // Alpha test
  109532. if (material && material.needAlphaTesting()) {
  109533. var alphaTexture = material.getAlphaTestTexture();
  109534. if (alphaTexture) {
  109535. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  109536. var textureMatrix = alphaTexture.getTextureMatrix();
  109537. if (textureMatrix) {
  109538. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  109539. }
  109540. }
  109541. }
  109542. // Glow emissive only
  109543. if (this._emissiveTextureAndColor.texture) {
  109544. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  109545. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  109546. }
  109547. // Bones
  109548. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109549. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109550. }
  109551. // Morph targets
  109552. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  109553. // Draw
  109554. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  109555. }
  109556. else {
  109557. // Need to reset refresh rate of the main map
  109558. this._mainTexture.resetRefreshCounter();
  109559. }
  109560. };
  109561. /**
  109562. * Rebuild the required buffers.
  109563. * @hidden Internal use only.
  109564. */
  109565. EffectLayer.prototype._rebuild = function () {
  109566. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109567. if (vb) {
  109568. vb._rebuild();
  109569. }
  109570. this._generateIndexBuffer();
  109571. };
  109572. /**
  109573. * Dispose only the render target textures and post process.
  109574. */
  109575. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  109576. this._mainTexture.dispose();
  109577. for (var i = 0; i < this._postProcesses.length; i++) {
  109578. if (this._postProcesses[i]) {
  109579. this._postProcesses[i].dispose();
  109580. }
  109581. }
  109582. this._postProcesses = [];
  109583. for (var i = 0; i < this._textures.length; i++) {
  109584. if (this._textures[i]) {
  109585. this._textures[i].dispose();
  109586. }
  109587. }
  109588. this._textures = [];
  109589. };
  109590. /**
  109591. * Dispose the highlight layer and free resources.
  109592. */
  109593. EffectLayer.prototype.dispose = function () {
  109594. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109595. if (vertexBuffer) {
  109596. vertexBuffer.dispose();
  109597. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109598. }
  109599. if (this._indexBuffer) {
  109600. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109601. this._indexBuffer = null;
  109602. }
  109603. // Clean textures and post processes
  109604. this._disposeTextureAndPostProcesses();
  109605. // Remove from scene
  109606. var index = this._scene.effectLayers.indexOf(this, 0);
  109607. if (index > -1) {
  109608. this._scene.effectLayers.splice(index, 1);
  109609. }
  109610. // Callback
  109611. this.onDisposeObservable.notifyObservers(this);
  109612. this.onDisposeObservable.clear();
  109613. this.onBeforeRenderMainTextureObservable.clear();
  109614. this.onBeforeComposeObservable.clear();
  109615. this.onAfterComposeObservable.clear();
  109616. this.onSizeChangedObservable.clear();
  109617. };
  109618. /**
  109619. * Gets the class name of the effect layer
  109620. * @returns the string with the class name of the effect layer
  109621. */
  109622. EffectLayer.prototype.getClassName = function () {
  109623. return "EffectLayer";
  109624. };
  109625. /**
  109626. * Creates an effect layer from parsed effect layer data
  109627. * @param parsedEffectLayer defines effect layer data
  109628. * @param scene defines the current scene
  109629. * @param rootUrl defines the root URL containing the effect layer information
  109630. * @returns a parsed effect Layer
  109631. */
  109632. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  109633. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  109634. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  109635. };
  109636. __decorate([
  109637. BABYLON.serialize()
  109638. ], EffectLayer.prototype, "name", void 0);
  109639. __decorate([
  109640. BABYLON.serializeAsColor4()
  109641. ], EffectLayer.prototype, "neutralColor", void 0);
  109642. __decorate([
  109643. BABYLON.serialize()
  109644. ], EffectLayer.prototype, "isEnabled", void 0);
  109645. __decorate([
  109646. BABYLON.serializeAsCameraReference()
  109647. ], EffectLayer.prototype, "camera", null);
  109648. __decorate([
  109649. BABYLON.serialize()
  109650. ], EffectLayer.prototype, "renderingGroupId", null);
  109651. return EffectLayer;
  109652. }());
  109653. BABYLON.EffectLayer = EffectLayer;
  109654. })(BABYLON || (BABYLON = {}));
  109655. //# sourceMappingURL=babylon.effectLayer.js.map
  109656. var BABYLON;
  109657. (function (BABYLON) {
  109658. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  109659. for (var index = 0; index < this.effectLayers.length; index++) {
  109660. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  109661. return this.effectLayers[index];
  109662. }
  109663. }
  109664. return null;
  109665. };
  109666. /**
  109667. * Special Glow Blur post process only blurring the alpha channel
  109668. * It enforces keeping the most luminous color in the color channel.
  109669. */
  109670. var GlowBlurPostProcess = /** @class */ (function (_super) {
  109671. __extends(GlowBlurPostProcess, _super);
  109672. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  109673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  109674. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  109675. _this.direction = direction;
  109676. _this.kernel = kernel;
  109677. _this.onApplyObservable.add(function (effect) {
  109678. effect.setFloat2("screenSize", _this.width, _this.height);
  109679. effect.setVector2("direction", _this.direction);
  109680. effect.setFloat("blurWidth", _this.kernel);
  109681. });
  109682. return _this;
  109683. }
  109684. return GlowBlurPostProcess;
  109685. }(BABYLON.PostProcess));
  109686. /**
  109687. * The highlight layer Helps adding a glow effect around a mesh.
  109688. *
  109689. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109690. * glowy meshes to your scene.
  109691. *
  109692. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  109693. */
  109694. var HighlightLayer = /** @class */ (function (_super) {
  109695. __extends(HighlightLayer, _super);
  109696. /**
  109697. * Instantiates a new highlight Layer and references it to the scene..
  109698. * @param name The name of the layer
  109699. * @param scene The scene to use the layer in
  109700. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  109701. */
  109702. function HighlightLayer(name, scene, options) {
  109703. var _this = _super.call(this, name, scene) || this;
  109704. _this.name = name;
  109705. /**
  109706. * Specifies whether or not the inner glow is ACTIVE in the layer.
  109707. */
  109708. _this.innerGlow = true;
  109709. /**
  109710. * Specifies whether or not the outer glow is ACTIVE in the layer.
  109711. */
  109712. _this.outerGlow = true;
  109713. /**
  109714. * An event triggered when the highlight layer is being blurred.
  109715. */
  109716. _this.onBeforeBlurObservable = new BABYLON.Observable();
  109717. /**
  109718. * An event triggered when the highlight layer has been blurred.
  109719. */
  109720. _this.onAfterBlurObservable = new BABYLON.Observable();
  109721. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  109722. _this._meshes = {};
  109723. _this._excludedMeshes = {};
  109724. _this.neutralColor = HighlightLayer.NeutralColor;
  109725. // Warn on stencil
  109726. if (!_this._engine.isStencilEnable) {
  109727. 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 }");
  109728. }
  109729. // Adapt options
  109730. _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);
  109731. // Initialize the layer
  109732. _this._init({
  109733. alphaBlendingMode: _this._options.alphaBlendingMode,
  109734. camera: _this._options.camera,
  109735. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109736. mainTextureRatio: _this._options.mainTextureRatio,
  109737. renderingGroupId: _this._options.renderingGroupId
  109738. });
  109739. // Do not render as long as no meshes have been added
  109740. _this._shouldRender = false;
  109741. return _this;
  109742. }
  109743. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  109744. /**
  109745. * Gets the horizontal size of the blur.
  109746. */
  109747. get: function () {
  109748. return this._horizontalBlurPostprocess.kernel;
  109749. },
  109750. /**
  109751. * Specifies the horizontal size of the blur.
  109752. */
  109753. set: function (value) {
  109754. this._horizontalBlurPostprocess.kernel = value;
  109755. },
  109756. enumerable: true,
  109757. configurable: true
  109758. });
  109759. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  109760. /**
  109761. * Gets the vertical size of the blur.
  109762. */
  109763. get: function () {
  109764. return this._verticalBlurPostprocess.kernel;
  109765. },
  109766. /**
  109767. * Specifies the vertical size of the blur.
  109768. */
  109769. set: function (value) {
  109770. this._verticalBlurPostprocess.kernel = value;
  109771. },
  109772. enumerable: true,
  109773. configurable: true
  109774. });
  109775. /**
  109776. * Get the effect name of the layer.
  109777. * @return The effect name
  109778. */
  109779. HighlightLayer.prototype.getEffectName = function () {
  109780. return HighlightLayer.EffectName;
  109781. };
  109782. /**
  109783. * Create the merge effect. This is the shader use to blit the information back
  109784. * to the main canvas at the end of the scene rendering.
  109785. */
  109786. HighlightLayer.prototype._createMergeEffect = function () {
  109787. // Effect
  109788. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  109789. };
  109790. /**
  109791. * Creates the render target textures and post processes used in the highlight layer.
  109792. */
  109793. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  109794. var _this = this;
  109795. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  109796. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  109797. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  109798. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  109799. var textureType = 0;
  109800. if (this._engine.getCaps().textureHalfFloatRender) {
  109801. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  109802. }
  109803. else {
  109804. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109805. }
  109806. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  109807. width: blurTextureWidth,
  109808. height: blurTextureHeight
  109809. }, this._scene, false, true, textureType);
  109810. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109811. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109812. this._blurTexture.anisotropicFilteringLevel = 16;
  109813. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  109814. this._blurTexture.renderParticles = false;
  109815. this._blurTexture.ignoreCameraViewport = true;
  109816. this._textures = [this._blurTexture];
  109817. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  109818. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109819. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  109820. effect.setTexture("textureSampler", _this._mainTexture);
  109821. });
  109822. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109823. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109824. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109825. });
  109826. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109827. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  109828. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109829. });
  109830. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109831. }
  109832. else {
  109833. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  109834. width: blurTextureWidth,
  109835. height: blurTextureHeight
  109836. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109837. this._horizontalBlurPostprocess.width = blurTextureWidth;
  109838. this._horizontalBlurPostprocess.height = blurTextureHeight;
  109839. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109840. effect.setTexture("textureSampler", _this._mainTexture);
  109841. });
  109842. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  109843. width: blurTextureWidth,
  109844. height: blurTextureHeight
  109845. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109846. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109847. }
  109848. this._mainTexture.onAfterUnbindObservable.add(function () {
  109849. _this.onBeforeBlurObservable.notifyObservers(_this);
  109850. var internalTexture = _this._blurTexture.getInternalTexture();
  109851. if (internalTexture) {
  109852. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  109853. }
  109854. _this.onAfterBlurObservable.notifyObservers(_this);
  109855. });
  109856. // Prevent autoClear.
  109857. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  109858. };
  109859. /**
  109860. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  109861. */
  109862. HighlightLayer.prototype.needStencil = function () {
  109863. return true;
  109864. };
  109865. /**
  109866. * Checks for the readiness of the element composing the layer.
  109867. * @param subMesh the mesh to check for
  109868. * @param useInstances specify wether or not to use instances to render the mesh
  109869. * @param emissiveTexture the associated emissive texture used to generate the glow
  109870. * @return true if ready otherwise, false
  109871. */
  109872. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  109873. var material = subMesh.getMaterial();
  109874. var mesh = subMesh.getRenderingMesh();
  109875. if (!material || !mesh || !this._meshes) {
  109876. return false;
  109877. }
  109878. var emissiveTexture = null;
  109879. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109880. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109881. emissiveTexture = material.emissiveTexture;
  109882. }
  109883. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  109884. };
  109885. /**
  109886. * Implementation specific of rendering the generating effect on the main canvas.
  109887. * @param effect The effect used to render through
  109888. */
  109889. HighlightLayer.prototype._internalRender = function (effect) {
  109890. // Texture
  109891. effect.setTexture("textureSampler", this._blurTexture);
  109892. // Cache
  109893. var engine = this._engine;
  109894. var previousStencilBuffer = engine.getStencilBuffer();
  109895. var previousStencilFunction = engine.getStencilFunction();
  109896. var previousStencilMask = engine.getStencilMask();
  109897. var previousStencilOperationPass = engine.getStencilOperationPass();
  109898. var previousStencilOperationFail = engine.getStencilOperationFail();
  109899. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  109900. var previousStencilReference = engine.getStencilFunctionReference();
  109901. // Stencil operations
  109902. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  109903. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  109904. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  109905. // Draw order
  109906. engine.setStencilMask(0x00);
  109907. engine.setStencilBuffer(true);
  109908. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  109909. // 2 passes inner outer
  109910. if (this.outerGlow) {
  109911. effect.setFloat("offset", 0);
  109912. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  109913. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109914. }
  109915. if (this.innerGlow) {
  109916. effect.setFloat("offset", 1);
  109917. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  109918. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109919. }
  109920. // Restore Cache
  109921. engine.setStencilFunction(previousStencilFunction);
  109922. engine.setStencilMask(previousStencilMask);
  109923. engine.setStencilBuffer(previousStencilBuffer);
  109924. engine.setStencilOperationPass(previousStencilOperationPass);
  109925. engine.setStencilOperationFail(previousStencilOperationFail);
  109926. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  109927. engine.setStencilFunctionReference(previousStencilReference);
  109928. };
  109929. /**
  109930. * Returns true if the layer contains information to display, otherwise false.
  109931. */
  109932. HighlightLayer.prototype.shouldRender = function () {
  109933. if (_super.prototype.shouldRender.call(this)) {
  109934. return this._meshes ? true : false;
  109935. }
  109936. return false;
  109937. };
  109938. /**
  109939. * Returns true if the mesh should render, otherwise false.
  109940. * @param mesh The mesh to render
  109941. * @returns true if it should render otherwise false
  109942. */
  109943. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  109944. // Excluded Mesh
  109945. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  109946. return false;
  109947. }
  109948. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109949. return false;
  109950. }
  109951. return true;
  109952. };
  109953. /**
  109954. * Sets the required values for both the emissive texture and and the main color.
  109955. */
  109956. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  109957. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109958. if (highlightLayerMesh) {
  109959. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  109960. }
  109961. else {
  109962. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  109963. }
  109964. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109965. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  109966. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  109967. }
  109968. else {
  109969. this._emissiveTextureAndColor.texture = null;
  109970. }
  109971. };
  109972. /**
  109973. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  109974. * @param mesh The mesh to exclude from the highlight layer
  109975. */
  109976. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  109977. if (!this._excludedMeshes) {
  109978. return;
  109979. }
  109980. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109981. if (!meshExcluded) {
  109982. this._excludedMeshes[mesh.uniqueId] = {
  109983. mesh: mesh,
  109984. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  109985. mesh.getEngine().setStencilBuffer(false);
  109986. }),
  109987. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  109988. mesh.getEngine().setStencilBuffer(true);
  109989. }),
  109990. };
  109991. }
  109992. };
  109993. /**
  109994. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  109995. * @param mesh The mesh to highlight
  109996. */
  109997. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  109998. if (!this._excludedMeshes) {
  109999. return;
  110000. }
  110001. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  110002. if (meshExcluded) {
  110003. if (meshExcluded.beforeRender) {
  110004. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  110005. }
  110006. if (meshExcluded.afterRender) {
  110007. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  110008. }
  110009. }
  110010. this._excludedMeshes[mesh.uniqueId] = null;
  110011. };
  110012. /**
  110013. * Determine if a given mesh will be highlighted by the current HighlightLayer
  110014. * @param mesh mesh to test
  110015. * @returns true if the mesh will be highlighted by the current HighlightLayer
  110016. */
  110017. HighlightLayer.prototype.hasMesh = function (mesh) {
  110018. if (!this._meshes) {
  110019. return false;
  110020. }
  110021. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110022. return false;
  110023. }
  110024. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  110025. };
  110026. /**
  110027. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  110028. * @param mesh The mesh to highlight
  110029. * @param color The color of the highlight
  110030. * @param glowEmissiveOnly Extract the glow from the emissive texture
  110031. */
  110032. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  110033. var _this = this;
  110034. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  110035. if (!this._meshes) {
  110036. return;
  110037. }
  110038. var meshHighlight = this._meshes[mesh.uniqueId];
  110039. if (meshHighlight) {
  110040. meshHighlight.color = color;
  110041. }
  110042. else {
  110043. this._meshes[mesh.uniqueId] = {
  110044. mesh: mesh,
  110045. color: color,
  110046. // Lambda required for capture due to Observable this context
  110047. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  110048. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  110049. _this._defaultStencilReference(mesh);
  110050. }
  110051. else {
  110052. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  110053. }
  110054. }),
  110055. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  110056. glowEmissiveOnly: glowEmissiveOnly
  110057. };
  110058. mesh.onDisposeObservable.add(function () {
  110059. _this._disposeMesh(mesh);
  110060. });
  110061. }
  110062. this._shouldRender = true;
  110063. };
  110064. /**
  110065. * Remove a mesh from the highlight layer in order to make it stop glowing.
  110066. * @param mesh The mesh to highlight
  110067. */
  110068. HighlightLayer.prototype.removeMesh = function (mesh) {
  110069. if (!this._meshes) {
  110070. return;
  110071. }
  110072. var meshHighlight = this._meshes[mesh.uniqueId];
  110073. if (meshHighlight) {
  110074. if (meshHighlight.observerHighlight) {
  110075. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  110076. }
  110077. if (meshHighlight.observerDefault) {
  110078. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  110079. }
  110080. delete this._meshes[mesh.uniqueId];
  110081. }
  110082. this._shouldRender = false;
  110083. for (var meshHighlightToCheck in this._meshes) {
  110084. if (this._meshes[meshHighlightToCheck]) {
  110085. this._shouldRender = true;
  110086. break;
  110087. }
  110088. }
  110089. };
  110090. /**
  110091. * Force the stencil to the normal expected value for none glowing parts
  110092. */
  110093. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  110094. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  110095. };
  110096. /**
  110097. * Free any resources and references associated to a mesh.
  110098. * Internal use
  110099. * @param mesh The mesh to free.
  110100. * @hidden
  110101. */
  110102. HighlightLayer.prototype._disposeMesh = function (mesh) {
  110103. this.removeMesh(mesh);
  110104. this.removeExcludedMesh(mesh);
  110105. };
  110106. /**
  110107. * Dispose the highlight layer and free resources.
  110108. */
  110109. HighlightLayer.prototype.dispose = function () {
  110110. if (this._meshes) {
  110111. // Clean mesh references
  110112. for (var id in this._meshes) {
  110113. var meshHighlight = this._meshes[id];
  110114. if (meshHighlight && meshHighlight.mesh) {
  110115. if (meshHighlight.observerHighlight) {
  110116. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  110117. }
  110118. if (meshHighlight.observerDefault) {
  110119. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  110120. }
  110121. }
  110122. }
  110123. this._meshes = null;
  110124. }
  110125. if (this._excludedMeshes) {
  110126. for (var id in this._excludedMeshes) {
  110127. var meshHighlight = this._excludedMeshes[id];
  110128. if (meshHighlight) {
  110129. if (meshHighlight.beforeRender) {
  110130. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  110131. }
  110132. if (meshHighlight.afterRender) {
  110133. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  110134. }
  110135. }
  110136. }
  110137. this._excludedMeshes = null;
  110138. }
  110139. _super.prototype.dispose.call(this);
  110140. };
  110141. /**
  110142. * Gets the class name of the effect layer
  110143. * @returns the string with the class name of the effect layer
  110144. */
  110145. HighlightLayer.prototype.getClassName = function () {
  110146. return "HighlightLayer";
  110147. };
  110148. /**
  110149. * Serializes this Highlight layer
  110150. * @returns a serialized Highlight layer object
  110151. */
  110152. HighlightLayer.prototype.serialize = function () {
  110153. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110154. serializationObject.customType = "BABYLON.HighlightLayer";
  110155. // Highlighted meshes
  110156. serializationObject.meshes = [];
  110157. if (this._meshes) {
  110158. for (var m in this._meshes) {
  110159. var mesh = this._meshes[m];
  110160. if (mesh) {
  110161. serializationObject.meshes.push({
  110162. glowEmissiveOnly: mesh.glowEmissiveOnly,
  110163. color: mesh.color.asArray(),
  110164. meshId: mesh.mesh.id
  110165. });
  110166. }
  110167. }
  110168. }
  110169. // Excluded meshes
  110170. serializationObject.excludedMeshes = [];
  110171. if (this._excludedMeshes) {
  110172. for (var e in this._excludedMeshes) {
  110173. var excludedMesh = this._excludedMeshes[e];
  110174. if (excludedMesh) {
  110175. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  110176. }
  110177. }
  110178. }
  110179. return serializationObject;
  110180. };
  110181. /**
  110182. * Creates a Highlight layer from parsed Highlight layer data
  110183. * @param parsedHightlightLayer defines the Highlight layer data
  110184. * @param scene defines the current scene
  110185. * @param rootUrl defines the root URL containing the Highlight layer information
  110186. * @returns a parsed Highlight layer
  110187. */
  110188. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  110189. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  110190. var index;
  110191. // Excluded meshes
  110192. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  110193. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  110194. if (mesh) {
  110195. hl.addExcludedMesh(mesh);
  110196. }
  110197. }
  110198. // Included meshes
  110199. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  110200. var highlightedMesh = parsedHightlightLayer.meshes[index];
  110201. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  110202. if (mesh) {
  110203. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  110204. }
  110205. }
  110206. return hl;
  110207. };
  110208. /**
  110209. * Effect Name of the highlight layer.
  110210. */
  110211. HighlightLayer.EffectName = "HighlightLayer";
  110212. /**
  110213. * The neutral color used during the preparation of the glow effect.
  110214. * This is black by default as the blend operation is a blend operation.
  110215. */
  110216. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  110217. /**
  110218. * Stencil value used for glowing meshes.
  110219. */
  110220. HighlightLayer.GlowingMeshStencilReference = 0x02;
  110221. /**
  110222. * Stencil value used for the other meshes in the scene.
  110223. */
  110224. HighlightLayer.NormalMeshStencilReference = 0x01;
  110225. __decorate([
  110226. BABYLON.serialize()
  110227. ], HighlightLayer.prototype, "innerGlow", void 0);
  110228. __decorate([
  110229. BABYLON.serialize()
  110230. ], HighlightLayer.prototype, "outerGlow", void 0);
  110231. __decorate([
  110232. BABYLON.serialize()
  110233. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  110234. __decorate([
  110235. BABYLON.serialize()
  110236. ], HighlightLayer.prototype, "blurVerticalSize", null);
  110237. __decorate([
  110238. BABYLON.serialize("options")
  110239. ], HighlightLayer.prototype, "_options", void 0);
  110240. return HighlightLayer;
  110241. }(BABYLON.EffectLayer));
  110242. BABYLON.HighlightLayer = HighlightLayer;
  110243. })(BABYLON || (BABYLON = {}));
  110244. //# sourceMappingURL=babylon.highlightLayer.js.map
  110245. var BABYLON;
  110246. (function (BABYLON) {
  110247. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  110248. for (var index = 0; index < this.effectLayers.length; index++) {
  110249. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  110250. return this.effectLayers[index];
  110251. }
  110252. }
  110253. return null;
  110254. };
  110255. /**
  110256. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  110257. *
  110258. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  110259. * glowy meshes to your scene.
  110260. *
  110261. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  110262. */
  110263. var GlowLayer = /** @class */ (function (_super) {
  110264. __extends(GlowLayer, _super);
  110265. /**
  110266. * Instantiates a new glow Layer and references it to the scene.
  110267. * @param name The name of the layer
  110268. * @param scene The scene to use the layer in
  110269. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  110270. */
  110271. function GlowLayer(name, scene, options) {
  110272. var _this = _super.call(this, name, scene) || this;
  110273. _this._intensity = 1.0;
  110274. _this._includedOnlyMeshes = [];
  110275. _this._excludedMeshes = [];
  110276. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  110277. // Adapt options
  110278. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  110279. // Initialize the layer
  110280. _this._init({
  110281. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  110282. camera: _this._options.camera,
  110283. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  110284. mainTextureRatio: _this._options.mainTextureRatio,
  110285. renderingGroupId: _this._options.renderingGroupId
  110286. });
  110287. return _this;
  110288. }
  110289. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  110290. /**
  110291. * Gets the kernel size of the blur.
  110292. */
  110293. get: function () {
  110294. return this._horizontalBlurPostprocess1.kernel;
  110295. },
  110296. /**
  110297. * Sets the kernel size of the blur.
  110298. */
  110299. set: function (value) {
  110300. this._horizontalBlurPostprocess1.kernel = value;
  110301. this._verticalBlurPostprocess1.kernel = value;
  110302. this._horizontalBlurPostprocess2.kernel = value;
  110303. this._verticalBlurPostprocess2.kernel = value;
  110304. },
  110305. enumerable: true,
  110306. configurable: true
  110307. });
  110308. Object.defineProperty(GlowLayer.prototype, "intensity", {
  110309. /**
  110310. * Gets the glow intensity.
  110311. */
  110312. get: function () {
  110313. return this._intensity;
  110314. },
  110315. /**
  110316. * Sets the glow intensity.
  110317. */
  110318. set: function (value) {
  110319. this._intensity = value;
  110320. },
  110321. enumerable: true,
  110322. configurable: true
  110323. });
  110324. /**
  110325. * Get the effect name of the layer.
  110326. * @return The effect name
  110327. */
  110328. GlowLayer.prototype.getEffectName = function () {
  110329. return GlowLayer.EffectName;
  110330. };
  110331. /**
  110332. * Create the merge effect. This is the shader use to blit the information back
  110333. * to the main canvas at the end of the scene rendering.
  110334. */
  110335. GlowLayer.prototype._createMergeEffect = function () {
  110336. // Effect
  110337. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  110338. };
  110339. /**
  110340. * Creates the render target textures and post processes used in the glow layer.
  110341. */
  110342. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  110343. var _this = this;
  110344. var blurTextureWidth = this._mainTextureDesiredSize.width;
  110345. var blurTextureHeight = this._mainTextureDesiredSize.height;
  110346. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  110347. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  110348. var textureType = 0;
  110349. if (this._engine.getCaps().textureHalfFloatRender) {
  110350. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  110351. }
  110352. else {
  110353. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110354. }
  110355. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  110356. width: blurTextureWidth,
  110357. height: blurTextureHeight
  110358. }, this._scene, false, true, textureType);
  110359. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110360. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110361. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110362. this._blurTexture1.renderParticles = false;
  110363. this._blurTexture1.ignoreCameraViewport = true;
  110364. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  110365. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  110366. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  110367. width: blurTextureWidth2,
  110368. height: blurTextureHeight2
  110369. }, this._scene, false, true, textureType);
  110370. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110371. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110372. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110373. this._blurTexture2.renderParticles = false;
  110374. this._blurTexture2.ignoreCameraViewport = true;
  110375. this._textures = [this._blurTexture1, this._blurTexture2];
  110376. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110377. width: blurTextureWidth,
  110378. height: blurTextureHeight
  110379. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110380. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  110381. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  110382. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  110383. effect.setTexture("textureSampler", _this._mainTexture);
  110384. });
  110385. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110386. width: blurTextureWidth,
  110387. height: blurTextureHeight
  110388. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110389. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110390. width: blurTextureWidth2,
  110391. height: blurTextureHeight2
  110392. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110393. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  110394. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  110395. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  110396. effect.setTexture("textureSampler", _this._blurTexture1);
  110397. });
  110398. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110399. width: blurTextureWidth2,
  110400. height: blurTextureHeight2
  110401. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110402. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110403. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  110404. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110405. this._mainTexture.samples = this._options.mainTextureSamples;
  110406. this._mainTexture.onAfterUnbindObservable.add(function () {
  110407. var internalTexture = _this._blurTexture1.getInternalTexture();
  110408. if (internalTexture) {
  110409. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  110410. internalTexture = _this._blurTexture2.getInternalTexture();
  110411. if (internalTexture) {
  110412. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  110413. }
  110414. }
  110415. });
  110416. // Prevent autoClear.
  110417. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  110418. };
  110419. /**
  110420. * Checks for the readiness of the element composing the layer.
  110421. * @param subMesh the mesh to check for
  110422. * @param useInstances specify wether or not to use instances to render the mesh
  110423. * @param emissiveTexture the associated emissive texture used to generate the glow
  110424. * @return true if ready otherwise, false
  110425. */
  110426. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  110427. var material = subMesh.getMaterial();
  110428. var mesh = subMesh.getRenderingMesh();
  110429. if (!material || !mesh) {
  110430. return false;
  110431. }
  110432. var emissiveTexture = material.emissiveTexture;
  110433. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  110434. };
  110435. /**
  110436. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  110437. */
  110438. GlowLayer.prototype.needStencil = function () {
  110439. return false;
  110440. };
  110441. /**
  110442. * Implementation specific of rendering the generating effect on the main canvas.
  110443. * @param effect The effect used to render through
  110444. */
  110445. GlowLayer.prototype._internalRender = function (effect) {
  110446. // Texture
  110447. effect.setTexture("textureSampler", this._blurTexture1);
  110448. effect.setTexture("textureSampler2", this._blurTexture2);
  110449. effect.setFloat("offset", this._intensity);
  110450. // Cache
  110451. var engine = this._engine;
  110452. var previousStencilBuffer = engine.getStencilBuffer();
  110453. // Draw order
  110454. engine.setStencilBuffer(false);
  110455. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110456. // Draw order
  110457. engine.setStencilBuffer(previousStencilBuffer);
  110458. };
  110459. /**
  110460. * Sets the required values for both the emissive texture and and the main color.
  110461. */
  110462. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  110463. var textureLevel = 1.0;
  110464. if (this.customEmissiveTextureSelector) {
  110465. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  110466. }
  110467. else {
  110468. if (material) {
  110469. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  110470. if (this._emissiveTextureAndColor.texture) {
  110471. textureLevel = this._emissiveTextureAndColor.texture.level;
  110472. }
  110473. }
  110474. else {
  110475. this._emissiveTextureAndColor.texture = null;
  110476. }
  110477. }
  110478. if (this.customEmissiveColorSelector) {
  110479. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  110480. }
  110481. else {
  110482. if (material.emissiveColor) {
  110483. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  110484. }
  110485. else {
  110486. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  110487. }
  110488. }
  110489. };
  110490. /**
  110491. * Returns true if the mesh should render, otherwise false.
  110492. * @param mesh The mesh to render
  110493. * @returns true if it should render otherwise false
  110494. */
  110495. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  110496. return this.hasMesh(mesh);
  110497. };
  110498. /**
  110499. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  110500. * @param mesh The mesh to exclude from the glow layer
  110501. */
  110502. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  110503. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  110504. this._excludedMeshes.push(mesh.uniqueId);
  110505. }
  110506. };
  110507. /**
  110508. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  110509. * @param mesh The mesh to remove
  110510. */
  110511. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  110512. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  110513. if (index !== -1) {
  110514. this._excludedMeshes.splice(index, 1);
  110515. }
  110516. };
  110517. /**
  110518. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  110519. * @param mesh The mesh to include in the glow layer
  110520. */
  110521. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  110522. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  110523. this._includedOnlyMeshes.push(mesh.uniqueId);
  110524. }
  110525. };
  110526. /**
  110527. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  110528. * @param mesh The mesh to remove
  110529. */
  110530. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  110531. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  110532. if (index !== -1) {
  110533. this._includedOnlyMeshes.splice(index, 1);
  110534. }
  110535. };
  110536. /**
  110537. * Determine if a given mesh will be used in the glow layer
  110538. * @param mesh The mesh to test
  110539. * @returns true if the mesh will be highlighted by the current glow layer
  110540. */
  110541. GlowLayer.prototype.hasMesh = function (mesh) {
  110542. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110543. return false;
  110544. }
  110545. // Included Mesh
  110546. if (this._includedOnlyMeshes.length) {
  110547. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  110548. }
  110549. // Excluded Mesh
  110550. if (this._excludedMeshes.length) {
  110551. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  110552. }
  110553. return true;
  110554. };
  110555. /**
  110556. * Free any resources and references associated to a mesh.
  110557. * Internal use
  110558. * @param mesh The mesh to free.
  110559. * @hidden
  110560. */
  110561. GlowLayer.prototype._disposeMesh = function (mesh) {
  110562. this.removeIncludedOnlyMesh(mesh);
  110563. this.removeExcludedMesh(mesh);
  110564. };
  110565. /**
  110566. * Gets the class name of the effect layer
  110567. * @returns the string with the class name of the effect layer
  110568. */
  110569. GlowLayer.prototype.getClassName = function () {
  110570. return "GlowLayer";
  110571. };
  110572. /**
  110573. * Serializes this glow layer
  110574. * @returns a serialized glow layer object
  110575. */
  110576. GlowLayer.prototype.serialize = function () {
  110577. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110578. serializationObject.customType = "BABYLON.GlowLayer";
  110579. var index;
  110580. // Included meshes
  110581. serializationObject.includedMeshes = [];
  110582. if (this._includedOnlyMeshes.length) {
  110583. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  110584. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  110585. if (mesh) {
  110586. serializationObject.includedMeshes.push(mesh.id);
  110587. }
  110588. }
  110589. }
  110590. // Excluded meshes
  110591. serializationObject.excludedMeshes = [];
  110592. if (this._excludedMeshes.length) {
  110593. for (index = 0; index < this._excludedMeshes.length; index++) {
  110594. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  110595. if (mesh) {
  110596. serializationObject.excludedMeshes.push(mesh.id);
  110597. }
  110598. }
  110599. }
  110600. return serializationObject;
  110601. };
  110602. /**
  110603. * Creates a Glow Layer from parsed glow layer data
  110604. * @param parsedGlowLayer defines glow layer data
  110605. * @param scene defines the current scene
  110606. * @param rootUrl defines the root URL containing the glow layer information
  110607. * @returns a parsed Glow Layer
  110608. */
  110609. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  110610. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  110611. var index;
  110612. // Excluded meshes
  110613. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  110614. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  110615. if (mesh) {
  110616. gl.addExcludedMesh(mesh);
  110617. }
  110618. }
  110619. // Included meshes
  110620. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  110621. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  110622. if (mesh) {
  110623. gl.addIncludedOnlyMesh(mesh);
  110624. }
  110625. }
  110626. return gl;
  110627. };
  110628. /**
  110629. * Effect Name of the layer.
  110630. */
  110631. GlowLayer.EffectName = "GlowLayer";
  110632. /**
  110633. * The default blur kernel size used for the glow.
  110634. */
  110635. GlowLayer.DefaultBlurKernelSize = 32;
  110636. /**
  110637. * The default texture size ratio used for the glow.
  110638. */
  110639. GlowLayer.DefaultTextureRatio = 0.5;
  110640. __decorate([
  110641. BABYLON.serialize()
  110642. ], GlowLayer.prototype, "blurKernelSize", null);
  110643. __decorate([
  110644. BABYLON.serialize()
  110645. ], GlowLayer.prototype, "intensity", null);
  110646. __decorate([
  110647. BABYLON.serialize("options")
  110648. ], GlowLayer.prototype, "_options", void 0);
  110649. return GlowLayer;
  110650. }(BABYLON.EffectLayer));
  110651. BABYLON.GlowLayer = GlowLayer;
  110652. })(BABYLON || (BABYLON = {}));
  110653. //# sourceMappingURL=babylon.glowLayer.js.map
  110654. var BABYLON;
  110655. (function (BABYLON) {
  110656. /**
  110657. * Defines the list of states available for a task inside a AssetsManager
  110658. */
  110659. var AssetTaskState;
  110660. (function (AssetTaskState) {
  110661. /**
  110662. * Initialization
  110663. */
  110664. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  110665. /**
  110666. * Running
  110667. */
  110668. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  110669. /**
  110670. * Done
  110671. */
  110672. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  110673. /**
  110674. * Error
  110675. */
  110676. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  110677. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  110678. /**
  110679. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  110680. */
  110681. var AbstractAssetTask = /** @class */ (function () {
  110682. /**
  110683. * Creates a new AssetsManager
  110684. * @param name defines the name of the task
  110685. */
  110686. function AbstractAssetTask(
  110687. /**
  110688. * Task name
  110689. */ name) {
  110690. this.name = name;
  110691. this._isCompleted = false;
  110692. this._taskState = AssetTaskState.INIT;
  110693. }
  110694. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  110695. /**
  110696. * Get if the task is completed
  110697. */
  110698. get: function () {
  110699. return this._isCompleted;
  110700. },
  110701. enumerable: true,
  110702. configurable: true
  110703. });
  110704. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  110705. /**
  110706. * Gets the current state of the task
  110707. */
  110708. get: function () {
  110709. return this._taskState;
  110710. },
  110711. enumerable: true,
  110712. configurable: true
  110713. });
  110714. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  110715. /**
  110716. * Gets the current error object (if task is in error)
  110717. */
  110718. get: function () {
  110719. return this._errorObject;
  110720. },
  110721. enumerable: true,
  110722. configurable: true
  110723. });
  110724. /**
  110725. * Internal only
  110726. * @hidden
  110727. */
  110728. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  110729. if (this._errorObject) {
  110730. return;
  110731. }
  110732. this._errorObject = {
  110733. message: message,
  110734. exception: exception
  110735. };
  110736. };
  110737. /**
  110738. * Execute the current task
  110739. * @param scene defines the scene where you want your assets to be loaded
  110740. * @param onSuccess is a callback called when the task is successfully executed
  110741. * @param onError is a callback called if an error occurs
  110742. */
  110743. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110744. var _this = this;
  110745. this._taskState = AssetTaskState.RUNNING;
  110746. this.runTask(scene, function () {
  110747. _this.onDoneCallback(onSuccess, onError);
  110748. }, function (msg, exception) {
  110749. _this.onErrorCallback(onError, msg, exception);
  110750. });
  110751. };
  110752. /**
  110753. * Execute the current task
  110754. * @param scene defines the scene where you want your assets to be loaded
  110755. * @param onSuccess is a callback called when the task is successfully executed
  110756. * @param onError is a callback called if an error occurs
  110757. */
  110758. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110759. throw new Error("runTask is not implemented");
  110760. };
  110761. /**
  110762. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  110763. * This can be used with failed tasks that have the reason for failure fixed.
  110764. */
  110765. AbstractAssetTask.prototype.reset = function () {
  110766. this._taskState = AssetTaskState.INIT;
  110767. };
  110768. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  110769. this._taskState = AssetTaskState.ERROR;
  110770. this._errorObject = {
  110771. message: message,
  110772. exception: exception
  110773. };
  110774. if (this.onError) {
  110775. this.onError(this, message, exception);
  110776. }
  110777. onError();
  110778. };
  110779. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  110780. try {
  110781. this._taskState = AssetTaskState.DONE;
  110782. this._isCompleted = true;
  110783. if (this.onSuccess) {
  110784. this.onSuccess(this);
  110785. }
  110786. onSuccess();
  110787. }
  110788. catch (e) {
  110789. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  110790. }
  110791. };
  110792. return AbstractAssetTask;
  110793. }());
  110794. BABYLON.AbstractAssetTask = AbstractAssetTask;
  110795. /**
  110796. * Class used to share progress information about assets loading
  110797. */
  110798. var AssetsProgressEvent = /** @class */ (function () {
  110799. /**
  110800. * Creates a AssetsProgressEvent
  110801. * @param remainingCount defines the number of remaining tasks to process
  110802. * @param totalCount defines the total number of tasks
  110803. * @param task defines the task that was just processed
  110804. */
  110805. function AssetsProgressEvent(remainingCount, totalCount, task) {
  110806. this.remainingCount = remainingCount;
  110807. this.totalCount = totalCount;
  110808. this.task = task;
  110809. }
  110810. return AssetsProgressEvent;
  110811. }());
  110812. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  110813. /**
  110814. * Define a task used by AssetsManager to load meshes
  110815. */
  110816. var MeshAssetTask = /** @class */ (function (_super) {
  110817. __extends(MeshAssetTask, _super);
  110818. /**
  110819. * Creates a new MeshAssetTask
  110820. * @param name defines the name of the task
  110821. * @param meshesNames defines the list of mesh's names you want to load
  110822. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  110823. * @param sceneFilename defines the filename of the scene to load from
  110824. */
  110825. function MeshAssetTask(
  110826. /**
  110827. * Defines the name of the task
  110828. */
  110829. name,
  110830. /**
  110831. * Defines the list of mesh's names you want to load
  110832. */
  110833. meshesNames,
  110834. /**
  110835. * Defines the root url to use as a base to load your meshes and associated resources
  110836. */
  110837. rootUrl,
  110838. /**
  110839. * Defines the filename of the scene to load from
  110840. */
  110841. sceneFilename) {
  110842. var _this = _super.call(this, name) || this;
  110843. _this.name = name;
  110844. _this.meshesNames = meshesNames;
  110845. _this.rootUrl = rootUrl;
  110846. _this.sceneFilename = sceneFilename;
  110847. return _this;
  110848. }
  110849. /**
  110850. * Execute the current task
  110851. * @param scene defines the scene where you want your assets to be loaded
  110852. * @param onSuccess is a callback called when the task is successfully executed
  110853. * @param onError is a callback called if an error occurs
  110854. */
  110855. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110856. var _this = this;
  110857. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  110858. _this.loadedMeshes = meshes;
  110859. _this.loadedParticleSystems = particleSystems;
  110860. _this.loadedSkeletons = skeletons;
  110861. onSuccess();
  110862. }, null, function (scene, message, exception) {
  110863. onError(message, exception);
  110864. });
  110865. };
  110866. return MeshAssetTask;
  110867. }(AbstractAssetTask));
  110868. BABYLON.MeshAssetTask = MeshAssetTask;
  110869. /**
  110870. * Define a task used by AssetsManager to load text content
  110871. */
  110872. var TextFileAssetTask = /** @class */ (function (_super) {
  110873. __extends(TextFileAssetTask, _super);
  110874. /**
  110875. * Creates a new TextFileAssetTask object
  110876. * @param name defines the name of the task
  110877. * @param url defines the location of the file to load
  110878. */
  110879. function TextFileAssetTask(
  110880. /**
  110881. * Defines the name of the task
  110882. */
  110883. name,
  110884. /**
  110885. * Defines the location of the file to load
  110886. */
  110887. url) {
  110888. var _this = _super.call(this, name) || this;
  110889. _this.name = name;
  110890. _this.url = url;
  110891. return _this;
  110892. }
  110893. /**
  110894. * Execute the current task
  110895. * @param scene defines the scene where you want your assets to be loaded
  110896. * @param onSuccess is a callback called when the task is successfully executed
  110897. * @param onError is a callback called if an error occurs
  110898. */
  110899. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110900. var _this = this;
  110901. scene._loadFile(this.url, function (data) {
  110902. _this.text = data;
  110903. onSuccess();
  110904. }, undefined, false, false, function (request, exception) {
  110905. if (request) {
  110906. onError(request.status + " " + request.statusText, exception);
  110907. }
  110908. });
  110909. };
  110910. return TextFileAssetTask;
  110911. }(AbstractAssetTask));
  110912. BABYLON.TextFileAssetTask = TextFileAssetTask;
  110913. /**
  110914. * Define a task used by AssetsManager to load binary data
  110915. */
  110916. var BinaryFileAssetTask = /** @class */ (function (_super) {
  110917. __extends(BinaryFileAssetTask, _super);
  110918. /**
  110919. * Creates a new BinaryFileAssetTask object
  110920. * @param name defines the name of the new task
  110921. * @param url defines the location of the file to load
  110922. */
  110923. function BinaryFileAssetTask(
  110924. /**
  110925. * Defines the name of the task
  110926. */
  110927. name,
  110928. /**
  110929. * Defines the location of the file to load
  110930. */
  110931. url) {
  110932. var _this = _super.call(this, name) || this;
  110933. _this.name = name;
  110934. _this.url = url;
  110935. return _this;
  110936. }
  110937. /**
  110938. * Execute the current task
  110939. * @param scene defines the scene where you want your assets to be loaded
  110940. * @param onSuccess is a callback called when the task is successfully executed
  110941. * @param onError is a callback called if an error occurs
  110942. */
  110943. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110944. var _this = this;
  110945. scene._loadFile(this.url, function (data) {
  110946. _this.data = data;
  110947. onSuccess();
  110948. }, undefined, true, true, function (request, exception) {
  110949. if (request) {
  110950. onError(request.status + " " + request.statusText, exception);
  110951. }
  110952. });
  110953. };
  110954. return BinaryFileAssetTask;
  110955. }(AbstractAssetTask));
  110956. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  110957. /**
  110958. * Define a task used by AssetsManager to load images
  110959. */
  110960. var ImageAssetTask = /** @class */ (function (_super) {
  110961. __extends(ImageAssetTask, _super);
  110962. /**
  110963. * Creates a new ImageAssetTask
  110964. * @param name defines the name of the task
  110965. * @param url defines the location of the image to load
  110966. */
  110967. function ImageAssetTask(
  110968. /**
  110969. * Defines the name of the task
  110970. */
  110971. name,
  110972. /**
  110973. * Defines the location of the image to load
  110974. */
  110975. url) {
  110976. var _this = _super.call(this, name) || this;
  110977. _this.name = name;
  110978. _this.url = url;
  110979. return _this;
  110980. }
  110981. /**
  110982. * Execute the current task
  110983. * @param scene defines the scene where you want your assets to be loaded
  110984. * @param onSuccess is a callback called when the task is successfully executed
  110985. * @param onError is a callback called if an error occurs
  110986. */
  110987. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110988. var _this = this;
  110989. var img = new Image();
  110990. BABYLON.Tools.SetCorsBehavior(this.url, img);
  110991. img.onload = function () {
  110992. _this.image = img;
  110993. onSuccess();
  110994. };
  110995. img.onerror = function (err) {
  110996. onError("Error loading image", err);
  110997. };
  110998. img.src = this.url;
  110999. };
  111000. return ImageAssetTask;
  111001. }(AbstractAssetTask));
  111002. BABYLON.ImageAssetTask = ImageAssetTask;
  111003. /**
  111004. * Define a task used by AssetsManager to load 2D textures
  111005. */
  111006. var TextureAssetTask = /** @class */ (function (_super) {
  111007. __extends(TextureAssetTask, _super);
  111008. /**
  111009. * Creates a new TextureAssetTask object
  111010. * @param name defines the name of the task
  111011. * @param url defines the location of the file to load
  111012. * @param noMipmap defines if mipmap should not be generated (default is false)
  111013. * @param invertY defines if texture must be inverted on Y axis (default is false)
  111014. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  111015. */
  111016. function TextureAssetTask(
  111017. /**
  111018. * Defines the name of the task
  111019. */
  111020. name,
  111021. /**
  111022. * Defines the location of the file to load
  111023. */
  111024. url,
  111025. /**
  111026. * Defines if mipmap should not be generated (default is false)
  111027. */
  111028. noMipmap,
  111029. /**
  111030. * Defines if texture must be inverted on Y axis (default is false)
  111031. */
  111032. invertY,
  111033. /**
  111034. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  111035. */
  111036. samplingMode) {
  111037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111038. var _this = _super.call(this, name) || this;
  111039. _this.name = name;
  111040. _this.url = url;
  111041. _this.noMipmap = noMipmap;
  111042. _this.invertY = invertY;
  111043. _this.samplingMode = samplingMode;
  111044. return _this;
  111045. }
  111046. /**
  111047. * Execute the current task
  111048. * @param scene defines the scene where you want your assets to be loaded
  111049. * @param onSuccess is a callback called when the task is successfully executed
  111050. * @param onError is a callback called if an error occurs
  111051. */
  111052. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111053. var onload = function () {
  111054. onSuccess();
  111055. };
  111056. var onerror = function (message, exception) {
  111057. onError(message, exception);
  111058. };
  111059. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  111060. };
  111061. return TextureAssetTask;
  111062. }(AbstractAssetTask));
  111063. BABYLON.TextureAssetTask = TextureAssetTask;
  111064. /**
  111065. * Define a task used by AssetsManager to load cube textures
  111066. */
  111067. var CubeTextureAssetTask = /** @class */ (function (_super) {
  111068. __extends(CubeTextureAssetTask, _super);
  111069. /**
  111070. * Creates a new CubeTextureAssetTask
  111071. * @param name defines the name of the task
  111072. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  111073. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  111074. * @param noMipmap defines if mipmaps should not be generated (default is false)
  111075. * @param files defines the explicit list of files (undefined by default)
  111076. */
  111077. function CubeTextureAssetTask(
  111078. /**
  111079. * Defines the name of the task
  111080. */
  111081. name,
  111082. /**
  111083. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  111084. */
  111085. url,
  111086. /**
  111087. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  111088. */
  111089. extensions,
  111090. /**
  111091. * Defines if mipmaps should not be generated (default is false)
  111092. */
  111093. noMipmap,
  111094. /**
  111095. * Defines the explicit list of files (undefined by default)
  111096. */
  111097. files) {
  111098. var _this = _super.call(this, name) || this;
  111099. _this.name = name;
  111100. _this.url = url;
  111101. _this.extensions = extensions;
  111102. _this.noMipmap = noMipmap;
  111103. _this.files = files;
  111104. return _this;
  111105. }
  111106. /**
  111107. * Execute the current task
  111108. * @param scene defines the scene where you want your assets to be loaded
  111109. * @param onSuccess is a callback called when the task is successfully executed
  111110. * @param onError is a callback called if an error occurs
  111111. */
  111112. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  111113. var onload = function () {
  111114. onSuccess();
  111115. };
  111116. var onerror = function (message, exception) {
  111117. onError(message, exception);
  111118. };
  111119. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  111120. };
  111121. return CubeTextureAssetTask;
  111122. }(AbstractAssetTask));
  111123. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  111124. /**
  111125. * Define a task used by AssetsManager to load HDR cube textures
  111126. */
  111127. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  111128. __extends(HDRCubeTextureAssetTask, _super);
  111129. /**
  111130. * Creates a new HDRCubeTextureAssetTask object
  111131. * @param name defines the name of the task
  111132. * @param url defines the location of the file to load
  111133. * @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.
  111134. * @param noMipmap defines if mipmaps should not be generated (default is false)
  111135. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  111136. * @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)
  111137. * @param reserved Internal use only
  111138. */
  111139. function HDRCubeTextureAssetTask(
  111140. /**
  111141. * Defines the name of the task
  111142. */
  111143. name,
  111144. /**
  111145. * Defines the location of the file to load
  111146. */
  111147. url,
  111148. /**
  111149. * Defines the desired size (the more it increases the longer the generation will be)
  111150. */
  111151. size,
  111152. /**
  111153. * Defines if mipmaps should not be generated (default is false)
  111154. */
  111155. noMipmap,
  111156. /**
  111157. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  111158. */
  111159. generateHarmonics,
  111160. /**
  111161. * 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)
  111162. */
  111163. gammaSpace,
  111164. /**
  111165. * Internal Use Only
  111166. */
  111167. reserved) {
  111168. if (noMipmap === void 0) { noMipmap = false; }
  111169. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111170. if (gammaSpace === void 0) { gammaSpace = false; }
  111171. if (reserved === void 0) { reserved = false; }
  111172. var _this = _super.call(this, name) || this;
  111173. _this.name = name;
  111174. _this.url = url;
  111175. _this.size = size;
  111176. _this.noMipmap = noMipmap;
  111177. _this.generateHarmonics = generateHarmonics;
  111178. _this.gammaSpace = gammaSpace;
  111179. _this.reserved = reserved;
  111180. return _this;
  111181. }
  111182. /**
  111183. * Execute the current task
  111184. * @param scene defines the scene where you want your assets to be loaded
  111185. * @param onSuccess is a callback called when the task is successfully executed
  111186. * @param onError is a callback called if an error occurs
  111187. */
  111188. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  111189. var onload = function () {
  111190. onSuccess();
  111191. };
  111192. var onerror = function (message, exception) {
  111193. onError(message, exception);
  111194. };
  111195. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  111196. };
  111197. return HDRCubeTextureAssetTask;
  111198. }(AbstractAssetTask));
  111199. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  111200. /**
  111201. * This class can be used to easily import assets into a scene
  111202. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  111203. */
  111204. var AssetsManager = /** @class */ (function () {
  111205. /**
  111206. * Creates a new AssetsManager
  111207. * @param scene defines the scene to work on
  111208. */
  111209. function AssetsManager(scene) {
  111210. this._isLoading = false;
  111211. this._tasks = new Array();
  111212. this._waitingTasksCount = 0;
  111213. this._totalTasksCount = 0;
  111214. /**
  111215. * Observable called when all tasks are processed
  111216. */
  111217. this.onTaskSuccessObservable = new BABYLON.Observable();
  111218. /**
  111219. * Observable called when a task had an error
  111220. */
  111221. this.onTaskErrorObservable = new BABYLON.Observable();
  111222. /**
  111223. * Observable called when a task is successful
  111224. */
  111225. this.onTasksDoneObservable = new BABYLON.Observable();
  111226. /**
  111227. * Observable called when a task is done (whatever the result is)
  111228. */
  111229. this.onProgressObservable = new BABYLON.Observable();
  111230. /**
  111231. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  111232. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  111233. */
  111234. this.useDefaultLoadingScreen = true;
  111235. this._scene = scene;
  111236. }
  111237. /**
  111238. * Add a MeshAssetTask to the list of active tasks
  111239. * @param taskName defines the name of the new task
  111240. * @param meshesNames defines the name of meshes to load
  111241. * @param rootUrl defines the root url to use to locate files
  111242. * @param sceneFilename defines the filename of the scene file
  111243. * @returns a new MeshAssetTask object
  111244. */
  111245. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  111246. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  111247. this._tasks.push(task);
  111248. return task;
  111249. };
  111250. /**
  111251. * Add a TextFileAssetTask to the list of active tasks
  111252. * @param taskName defines the name of the new task
  111253. * @param url defines the url of the file to load
  111254. * @returns a new TextFileAssetTask object
  111255. */
  111256. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  111257. var task = new TextFileAssetTask(taskName, url);
  111258. this._tasks.push(task);
  111259. return task;
  111260. };
  111261. /**
  111262. * Add a BinaryFileAssetTask to the list of active tasks
  111263. * @param taskName defines the name of the new task
  111264. * @param url defines the url of the file to load
  111265. * @returns a new BinaryFileAssetTask object
  111266. */
  111267. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  111268. var task = new BinaryFileAssetTask(taskName, url);
  111269. this._tasks.push(task);
  111270. return task;
  111271. };
  111272. /**
  111273. * Add a ImageAssetTask to the list of active tasks
  111274. * @param taskName defines the name of the new task
  111275. * @param url defines the url of the file to load
  111276. * @returns a new ImageAssetTask object
  111277. */
  111278. AssetsManager.prototype.addImageTask = function (taskName, url) {
  111279. var task = new ImageAssetTask(taskName, url);
  111280. this._tasks.push(task);
  111281. return task;
  111282. };
  111283. /**
  111284. * Add a TextureAssetTask to the list of active tasks
  111285. * @param taskName defines the name of the new task
  111286. * @param url defines the url of the file to load
  111287. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111288. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  111289. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  111290. * @returns a new TextureAssetTask object
  111291. */
  111292. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  111293. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111294. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  111295. this._tasks.push(task);
  111296. return task;
  111297. };
  111298. /**
  111299. * Add a CubeTextureAssetTask to the list of active tasks
  111300. * @param taskName defines the name of the new task
  111301. * @param url defines the url of the file to load
  111302. * @param extensions defines the extension to use to load the cube map (can be null)
  111303. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111304. * @param files defines the list of files to load (can be null)
  111305. * @returns a new CubeTextureAssetTask object
  111306. */
  111307. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  111308. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  111309. this._tasks.push(task);
  111310. return task;
  111311. };
  111312. /**
  111313. *
  111314. * Add a HDRCubeTextureAssetTask to the list of active tasks
  111315. * @param taskName defines the name of the new task
  111316. * @param url defines the url of the file to load
  111317. * @param size defines the size you want for the cubemap (can be null)
  111318. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111319. * @param generateHarmonics defines if you want to automatically generate (true by default)
  111320. * @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)
  111321. * @param reserved Internal use only
  111322. * @returns a new HDRCubeTextureAssetTask object
  111323. */
  111324. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  111325. if (noMipmap === void 0) { noMipmap = false; }
  111326. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111327. if (gammaSpace === void 0) { gammaSpace = false; }
  111328. if (reserved === void 0) { reserved = false; }
  111329. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  111330. this._tasks.push(task);
  111331. return task;
  111332. };
  111333. /**
  111334. * Remove a task from the assets manager.
  111335. * @param task the task to remove
  111336. */
  111337. AssetsManager.prototype.removeTask = function (task) {
  111338. var index = this._tasks.indexOf(task);
  111339. if (index > -1) {
  111340. this._tasks.splice(index, 1);
  111341. }
  111342. };
  111343. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  111344. this._waitingTasksCount--;
  111345. try {
  111346. if (this.onProgress) {
  111347. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  111348. }
  111349. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  111350. }
  111351. catch (e) {
  111352. BABYLON.Tools.Error("Error running progress callbacks.");
  111353. console.log(e);
  111354. }
  111355. if (this._waitingTasksCount === 0) {
  111356. try {
  111357. if (this.onFinish) {
  111358. this.onFinish(this._tasks);
  111359. }
  111360. // Let's remove successfull tasks
  111361. var currentTasks = this._tasks.slice();
  111362. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  111363. var task = currentTasks_1[_i];
  111364. if (task.taskState === AssetTaskState.DONE) {
  111365. var index = this._tasks.indexOf(task);
  111366. if (index > -1) {
  111367. this._tasks.splice(index, 1);
  111368. }
  111369. }
  111370. }
  111371. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111372. }
  111373. catch (e) {
  111374. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  111375. console.log(e);
  111376. }
  111377. this._isLoading = false;
  111378. this._scene.getEngine().hideLoadingUI();
  111379. }
  111380. };
  111381. AssetsManager.prototype._runTask = function (task) {
  111382. var _this = this;
  111383. var done = function () {
  111384. try {
  111385. if (_this.onTaskSuccess) {
  111386. _this.onTaskSuccess(task);
  111387. }
  111388. _this.onTaskSuccessObservable.notifyObservers(task);
  111389. _this._decreaseWaitingTasksCount(task);
  111390. }
  111391. catch (e) {
  111392. error("Error executing task success callbacks", e);
  111393. }
  111394. };
  111395. var error = function (message, exception) {
  111396. task._setErrorObject(message, exception);
  111397. if (_this.onTaskError) {
  111398. _this.onTaskError(task);
  111399. }
  111400. _this.onTaskErrorObservable.notifyObservers(task);
  111401. _this._decreaseWaitingTasksCount(task);
  111402. };
  111403. task.run(this._scene, done, error);
  111404. };
  111405. /**
  111406. * Reset the AssetsManager and remove all tasks
  111407. * @return the current instance of the AssetsManager
  111408. */
  111409. AssetsManager.prototype.reset = function () {
  111410. this._isLoading = false;
  111411. this._tasks = new Array();
  111412. return this;
  111413. };
  111414. /**
  111415. * Start the loading process
  111416. * @return the current instance of the AssetsManager
  111417. */
  111418. AssetsManager.prototype.load = function () {
  111419. if (this._isLoading) {
  111420. return this;
  111421. }
  111422. this._isLoading = true;
  111423. this._waitingTasksCount = this._tasks.length;
  111424. this._totalTasksCount = this._tasks.length;
  111425. if (this._waitingTasksCount === 0) {
  111426. this._isLoading = false;
  111427. if (this.onFinish) {
  111428. this.onFinish(this._tasks);
  111429. }
  111430. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111431. return this;
  111432. }
  111433. if (this.useDefaultLoadingScreen) {
  111434. this._scene.getEngine().displayLoadingUI();
  111435. }
  111436. for (var index = 0; index < this._tasks.length; index++) {
  111437. var task = this._tasks[index];
  111438. if (task.taskState === AssetTaskState.INIT) {
  111439. this._runTask(task);
  111440. }
  111441. }
  111442. return this;
  111443. };
  111444. return AssetsManager;
  111445. }());
  111446. BABYLON.AssetsManager = AssetsManager;
  111447. })(BABYLON || (BABYLON = {}));
  111448. //# sourceMappingURL=babylon.assetsManager.js.map
  111449. var BABYLON;
  111450. (function (BABYLON) {
  111451. var serializedGeometries = [];
  111452. var serializeGeometry = function (geometry, serializationGeometries) {
  111453. if (serializedGeometries[geometry.id]) {
  111454. return;
  111455. }
  111456. if (geometry.doNotSerialize) {
  111457. return;
  111458. }
  111459. if (geometry instanceof BABYLON.BoxGeometry) {
  111460. serializationGeometries.boxes.push(geometry.serialize());
  111461. }
  111462. else if (geometry instanceof BABYLON.SphereGeometry) {
  111463. serializationGeometries.spheres.push(geometry.serialize());
  111464. }
  111465. else if (geometry instanceof BABYLON.CylinderGeometry) {
  111466. serializationGeometries.cylinders.push(geometry.serialize());
  111467. }
  111468. else if (geometry instanceof BABYLON.TorusGeometry) {
  111469. serializationGeometries.toruses.push(geometry.serialize());
  111470. }
  111471. else if (geometry instanceof BABYLON.GroundGeometry) {
  111472. serializationGeometries.grounds.push(geometry.serialize());
  111473. }
  111474. else if (geometry instanceof BABYLON.Plane) {
  111475. serializationGeometries.planes.push(geometry.serialize());
  111476. }
  111477. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  111478. serializationGeometries.torusKnots.push(geometry.serialize());
  111479. }
  111480. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  111481. throw new Error("Unknown primitive type");
  111482. }
  111483. else {
  111484. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  111485. }
  111486. serializedGeometries[geometry.id] = true;
  111487. };
  111488. var serializeMesh = function (mesh, serializationScene) {
  111489. var serializationObject = {};
  111490. // Geometry
  111491. var geometry = mesh._geometry;
  111492. if (geometry) {
  111493. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  111494. // 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
  111495. serializeGeometry(geometry, serializationScene.geometries);
  111496. }
  111497. }
  111498. // Custom
  111499. if (mesh.serialize) {
  111500. mesh.serialize(serializationObject);
  111501. }
  111502. return serializationObject;
  111503. };
  111504. var finalizeSingleMesh = function (mesh, serializationObject) {
  111505. //only works if the mesh is already loaded
  111506. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111507. //serialize material
  111508. if (mesh.material) {
  111509. if (mesh.material instanceof BABYLON.MultiMaterial) {
  111510. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  111511. serializationObject.materials = serializationObject.materials || [];
  111512. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111513. serializationObject.multiMaterials.push(mesh.material.serialize());
  111514. var _loop_1 = function (submaterial) {
  111515. if (submaterial) {
  111516. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  111517. serializationObject.materials.push(submaterial.serialize());
  111518. }
  111519. }
  111520. };
  111521. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  111522. var submaterial = _a[_i];
  111523. _loop_1(submaterial);
  111524. }
  111525. }
  111526. }
  111527. else {
  111528. serializationObject.materials = serializationObject.materials || [];
  111529. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111530. serializationObject.materials.push(mesh.material.serialize());
  111531. }
  111532. }
  111533. }
  111534. //serialize geometry
  111535. var geometry = mesh._geometry;
  111536. if (geometry) {
  111537. if (!serializationObject.geometries) {
  111538. serializationObject.geometries = {};
  111539. serializationObject.geometries.boxes = [];
  111540. serializationObject.geometries.spheres = [];
  111541. serializationObject.geometries.cylinders = [];
  111542. serializationObject.geometries.toruses = [];
  111543. serializationObject.geometries.grounds = [];
  111544. serializationObject.geometries.planes = [];
  111545. serializationObject.geometries.torusKnots = [];
  111546. serializationObject.geometries.vertexData = [];
  111547. }
  111548. serializeGeometry(geometry, serializationObject.geometries);
  111549. }
  111550. // Skeletons
  111551. if (mesh.skeleton) {
  111552. serializationObject.skeletons = serializationObject.skeletons || [];
  111553. serializationObject.skeletons.push(mesh.skeleton.serialize());
  111554. }
  111555. //serialize the actual mesh
  111556. serializationObject.meshes = serializationObject.meshes || [];
  111557. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111558. }
  111559. };
  111560. /**
  111561. * Class used to serialize a scene into a string
  111562. */
  111563. var SceneSerializer = /** @class */ (function () {
  111564. function SceneSerializer() {
  111565. }
  111566. /**
  111567. * Clear cache used by a previous serialization
  111568. */
  111569. SceneSerializer.ClearCache = function () {
  111570. serializedGeometries = [];
  111571. };
  111572. /**
  111573. * Serialize a scene into a JSON compatible object
  111574. * @param scene defines the scene to serialize
  111575. * @returns a JSON compatible object
  111576. */
  111577. SceneSerializer.Serialize = function (scene) {
  111578. var serializationObject = {};
  111579. SceneSerializer.ClearCache();
  111580. // Scene
  111581. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  111582. serializationObject.autoClear = scene.autoClear;
  111583. serializationObject.clearColor = scene.clearColor.asArray();
  111584. serializationObject.ambientColor = scene.ambientColor.asArray();
  111585. serializationObject.gravity = scene.gravity.asArray();
  111586. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  111587. serializationObject.workerCollisions = scene.workerCollisions;
  111588. // Fog
  111589. if (scene.fogMode && scene.fogMode !== 0) {
  111590. serializationObject.fogMode = scene.fogMode;
  111591. serializationObject.fogColor = scene.fogColor.asArray();
  111592. serializationObject.fogStart = scene.fogStart;
  111593. serializationObject.fogEnd = scene.fogEnd;
  111594. serializationObject.fogDensity = scene.fogDensity;
  111595. }
  111596. //Physics
  111597. if (scene.isPhysicsEnabled()) {
  111598. var physicEngine = scene.getPhysicsEngine();
  111599. if (physicEngine) {
  111600. serializationObject.physicsEnabled = true;
  111601. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  111602. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  111603. }
  111604. }
  111605. // Metadata
  111606. if (scene.metadata) {
  111607. serializationObject.metadata = scene.metadata;
  111608. }
  111609. // Morph targets
  111610. serializationObject.morphTargetManagers = [];
  111611. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  111612. var abstractMesh = _a[_i];
  111613. var manager = abstractMesh.morphTargetManager;
  111614. if (manager) {
  111615. serializationObject.morphTargetManagers.push(manager.serialize());
  111616. }
  111617. }
  111618. // Lights
  111619. serializationObject.lights = [];
  111620. var index;
  111621. var light;
  111622. for (index = 0; index < scene.lights.length; index++) {
  111623. light = scene.lights[index];
  111624. if (!light.doNotSerialize) {
  111625. serializationObject.lights.push(light.serialize());
  111626. }
  111627. }
  111628. // Cameras
  111629. serializationObject.cameras = [];
  111630. for (index = 0; index < scene.cameras.length; index++) {
  111631. var camera = scene.cameras[index];
  111632. if (!camera.doNotSerialize) {
  111633. serializationObject.cameras.push(camera.serialize());
  111634. }
  111635. }
  111636. if (scene.activeCamera) {
  111637. serializationObject.activeCameraID = scene.activeCamera.id;
  111638. }
  111639. // Animations
  111640. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  111641. // Materials
  111642. serializationObject.materials = [];
  111643. serializationObject.multiMaterials = [];
  111644. var material;
  111645. for (index = 0; index < scene.materials.length; index++) {
  111646. material = scene.materials[index];
  111647. if (!material.doNotSerialize) {
  111648. serializationObject.materials.push(material.serialize());
  111649. }
  111650. }
  111651. // MultiMaterials
  111652. serializationObject.multiMaterials = [];
  111653. for (index = 0; index < scene.multiMaterials.length; index++) {
  111654. var multiMaterial = scene.multiMaterials[index];
  111655. serializationObject.multiMaterials.push(multiMaterial.serialize());
  111656. }
  111657. // Environment texture
  111658. if (scene.environmentTexture) {
  111659. serializationObject.environmentTexture = scene.environmentTexture.name;
  111660. }
  111661. // Skeletons
  111662. serializationObject.skeletons = [];
  111663. for (index = 0; index < scene.skeletons.length; index++) {
  111664. var skeleton = scene.skeletons[index];
  111665. if (!skeleton.doNotSerialize) {
  111666. serializationObject.skeletons.push(skeleton.serialize());
  111667. }
  111668. }
  111669. // Transform nodes
  111670. serializationObject.transformNodes = [];
  111671. for (index = 0; index < scene.transformNodes.length; index++) {
  111672. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  111673. }
  111674. // Geometries
  111675. serializationObject.geometries = {};
  111676. serializationObject.geometries.boxes = [];
  111677. serializationObject.geometries.spheres = [];
  111678. serializationObject.geometries.cylinders = [];
  111679. serializationObject.geometries.toruses = [];
  111680. serializationObject.geometries.grounds = [];
  111681. serializationObject.geometries.planes = [];
  111682. serializationObject.geometries.torusKnots = [];
  111683. serializationObject.geometries.vertexData = [];
  111684. serializedGeometries = [];
  111685. var geometries = scene.getGeometries();
  111686. for (index = 0; index < geometries.length; index++) {
  111687. var geometry = geometries[index];
  111688. if (geometry.isReady()) {
  111689. serializeGeometry(geometry, serializationObject.geometries);
  111690. }
  111691. }
  111692. // Meshes
  111693. serializationObject.meshes = [];
  111694. for (index = 0; index < scene.meshes.length; index++) {
  111695. var abstractMesh = scene.meshes[index];
  111696. if (abstractMesh instanceof BABYLON.Mesh) {
  111697. var mesh = abstractMesh;
  111698. if (!mesh.doNotSerialize) {
  111699. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111700. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111701. }
  111702. }
  111703. }
  111704. }
  111705. // Particles Systems
  111706. serializationObject.particleSystems = [];
  111707. for (index = 0; index < scene.particleSystems.length; index++) {
  111708. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  111709. }
  111710. // Action Manager
  111711. if (scene.actionManager) {
  111712. serializationObject.actions = scene.actionManager.serialize("scene");
  111713. }
  111714. // Components
  111715. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  111716. var component = _c[_b];
  111717. component.serialize(serializationObject);
  111718. }
  111719. return serializationObject;
  111720. };
  111721. /**
  111722. * Serialize a mesh into a JSON compatible object
  111723. * @param toSerialize defines the mesh to serialize
  111724. * @param withParents defines if parents must be serialized as well
  111725. * @param withChildren defines if children must be serialized as well
  111726. * @returns a JSON compatible object
  111727. */
  111728. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  111729. if (withParents === void 0) { withParents = false; }
  111730. if (withChildren === void 0) { withChildren = false; }
  111731. var serializationObject = {};
  111732. SceneSerializer.ClearCache();
  111733. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  111734. if (withParents || withChildren) {
  111735. //deliberate for loop! not for each, appended should be processed as well.
  111736. for (var i = 0; i < toSerialize.length; ++i) {
  111737. if (withChildren) {
  111738. toSerialize[i].getDescendants().forEach(function (node) {
  111739. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  111740. toSerialize.push(node);
  111741. }
  111742. });
  111743. }
  111744. //make sure the array doesn't contain the object already
  111745. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  111746. toSerialize.push(toSerialize[i].parent);
  111747. }
  111748. }
  111749. }
  111750. toSerialize.forEach(function (mesh) {
  111751. finalizeSingleMesh(mesh, serializationObject);
  111752. });
  111753. return serializationObject;
  111754. };
  111755. return SceneSerializer;
  111756. }());
  111757. BABYLON.SceneSerializer = SceneSerializer;
  111758. })(BABYLON || (BABYLON = {}));
  111759. //# sourceMappingURL=babylon.sceneSerializer.js.map
  111760. var BABYLON;
  111761. (function (BABYLON) {
  111762. /**
  111763. * Class used to generate realtime reflection / refraction cube textures
  111764. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  111765. */
  111766. var ReflectionProbe = /** @class */ (function () {
  111767. /**
  111768. * Creates a new reflection probe
  111769. * @param name defines the name of the probe
  111770. * @param size defines the texture resolution (for each face)
  111771. * @param scene defines the hosting scene
  111772. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  111773. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  111774. */
  111775. function ReflectionProbe(
  111776. /** defines the name of the probe */
  111777. name, size, scene, generateMipMaps, useFloat) {
  111778. if (generateMipMaps === void 0) { generateMipMaps = true; }
  111779. if (useFloat === void 0) { useFloat = false; }
  111780. var _this = this;
  111781. this.name = name;
  111782. this._viewMatrix = BABYLON.Matrix.Identity();
  111783. this._target = BABYLON.Vector3.Zero();
  111784. this._add = BABYLON.Vector3.Zero();
  111785. this._invertYAxis = false;
  111786. /** Gets or sets probe position (center of the cube map) */
  111787. this.position = BABYLON.Vector3.Zero();
  111788. this._scene = scene;
  111789. // Create the scene field if not exist.
  111790. if (!this._scene.reflectionProbes) {
  111791. this._scene.reflectionProbes = new Array();
  111792. }
  111793. this._scene.reflectionProbes.push(this);
  111794. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  111795. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  111796. switch (faceIndex) {
  111797. case 0:
  111798. _this._add.copyFromFloats(1, 0, 0);
  111799. break;
  111800. case 1:
  111801. _this._add.copyFromFloats(-1, 0, 0);
  111802. break;
  111803. case 2:
  111804. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  111805. break;
  111806. case 3:
  111807. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  111808. break;
  111809. case 4:
  111810. _this._add.copyFromFloats(0, 0, 1);
  111811. break;
  111812. case 5:
  111813. _this._add.copyFromFloats(0, 0, -1);
  111814. break;
  111815. }
  111816. if (_this._attachedMesh) {
  111817. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  111818. }
  111819. _this.position.addToRef(_this._add, _this._target);
  111820. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  111821. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  111822. scene._forcedViewPosition = _this.position;
  111823. });
  111824. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  111825. scene._forcedViewPosition = null;
  111826. scene.updateTransformMatrix(true);
  111827. });
  111828. if (scene.activeCamera) {
  111829. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  111830. }
  111831. }
  111832. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  111833. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  111834. get: function () {
  111835. return this._renderTargetTexture.samples;
  111836. },
  111837. set: function (value) {
  111838. this._renderTargetTexture.samples = value;
  111839. },
  111840. enumerable: true,
  111841. configurable: true
  111842. });
  111843. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  111844. /** Gets or sets the refresh rate to use (on every frame by default) */
  111845. get: function () {
  111846. return this._renderTargetTexture.refreshRate;
  111847. },
  111848. set: function (value) {
  111849. this._renderTargetTexture.refreshRate = value;
  111850. },
  111851. enumerable: true,
  111852. configurable: true
  111853. });
  111854. /**
  111855. * Gets the hosting scene
  111856. * @returns a Scene
  111857. */
  111858. ReflectionProbe.prototype.getScene = function () {
  111859. return this._scene;
  111860. };
  111861. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  111862. /** Gets the internal CubeTexture used to render to */
  111863. get: function () {
  111864. return this._renderTargetTexture;
  111865. },
  111866. enumerable: true,
  111867. configurable: true
  111868. });
  111869. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  111870. /** Gets the list of meshes to render */
  111871. get: function () {
  111872. return this._renderTargetTexture.renderList;
  111873. },
  111874. enumerable: true,
  111875. configurable: true
  111876. });
  111877. /**
  111878. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  111879. * @param mesh defines the mesh to attach to
  111880. */
  111881. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  111882. this._attachedMesh = mesh;
  111883. };
  111884. /**
  111885. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  111886. * @param renderingGroupId The rendering group id corresponding to its index
  111887. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  111888. */
  111889. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  111890. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  111891. };
  111892. /**
  111893. * Clean all associated resources
  111894. */
  111895. ReflectionProbe.prototype.dispose = function () {
  111896. var index = this._scene.reflectionProbes.indexOf(this);
  111897. if (index !== -1) {
  111898. // Remove from the scene if found
  111899. this._scene.reflectionProbes.splice(index, 1);
  111900. }
  111901. if (this._renderTargetTexture) {
  111902. this._renderTargetTexture.dispose();
  111903. this._renderTargetTexture = null;
  111904. }
  111905. };
  111906. return ReflectionProbe;
  111907. }());
  111908. BABYLON.ReflectionProbe = ReflectionProbe;
  111909. })(BABYLON || (BABYLON = {}));
  111910. //# sourceMappingURL=babylon.reflectionProbe.js.map
  111911. var BABYLON;
  111912. (function (BABYLON) {
  111913. /**
  111914. * Defines the layer scene component responsible to manage any layers
  111915. * in a given scene.
  111916. */
  111917. var LayerSceneComponent = /** @class */ (function () {
  111918. /**
  111919. * Creates a new instance of the component for the given scene
  111920. * @param scene Defines the scene to register the component in
  111921. */
  111922. function LayerSceneComponent(scene) {
  111923. /**
  111924. * The component name helpfull to identify the component in the list of scene components.
  111925. */
  111926. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  111927. this.scene = scene;
  111928. this._engine = scene.getEngine();
  111929. scene.layers = new Array();
  111930. }
  111931. /**
  111932. * Registers the component in a given scene
  111933. */
  111934. LayerSceneComponent.prototype.register = function () {
  111935. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  111936. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  111937. };
  111938. /**
  111939. * Rebuilds the elements related to this component in case of
  111940. * context lost for instance.
  111941. */
  111942. LayerSceneComponent.prototype.rebuild = function () {
  111943. var layers = this.scene.layers;
  111944. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  111945. var layer = layers_1[_i];
  111946. layer._rebuild();
  111947. }
  111948. };
  111949. /**
  111950. * Disposes the component and the associated ressources.
  111951. */
  111952. LayerSceneComponent.prototype.dispose = function () {
  111953. var layers = this.scene.layers;
  111954. while (layers.length) {
  111955. layers[0].dispose();
  111956. }
  111957. };
  111958. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  111959. var layers = this.scene.layers;
  111960. if (layers.length) {
  111961. this._engine.setDepthBuffer(false);
  111962. var cameraLayerMask = camera.layerMask;
  111963. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111964. var layer = layers_2[_i];
  111965. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  111966. layer.render();
  111967. }
  111968. }
  111969. this._engine.setDepthBuffer(true);
  111970. }
  111971. };
  111972. LayerSceneComponent.prototype._drawBackground = function (camera) {
  111973. this._draw(camera, true);
  111974. };
  111975. LayerSceneComponent.prototype._drawForeground = function (camera) {
  111976. this._draw(camera, false);
  111977. };
  111978. return LayerSceneComponent;
  111979. }());
  111980. BABYLON.LayerSceneComponent = LayerSceneComponent;
  111981. })(BABYLON || (BABYLON = {}));
  111982. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  111983. var BABYLON;
  111984. (function (BABYLON) {
  111985. /**
  111986. * This represents a full screen 2d layer.
  111987. * This can be usefull to display a picture in the background of your scene for instance.
  111988. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111989. */
  111990. var Layer = /** @class */ (function () {
  111991. /**
  111992. * Instantiates a new layer.
  111993. * This represents a full screen 2d layer.
  111994. * This can be usefull to display a picture in the background of your scene for instance.
  111995. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111996. * @param name Define the name of the layer in the scene
  111997. * @param imgUrl Define the url of the texture to display in the layer
  111998. * @param scene Define the scene the layer belongs to
  111999. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  112000. * @param color Defines a color for the layer
  112001. */
  112002. function Layer(
  112003. /**
  112004. * Define the name of the layer.
  112005. */
  112006. name, imgUrl, scene, isBackground, color) {
  112007. this.name = name;
  112008. /**
  112009. * Define the scale of the layer in order to zoom in out of the texture.
  112010. */
  112011. this.scale = new BABYLON.Vector2(1, 1);
  112012. /**
  112013. * Define an offset for the layer in order to shift the texture.
  112014. */
  112015. this.offset = new BABYLON.Vector2(0, 0);
  112016. /**
  112017. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  112018. */
  112019. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  112020. /**
  112021. * Define a mask to restrict the layer to only some of the scene cameras.
  112022. */
  112023. this.layerMask = 0x0FFFFFFF;
  112024. this._vertexBuffers = {};
  112025. /**
  112026. * An event triggered when the layer is disposed.
  112027. */
  112028. this.onDisposeObservable = new BABYLON.Observable();
  112029. /**
  112030. * An event triggered before rendering the scene
  112031. */
  112032. this.onBeforeRenderObservable = new BABYLON.Observable();
  112033. /**
  112034. * An event triggered after rendering the scene
  112035. */
  112036. this.onAfterRenderObservable = new BABYLON.Observable();
  112037. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  112038. this.isBackground = isBackground === undefined ? true : isBackground;
  112039. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  112040. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  112041. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  112042. if (!layerComponent) {
  112043. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  112044. this._scene._addComponent(layerComponent);
  112045. }
  112046. this._scene.layers.push(this);
  112047. var engine = this._scene.getEngine();
  112048. // VBO
  112049. var vertices = [];
  112050. vertices.push(1, 1);
  112051. vertices.push(-1, 1);
  112052. vertices.push(-1, -1);
  112053. vertices.push(1, -1);
  112054. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  112055. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  112056. this._createIndexBuffer();
  112057. // Effects
  112058. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  112059. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  112060. }
  112061. Object.defineProperty(Layer.prototype, "onDispose", {
  112062. /**
  112063. * Back compatibility with callback before the onDisposeObservable existed.
  112064. * The set callback will be triggered when the layer has been disposed.
  112065. */
  112066. set: function (callback) {
  112067. if (this._onDisposeObserver) {
  112068. this.onDisposeObservable.remove(this._onDisposeObserver);
  112069. }
  112070. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  112071. },
  112072. enumerable: true,
  112073. configurable: true
  112074. });
  112075. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  112076. /**
  112077. * Back compatibility with callback before the onBeforeRenderObservable existed.
  112078. * The set callback will be triggered just before rendering the layer.
  112079. */
  112080. set: function (callback) {
  112081. if (this._onBeforeRenderObserver) {
  112082. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  112083. }
  112084. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  112085. },
  112086. enumerable: true,
  112087. configurable: true
  112088. });
  112089. Object.defineProperty(Layer.prototype, "onAfterRender", {
  112090. /**
  112091. * Back compatibility with callback before the onAfterRenderObservable existed.
  112092. * The set callback will be triggered just after rendering the layer.
  112093. */
  112094. set: function (callback) {
  112095. if (this._onAfterRenderObserver) {
  112096. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  112097. }
  112098. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  112099. },
  112100. enumerable: true,
  112101. configurable: true
  112102. });
  112103. Layer.prototype._createIndexBuffer = function () {
  112104. var engine = this._scene.getEngine();
  112105. // Indices
  112106. var indices = [];
  112107. indices.push(0);
  112108. indices.push(1);
  112109. indices.push(2);
  112110. indices.push(0);
  112111. indices.push(2);
  112112. indices.push(3);
  112113. this._indexBuffer = engine.createIndexBuffer(indices);
  112114. };
  112115. /** @hidden */
  112116. Layer.prototype._rebuild = function () {
  112117. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112118. if (vb) {
  112119. vb._rebuild();
  112120. }
  112121. this._createIndexBuffer();
  112122. };
  112123. /**
  112124. * Renders the layer in the scene.
  112125. */
  112126. Layer.prototype.render = function () {
  112127. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  112128. // Check
  112129. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  112130. return;
  112131. }
  112132. var engine = this._scene.getEngine();
  112133. this.onBeforeRenderObservable.notifyObservers(this);
  112134. // Render
  112135. engine.enableEffect(currentEffect);
  112136. engine.setState(false);
  112137. // Texture
  112138. currentEffect.setTexture("textureSampler", this.texture);
  112139. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  112140. // Color
  112141. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  112142. // Scale / offset
  112143. currentEffect.setVector2("offset", this.offset);
  112144. currentEffect.setVector2("scale", this.scale);
  112145. // VBOs
  112146. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  112147. // Draw order
  112148. if (!this.alphaTest) {
  112149. engine.setAlphaMode(this.alphaBlendingMode);
  112150. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112151. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  112152. }
  112153. else {
  112154. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112155. }
  112156. this.onAfterRenderObservable.notifyObservers(this);
  112157. };
  112158. /**
  112159. * Disposes and releases the associated ressources.
  112160. */
  112161. Layer.prototype.dispose = function () {
  112162. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  112163. if (vertexBuffer) {
  112164. vertexBuffer.dispose();
  112165. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  112166. }
  112167. if (this._indexBuffer) {
  112168. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  112169. this._indexBuffer = null;
  112170. }
  112171. if (this.texture) {
  112172. this.texture.dispose();
  112173. this.texture = null;
  112174. }
  112175. // Remove from scene
  112176. var index = this._scene.layers.indexOf(this);
  112177. this._scene.layers.splice(index, 1);
  112178. // Callback
  112179. this.onDisposeObservable.notifyObservers(this);
  112180. this.onDisposeObservable.clear();
  112181. this.onAfterRenderObservable.clear();
  112182. this.onBeforeRenderObservable.clear();
  112183. };
  112184. return Layer;
  112185. }());
  112186. BABYLON.Layer = Layer;
  112187. })(BABYLON || (BABYLON = {}));
  112188. //# sourceMappingURL=babylon.layer.js.map
  112189. var BABYLON;
  112190. (function (BABYLON) {
  112191. /**
  112192. * Class used to host texture specific utilities
  112193. */
  112194. var TextureTools = /** @class */ (function () {
  112195. function TextureTools() {
  112196. }
  112197. /**
  112198. * Uses the GPU to create a copy texture rescaled at a given size
  112199. * @param texture Texture to copy from
  112200. * @param width defines the desired width
  112201. * @param height defines the desired height
  112202. * @param useBilinearMode defines if bilinear mode has to be used
  112203. * @return the generated texture
  112204. */
  112205. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  112206. if (useBilinearMode === void 0) { useBilinearMode = true; }
  112207. var scene = texture.getScene();
  112208. var engine = scene.getEngine();
  112209. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  112210. rtt.wrapU = texture.wrapU;
  112211. rtt.wrapV = texture.wrapV;
  112212. rtt.uOffset = texture.uOffset;
  112213. rtt.vOffset = texture.vOffset;
  112214. rtt.uScale = texture.uScale;
  112215. rtt.vScale = texture.vScale;
  112216. rtt.uAng = texture.uAng;
  112217. rtt.vAng = texture.vAng;
  112218. rtt.wAng = texture.wAng;
  112219. rtt.coordinatesIndex = texture.coordinatesIndex;
  112220. rtt.level = texture.level;
  112221. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  112222. rtt._texture.isReady = false;
  112223. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112224. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112225. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  112226. passPostProcess.getEffect().executeWhenCompiled(function () {
  112227. passPostProcess.onApply = function (effect) {
  112228. effect.setTexture("textureSampler", texture);
  112229. };
  112230. var internalTexture = rtt.getInternalTexture();
  112231. if (internalTexture) {
  112232. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  112233. engine.unBindFramebuffer(internalTexture);
  112234. rtt.disposeFramebufferObjects();
  112235. passPostProcess.dispose();
  112236. internalTexture.isReady = true;
  112237. }
  112238. });
  112239. return rtt;
  112240. };
  112241. /**
  112242. * Gets an environment BRDF texture for a given scene
  112243. * @param scene defines the hosting scene
  112244. * @returns the environment BRDF texture
  112245. */
  112246. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  112247. if (!scene._environmentBRDFTexture) {
  112248. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112249. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112250. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112251. scene._environmentBRDFTexture = texture;
  112252. }
  112253. return scene._environmentBRDFTexture;
  112254. };
  112255. 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=";
  112256. return TextureTools;
  112257. }());
  112258. BABYLON.TextureTools = TextureTools;
  112259. })(BABYLON || (BABYLON = {}));
  112260. //# sourceMappingURL=babylon.textureTools.js.map
  112261. var BABYLON;
  112262. (function (BABYLON) {
  112263. /**
  112264. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  112265. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  112266. */
  112267. var FramingBehavior = /** @class */ (function () {
  112268. function FramingBehavior() {
  112269. this._mode = FramingBehavior.FitFrustumSidesMode;
  112270. this._radiusScale = 1.0;
  112271. this._positionScale = 0.5;
  112272. this._defaultElevation = 0.3;
  112273. this._elevationReturnTime = 1500;
  112274. this._elevationReturnWaitTime = 1000;
  112275. this._zoomStopsAnimation = false;
  112276. this._framingTime = 1500;
  112277. /**
  112278. * Define if the behavior should automatically change the configured
  112279. * camera limits and sensibilities.
  112280. */
  112281. this.autoCorrectCameraLimitsAndSensibility = true;
  112282. this._isPointerDown = false;
  112283. this._lastInteractionTime = -Infinity;
  112284. // Framing control
  112285. this._animatables = new Array();
  112286. this._betaIsAnimating = false;
  112287. }
  112288. Object.defineProperty(FramingBehavior.prototype, "name", {
  112289. /**
  112290. * Gets the name of the behavior.
  112291. */
  112292. get: function () {
  112293. return "Framing";
  112294. },
  112295. enumerable: true,
  112296. configurable: true
  112297. });
  112298. Object.defineProperty(FramingBehavior.prototype, "mode", {
  112299. /**
  112300. * Gets current mode used by the behavior.
  112301. */
  112302. get: function () {
  112303. return this._mode;
  112304. },
  112305. /**
  112306. * Sets the current mode used by the behavior
  112307. */
  112308. set: function (mode) {
  112309. this._mode = mode;
  112310. },
  112311. enumerable: true,
  112312. configurable: true
  112313. });
  112314. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  112315. /**
  112316. * Gets the scale applied to the radius
  112317. */
  112318. get: function () {
  112319. return this._radiusScale;
  112320. },
  112321. /**
  112322. * Sets the scale applied to the radius (1 by default)
  112323. */
  112324. set: function (radius) {
  112325. this._radiusScale = radius;
  112326. },
  112327. enumerable: true,
  112328. configurable: true
  112329. });
  112330. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  112331. /**
  112332. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112333. */
  112334. get: function () {
  112335. return this._positionScale;
  112336. },
  112337. /**
  112338. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112339. */
  112340. set: function (scale) {
  112341. this._positionScale = scale;
  112342. },
  112343. enumerable: true,
  112344. configurable: true
  112345. });
  112346. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  112347. /**
  112348. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112349. * behaviour is triggered, in radians.
  112350. */
  112351. get: function () {
  112352. return this._defaultElevation;
  112353. },
  112354. /**
  112355. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112356. * behaviour is triggered, in radians.
  112357. */
  112358. set: function (elevation) {
  112359. this._defaultElevation = elevation;
  112360. },
  112361. enumerable: true,
  112362. configurable: true
  112363. });
  112364. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  112365. /**
  112366. * Gets the time (in milliseconds) taken to return to the default beta position.
  112367. * Negative value indicates camera should not return to default.
  112368. */
  112369. get: function () {
  112370. return this._elevationReturnTime;
  112371. },
  112372. /**
  112373. * Sets the time (in milliseconds) taken to return to the default beta position.
  112374. * Negative value indicates camera should not return to default.
  112375. */
  112376. set: function (speed) {
  112377. this._elevationReturnTime = speed;
  112378. },
  112379. enumerable: true,
  112380. configurable: true
  112381. });
  112382. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  112383. /**
  112384. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112385. */
  112386. get: function () {
  112387. return this._elevationReturnWaitTime;
  112388. },
  112389. /**
  112390. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112391. */
  112392. set: function (time) {
  112393. this._elevationReturnWaitTime = time;
  112394. },
  112395. enumerable: true,
  112396. configurable: true
  112397. });
  112398. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  112399. /**
  112400. * Gets the flag that indicates if user zooming should stop animation.
  112401. */
  112402. get: function () {
  112403. return this._zoomStopsAnimation;
  112404. },
  112405. /**
  112406. * Sets the flag that indicates if user zooming should stop animation.
  112407. */
  112408. set: function (flag) {
  112409. this._zoomStopsAnimation = flag;
  112410. },
  112411. enumerable: true,
  112412. configurable: true
  112413. });
  112414. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  112415. /**
  112416. * Gets the transition time when framing the mesh, in milliseconds
  112417. */
  112418. get: function () {
  112419. return this._framingTime;
  112420. },
  112421. /**
  112422. * Sets the transition time when framing the mesh, in milliseconds
  112423. */
  112424. set: function (time) {
  112425. this._framingTime = time;
  112426. },
  112427. enumerable: true,
  112428. configurable: true
  112429. });
  112430. /**
  112431. * Initializes the behavior.
  112432. */
  112433. FramingBehavior.prototype.init = function () {
  112434. // Do notihng
  112435. };
  112436. /**
  112437. * Attaches the behavior to its arc rotate camera.
  112438. * @param camera Defines the camera to attach the behavior to
  112439. */
  112440. FramingBehavior.prototype.attach = function (camera) {
  112441. var _this = this;
  112442. this._attachedCamera = camera;
  112443. var scene = this._attachedCamera.getScene();
  112444. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  112445. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112446. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112447. _this._isPointerDown = true;
  112448. return;
  112449. }
  112450. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112451. _this._isPointerDown = false;
  112452. }
  112453. });
  112454. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112455. if (mesh) {
  112456. _this.zoomOnMesh(mesh);
  112457. }
  112458. });
  112459. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112460. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112461. _this._applyUserInteraction();
  112462. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  112463. // back to the default position after a given timeout
  112464. _this._maintainCameraAboveGround();
  112465. });
  112466. };
  112467. /**
  112468. * Detaches the behavior from its current arc rotate camera.
  112469. */
  112470. FramingBehavior.prototype.detach = function () {
  112471. if (!this._attachedCamera) {
  112472. return;
  112473. }
  112474. var scene = this._attachedCamera.getScene();
  112475. if (this._onPrePointerObservableObserver) {
  112476. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112477. }
  112478. if (this._onAfterCheckInputsObserver) {
  112479. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112480. }
  112481. if (this._onMeshTargetChangedObserver) {
  112482. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112483. }
  112484. this._attachedCamera = null;
  112485. };
  112486. /**
  112487. * Targets the given mesh and updates zoom level accordingly.
  112488. * @param mesh The mesh to target.
  112489. * @param radius Optional. If a cached radius position already exists, overrides default.
  112490. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112491. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112492. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112493. */
  112494. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112495. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112496. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112497. mesh.computeWorldMatrix(true);
  112498. var boundingBox = mesh.getBoundingInfo().boundingBox;
  112499. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  112500. };
  112501. /**
  112502. * Targets the given mesh with its children and updates zoom level accordingly.
  112503. * @param mesh The mesh to target.
  112504. * @param radius Optional. If a cached radius position already exists, overrides default.
  112505. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112506. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112507. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112508. */
  112509. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112510. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112511. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112512. mesh.computeWorldMatrix(true);
  112513. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  112514. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  112515. };
  112516. /**
  112517. * Targets the given meshes with their children and updates zoom level accordingly.
  112518. * @param meshes The mesh to target.
  112519. * @param radius Optional. If a cached radius position already exists, overrides default.
  112520. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112521. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112522. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112523. */
  112524. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  112525. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112526. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112527. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  112528. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  112529. for (var i = 0; i < meshes.length; i++) {
  112530. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  112531. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  112532. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  112533. }
  112534. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  112535. };
  112536. /**
  112537. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  112538. * @param minimumWorld Determines the smaller position of the bounding box extend
  112539. * @param maximumWorld Determines the bigger position of the bounding box extend
  112540. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112541. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112542. */
  112543. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  112544. var _this = this;
  112545. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112546. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112547. var zoomTarget;
  112548. if (!this._attachedCamera) {
  112549. return;
  112550. }
  112551. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  112552. var bottom = minimumWorld.y;
  112553. var top = maximumWorld.y;
  112554. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  112555. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  112556. if (focusOnOriginXZ) {
  112557. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  112558. }
  112559. else {
  112560. var centerWorld = minimumWorld.add(radiusWorld);
  112561. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  112562. }
  112563. if (!this._vectorTransition) {
  112564. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  112565. }
  112566. this._betaIsAnimating = true;
  112567. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  112568. if (animatable) {
  112569. this._animatables.push(animatable);
  112570. }
  112571. // sets the radius and lower radius bounds
  112572. // Small delta ensures camera is not always at lower zoom limit.
  112573. var radius = 0;
  112574. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  112575. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112576. if (this.autoCorrectCameraLimitsAndSensibility) {
  112577. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  112578. }
  112579. radius = position;
  112580. }
  112581. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112582. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112583. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  112584. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  112585. }
  112586. }
  112587. // Set sensibilities
  112588. if (this.autoCorrectCameraLimitsAndSensibility) {
  112589. var extend = maximumWorld.subtract(minimumWorld).length();
  112590. this._attachedCamera.panningSensibility = 5000 / extend;
  112591. this._attachedCamera.wheelPrecision = 100 / radius;
  112592. }
  112593. // transition to new radius
  112594. if (!this._radiusTransition) {
  112595. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112596. }
  112597. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  112598. _this.stopAllAnimations();
  112599. if (onAnimationEnd) {
  112600. onAnimationEnd();
  112601. }
  112602. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  112603. _this._attachedCamera.storeState();
  112604. }
  112605. });
  112606. if (animatable) {
  112607. this._animatables.push(animatable);
  112608. }
  112609. };
  112610. /**
  112611. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  112612. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  112613. * frustum width.
  112614. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  112615. * to fully enclose the mesh in the viewing frustum.
  112616. */
  112617. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  112618. var size = maximumWorld.subtract(minimumWorld);
  112619. var boxVectorGlobalDiagonal = size.length();
  112620. var frustumSlope = this._getFrustumSlope();
  112621. // Formula for setting distance
  112622. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  112623. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  112624. // Horizon distance
  112625. var radius = radiusWithoutFraming * this._radiusScale;
  112626. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  112627. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  112628. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  112629. var camera = this._attachedCamera;
  112630. if (!camera) {
  112631. return 0;
  112632. }
  112633. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112634. // Don't exceed the requested limit
  112635. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  112636. }
  112637. // Don't exceed the upper radius limit
  112638. if (camera.upperRadiusLimit) {
  112639. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  112640. }
  112641. return distance;
  112642. };
  112643. /**
  112644. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  112645. * is automatically returned to its default position (expected to be above ground plane).
  112646. */
  112647. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  112648. var _this = this;
  112649. if (this._elevationReturnTime < 0) {
  112650. return;
  112651. }
  112652. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  112653. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  112654. var limitBeta = Math.PI * 0.5;
  112655. // Bring the camera back up if below the ground plane
  112656. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  112657. this._betaIsAnimating = true;
  112658. //Transition to new position
  112659. this.stopAllAnimations();
  112660. if (!this._betaTransition) {
  112661. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112662. }
  112663. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  112664. _this._clearAnimationLocks();
  112665. _this.stopAllAnimations();
  112666. });
  112667. if (animatabe) {
  112668. this._animatables.push(animatabe);
  112669. }
  112670. }
  112671. };
  112672. /**
  112673. * Returns the frustum slope based on the canvas ratio and camera FOV
  112674. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  112675. */
  112676. FramingBehavior.prototype._getFrustumSlope = function () {
  112677. // Calculate the viewport ratio
  112678. // Aspect Ratio is Height/Width.
  112679. var camera = this._attachedCamera;
  112680. if (!camera) {
  112681. return BABYLON.Vector2.Zero();
  112682. }
  112683. var engine = camera.getScene().getEngine();
  112684. var aspectRatio = engine.getAspectRatio(camera);
  112685. // Camera FOV is the vertical field of view (top-bottom) in radians.
  112686. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  112687. var frustumSlopeY = Math.tan(camera.fov / 2);
  112688. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  112689. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  112690. // along the forward vector.
  112691. var frustumSlopeX = frustumSlopeY * aspectRatio;
  112692. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  112693. };
  112694. /**
  112695. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  112696. */
  112697. FramingBehavior.prototype._clearAnimationLocks = function () {
  112698. this._betaIsAnimating = false;
  112699. };
  112700. /**
  112701. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112702. */
  112703. FramingBehavior.prototype._applyUserInteraction = function () {
  112704. if (this.isUserIsMoving) {
  112705. this._lastInteractionTime = BABYLON.Tools.Now;
  112706. this.stopAllAnimations();
  112707. this._clearAnimationLocks();
  112708. }
  112709. };
  112710. /**
  112711. * Stops and removes all animations that have been applied to the camera
  112712. */
  112713. FramingBehavior.prototype.stopAllAnimations = function () {
  112714. if (this._attachedCamera) {
  112715. this._attachedCamera.animations = [];
  112716. }
  112717. while (this._animatables.length) {
  112718. if (this._animatables[0]) {
  112719. this._animatables[0].onAnimationEnd = null;
  112720. this._animatables[0].stop();
  112721. }
  112722. this._animatables.shift();
  112723. }
  112724. };
  112725. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  112726. /**
  112727. * Gets a value indicating if the user is moving the camera
  112728. */
  112729. get: function () {
  112730. if (!this._attachedCamera) {
  112731. return false;
  112732. }
  112733. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112734. this._attachedCamera.inertialBetaOffset !== 0 ||
  112735. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112736. this._attachedCamera.inertialPanningX !== 0 ||
  112737. this._attachedCamera.inertialPanningY !== 0 ||
  112738. this._isPointerDown;
  112739. },
  112740. enumerable: true,
  112741. configurable: true
  112742. });
  112743. /**
  112744. * The easing function used by animations
  112745. */
  112746. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  112747. /**
  112748. * The easing mode used by animations
  112749. */
  112750. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  112751. // Statics
  112752. /**
  112753. * The camera can move all the way towards the mesh.
  112754. */
  112755. FramingBehavior.IgnoreBoundsSizeMode = 0;
  112756. /**
  112757. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  112758. */
  112759. FramingBehavior.FitFrustumSidesMode = 1;
  112760. return FramingBehavior;
  112761. }());
  112762. BABYLON.FramingBehavior = FramingBehavior;
  112763. })(BABYLON || (BABYLON = {}));
  112764. //# sourceMappingURL=babylon.framingBehavior.js.map
  112765. var BABYLON;
  112766. (function (BABYLON) {
  112767. /**
  112768. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  112769. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  112770. */
  112771. var BouncingBehavior = /** @class */ (function () {
  112772. function BouncingBehavior() {
  112773. /**
  112774. * The duration of the animation, in milliseconds
  112775. */
  112776. this.transitionDuration = 450;
  112777. /**
  112778. * Length of the distance animated by the transition when lower radius is reached
  112779. */
  112780. this.lowerRadiusTransitionRange = 2;
  112781. /**
  112782. * Length of the distance animated by the transition when upper radius is reached
  112783. */
  112784. this.upperRadiusTransitionRange = -2;
  112785. this._autoTransitionRange = false;
  112786. // Animations
  112787. this._radiusIsAnimating = false;
  112788. this._radiusBounceTransition = null;
  112789. this._animatables = new Array();
  112790. }
  112791. Object.defineProperty(BouncingBehavior.prototype, "name", {
  112792. /**
  112793. * Gets the name of the behavior.
  112794. */
  112795. get: function () {
  112796. return "Bouncing";
  112797. },
  112798. enumerable: true,
  112799. configurable: true
  112800. });
  112801. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  112802. /**
  112803. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112804. */
  112805. get: function () {
  112806. return this._autoTransitionRange;
  112807. },
  112808. /**
  112809. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112810. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  112811. */
  112812. set: function (value) {
  112813. var _this = this;
  112814. if (this._autoTransitionRange === value) {
  112815. return;
  112816. }
  112817. this._autoTransitionRange = value;
  112818. var camera = this._attachedCamera;
  112819. if (!camera) {
  112820. return;
  112821. }
  112822. if (value) {
  112823. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112824. if (!mesh) {
  112825. return;
  112826. }
  112827. mesh.computeWorldMatrix(true);
  112828. var diagonal = mesh.getBoundingInfo().diagonalLength;
  112829. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  112830. _this.upperRadiusTransitionRange = diagonal * 0.05;
  112831. });
  112832. }
  112833. else if (this._onMeshTargetChangedObserver) {
  112834. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112835. }
  112836. },
  112837. enumerable: true,
  112838. configurable: true
  112839. });
  112840. /**
  112841. * Initializes the behavior.
  112842. */
  112843. BouncingBehavior.prototype.init = function () {
  112844. // Do notihng
  112845. };
  112846. /**
  112847. * Attaches the behavior to its arc rotate camera.
  112848. * @param camera Defines the camera to attach the behavior to
  112849. */
  112850. BouncingBehavior.prototype.attach = function (camera) {
  112851. var _this = this;
  112852. this._attachedCamera = camera;
  112853. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112854. if (!_this._attachedCamera) {
  112855. return;
  112856. }
  112857. // Add the bounce animation to the lower radius limit
  112858. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  112859. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  112860. }
  112861. // Add the bounce animation to the upper radius limit
  112862. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  112863. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  112864. }
  112865. });
  112866. };
  112867. /**
  112868. * Detaches the behavior from its current arc rotate camera.
  112869. */
  112870. BouncingBehavior.prototype.detach = function () {
  112871. if (!this._attachedCamera) {
  112872. return;
  112873. }
  112874. if (this._onAfterCheckInputsObserver) {
  112875. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112876. }
  112877. if (this._onMeshTargetChangedObserver) {
  112878. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112879. }
  112880. this._attachedCamera = null;
  112881. };
  112882. /**
  112883. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  112884. * @param radiusLimit The limit to check against.
  112885. * @return Bool to indicate if at limit.
  112886. */
  112887. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  112888. if (!this._attachedCamera) {
  112889. return false;
  112890. }
  112891. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  112892. return true;
  112893. }
  112894. return false;
  112895. };
  112896. /**
  112897. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  112898. * @param radiusDelta The delta by which to animate to. Can be negative.
  112899. */
  112900. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  112901. var _this = this;
  112902. if (!this._attachedCamera) {
  112903. return;
  112904. }
  112905. if (!this._radiusBounceTransition) {
  112906. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  112907. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  112908. }
  112909. // Prevent zoom until bounce has completed
  112910. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  112911. this._attachedCamera.wheelPrecision = Infinity;
  112912. this._attachedCamera.inertialRadiusOffset = 0;
  112913. // Animate to the radius limit
  112914. this.stopAllAnimations();
  112915. this._radiusIsAnimating = true;
  112916. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  112917. if (animatable) {
  112918. this._animatables.push(animatable);
  112919. }
  112920. };
  112921. /**
  112922. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  112923. */
  112924. BouncingBehavior.prototype._clearAnimationLocks = function () {
  112925. this._radiusIsAnimating = false;
  112926. if (this._attachedCamera) {
  112927. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  112928. }
  112929. };
  112930. /**
  112931. * Stops and removes all animations that have been applied to the camera
  112932. */
  112933. BouncingBehavior.prototype.stopAllAnimations = function () {
  112934. if (this._attachedCamera) {
  112935. this._attachedCamera.animations = [];
  112936. }
  112937. while (this._animatables.length) {
  112938. this._animatables[0].onAnimationEnd = null;
  112939. this._animatables[0].stop();
  112940. this._animatables.shift();
  112941. }
  112942. };
  112943. /**
  112944. * The easing function used by animations
  112945. */
  112946. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  112947. /**
  112948. * The easing mode used by animations
  112949. */
  112950. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  112951. return BouncingBehavior;
  112952. }());
  112953. BABYLON.BouncingBehavior = BouncingBehavior;
  112954. })(BABYLON || (BABYLON = {}));
  112955. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  112956. var BABYLON;
  112957. (function (BABYLON) {
  112958. /**
  112959. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  112960. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  112961. */
  112962. var AutoRotationBehavior = /** @class */ (function () {
  112963. function AutoRotationBehavior() {
  112964. this._zoomStopsAnimation = false;
  112965. this._idleRotationSpeed = 0.05;
  112966. this._idleRotationWaitTime = 2000;
  112967. this._idleRotationSpinupTime = 2000;
  112968. this._isPointerDown = false;
  112969. this._lastFrameTime = null;
  112970. this._lastInteractionTime = -Infinity;
  112971. this._cameraRotationSpeed = 0;
  112972. this._lastFrameRadius = 0;
  112973. }
  112974. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  112975. /**
  112976. * Gets the name of the behavior.
  112977. */
  112978. get: function () {
  112979. return "AutoRotation";
  112980. },
  112981. enumerable: true,
  112982. configurable: true
  112983. });
  112984. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  112985. /**
  112986. * Gets the flag that indicates if user zooming should stop animation.
  112987. */
  112988. get: function () {
  112989. return this._zoomStopsAnimation;
  112990. },
  112991. /**
  112992. * Sets the flag that indicates if user zooming should stop animation.
  112993. */
  112994. set: function (flag) {
  112995. this._zoomStopsAnimation = flag;
  112996. },
  112997. enumerable: true,
  112998. configurable: true
  112999. });
  113000. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  113001. /**
  113002. * Gets the default speed at which the camera rotates around the model.
  113003. */
  113004. get: function () {
  113005. return this._idleRotationSpeed;
  113006. },
  113007. /**
  113008. * Sets the default speed at which the camera rotates around the model.
  113009. */
  113010. set: function (speed) {
  113011. this._idleRotationSpeed = speed;
  113012. },
  113013. enumerable: true,
  113014. configurable: true
  113015. });
  113016. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  113017. /**
  113018. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  113019. */
  113020. get: function () {
  113021. return this._idleRotationWaitTime;
  113022. },
  113023. /**
  113024. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  113025. */
  113026. set: function (time) {
  113027. this._idleRotationWaitTime = time;
  113028. },
  113029. enumerable: true,
  113030. configurable: true
  113031. });
  113032. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  113033. /**
  113034. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  113035. */
  113036. get: function () {
  113037. return this._idleRotationSpinupTime;
  113038. },
  113039. /**
  113040. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  113041. */
  113042. set: function (time) {
  113043. this._idleRotationSpinupTime = time;
  113044. },
  113045. enumerable: true,
  113046. configurable: true
  113047. });
  113048. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  113049. /**
  113050. * Gets a value indicating if the camera is currently rotating because of this behavior
  113051. */
  113052. get: function () {
  113053. return Math.abs(this._cameraRotationSpeed) > 0;
  113054. },
  113055. enumerable: true,
  113056. configurable: true
  113057. });
  113058. /**
  113059. * Initializes the behavior.
  113060. */
  113061. AutoRotationBehavior.prototype.init = function () {
  113062. // Do notihng
  113063. };
  113064. /**
  113065. * Attaches the behavior to its arc rotate camera.
  113066. * @param camera Defines the camera to attach the behavior to
  113067. */
  113068. AutoRotationBehavior.prototype.attach = function (camera) {
  113069. var _this = this;
  113070. this._attachedCamera = camera;
  113071. var scene = this._attachedCamera.getScene();
  113072. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  113073. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  113074. _this._isPointerDown = true;
  113075. return;
  113076. }
  113077. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  113078. _this._isPointerDown = false;
  113079. }
  113080. });
  113081. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  113082. var now = BABYLON.Tools.Now;
  113083. var dt = 0;
  113084. if (_this._lastFrameTime != null) {
  113085. dt = now - _this._lastFrameTime;
  113086. }
  113087. _this._lastFrameTime = now;
  113088. // Stop the animation if there is user interaction and the animation should stop for this interaction
  113089. _this._applyUserInteraction();
  113090. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  113091. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  113092. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  113093. // Step camera rotation by rotation speed
  113094. if (_this._attachedCamera) {
  113095. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  113096. }
  113097. });
  113098. };
  113099. /**
  113100. * Detaches the behavior from its current arc rotate camera.
  113101. */
  113102. AutoRotationBehavior.prototype.detach = function () {
  113103. if (!this._attachedCamera) {
  113104. return;
  113105. }
  113106. var scene = this._attachedCamera.getScene();
  113107. if (this._onPrePointerObservableObserver) {
  113108. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  113109. }
  113110. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  113111. this._attachedCamera = null;
  113112. };
  113113. /**
  113114. * Returns true if user is scrolling.
  113115. * @return true if user is scrolling.
  113116. */
  113117. AutoRotationBehavior.prototype._userIsZooming = function () {
  113118. if (!this._attachedCamera) {
  113119. return false;
  113120. }
  113121. return this._attachedCamera.inertialRadiusOffset !== 0;
  113122. };
  113123. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  113124. if (!this._attachedCamera) {
  113125. return false;
  113126. }
  113127. var zoomHasHitLimit = false;
  113128. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  113129. zoomHasHitLimit = true;
  113130. }
  113131. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  113132. this._lastFrameRadius = this._attachedCamera.radius;
  113133. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  113134. };
  113135. /**
  113136. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  113137. */
  113138. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  113139. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  113140. this._lastInteractionTime = BABYLON.Tools.Now;
  113141. }
  113142. };
  113143. // Tools
  113144. AutoRotationBehavior.prototype._userIsMoving = function () {
  113145. if (!this._attachedCamera) {
  113146. return false;
  113147. }
  113148. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  113149. this._attachedCamera.inertialBetaOffset !== 0 ||
  113150. this._attachedCamera.inertialRadiusOffset !== 0 ||
  113151. this._attachedCamera.inertialPanningX !== 0 ||
  113152. this._attachedCamera.inertialPanningY !== 0 ||
  113153. this._isPointerDown;
  113154. };
  113155. return AutoRotationBehavior;
  113156. }());
  113157. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  113158. })(BABYLON || (BABYLON = {}));
  113159. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  113160. var BABYLON;
  113161. (function (BABYLON) {
  113162. /**
  113163. * Options to create the null engine
  113164. */
  113165. var NullEngineOptions = /** @class */ (function () {
  113166. function NullEngineOptions() {
  113167. /**
  113168. * Render width (Default: 512)
  113169. */
  113170. this.renderWidth = 512;
  113171. /**
  113172. * Render height (Default: 256)
  113173. */
  113174. this.renderHeight = 256;
  113175. /**
  113176. * Texture size (Default: 512)
  113177. */
  113178. this.textureSize = 512;
  113179. /**
  113180. * If delta time between frames should be constant
  113181. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113182. */
  113183. this.deterministicLockstep = false;
  113184. /**
  113185. * Maximum about of steps between frames (Default: 4)
  113186. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113187. */
  113188. this.lockstepMaxSteps = 4;
  113189. }
  113190. return NullEngineOptions;
  113191. }());
  113192. BABYLON.NullEngineOptions = NullEngineOptions;
  113193. /**
  113194. * The null engine class provides support for headless version of babylon.js.
  113195. * This can be used in server side scenario or for testing purposes
  113196. */
  113197. var NullEngine = /** @class */ (function (_super) {
  113198. __extends(NullEngine, _super);
  113199. function NullEngine(options) {
  113200. if (options === void 0) { options = new NullEngineOptions(); }
  113201. var _this = _super.call(this, null) || this;
  113202. if (options.deterministicLockstep === undefined) {
  113203. options.deterministicLockstep = false;
  113204. }
  113205. if (options.lockstepMaxSteps === undefined) {
  113206. options.lockstepMaxSteps = 4;
  113207. }
  113208. _this._options = options;
  113209. // Init caps
  113210. // We consider we are on a webgl1 capable device
  113211. _this._caps = new BABYLON.EngineCapabilities();
  113212. _this._caps.maxTexturesImageUnits = 16;
  113213. _this._caps.maxVertexTextureImageUnits = 16;
  113214. _this._caps.maxTextureSize = 512;
  113215. _this._caps.maxCubemapTextureSize = 512;
  113216. _this._caps.maxRenderTextureSize = 512;
  113217. _this._caps.maxVertexAttribs = 16;
  113218. _this._caps.maxVaryingVectors = 16;
  113219. _this._caps.maxFragmentUniformVectors = 16;
  113220. _this._caps.maxVertexUniformVectors = 16;
  113221. // Extensions
  113222. _this._caps.standardDerivatives = false;
  113223. _this._caps.astc = null;
  113224. _this._caps.s3tc = null;
  113225. _this._caps.pvrtc = null;
  113226. _this._caps.etc1 = null;
  113227. _this._caps.etc2 = null;
  113228. _this._caps.textureAnisotropicFilterExtension = null;
  113229. _this._caps.maxAnisotropy = 0;
  113230. _this._caps.uintIndices = false;
  113231. _this._caps.fragmentDepthSupported = false;
  113232. _this._caps.highPrecisionShaderSupported = true;
  113233. _this._caps.colorBufferFloat = false;
  113234. _this._caps.textureFloat = false;
  113235. _this._caps.textureFloatLinearFiltering = false;
  113236. _this._caps.textureFloatRender = false;
  113237. _this._caps.textureHalfFloat = false;
  113238. _this._caps.textureHalfFloatLinearFiltering = false;
  113239. _this._caps.textureHalfFloatRender = false;
  113240. _this._caps.textureLOD = false;
  113241. _this._caps.drawBuffersExtension = false;
  113242. _this._caps.depthTextureExtension = false;
  113243. _this._caps.vertexArrayObject = false;
  113244. _this._caps.instancedArrays = false;
  113245. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  113246. // Wrappers
  113247. if (typeof URL === "undefined") {
  113248. URL = {
  113249. createObjectURL: function () { },
  113250. revokeObjectURL: function () { }
  113251. };
  113252. }
  113253. if (typeof Blob === "undefined") {
  113254. Blob = function () { };
  113255. }
  113256. return _this;
  113257. }
  113258. /**
  113259. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  113260. */
  113261. NullEngine.prototype.isDeterministicLockStep = function () {
  113262. return this._options.deterministicLockstep;
  113263. };
  113264. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  113265. NullEngine.prototype.getLockstepMaxSteps = function () {
  113266. return this._options.lockstepMaxSteps;
  113267. };
  113268. /**
  113269. * Sets hardware scaling, used to save performance if needed
  113270. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  113271. */
  113272. NullEngine.prototype.getHardwareScalingLevel = function () {
  113273. return 1.0;
  113274. };
  113275. NullEngine.prototype.createVertexBuffer = function (vertices) {
  113276. return {
  113277. capacity: 0,
  113278. references: 1,
  113279. is32Bits: false
  113280. };
  113281. };
  113282. NullEngine.prototype.createIndexBuffer = function (indices) {
  113283. return {
  113284. capacity: 0,
  113285. references: 1,
  113286. is32Bits: false
  113287. };
  113288. };
  113289. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  113290. if (stencil === void 0) { stencil = false; }
  113291. };
  113292. NullEngine.prototype.getRenderWidth = function (useScreen) {
  113293. if (useScreen === void 0) { useScreen = false; }
  113294. if (!useScreen && this._currentRenderTarget) {
  113295. return this._currentRenderTarget.width;
  113296. }
  113297. return this._options.renderWidth;
  113298. };
  113299. NullEngine.prototype.getRenderHeight = function (useScreen) {
  113300. if (useScreen === void 0) { useScreen = false; }
  113301. if (!useScreen && this._currentRenderTarget) {
  113302. return this._currentRenderTarget.height;
  113303. }
  113304. return this._options.renderHeight;
  113305. };
  113306. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  113307. this._cachedViewport = viewport;
  113308. };
  113309. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  113310. return {
  113311. transformFeedback: null,
  113312. __SPECTOR_rebuildProgram: null
  113313. };
  113314. };
  113315. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  113316. return [];
  113317. };
  113318. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  113319. return [];
  113320. };
  113321. NullEngine.prototype.bindSamplers = function (effect) {
  113322. this._currentEffect = null;
  113323. };
  113324. NullEngine.prototype.enableEffect = function (effect) {
  113325. this._currentEffect = effect;
  113326. if (effect.onBind) {
  113327. effect.onBind(effect);
  113328. }
  113329. if (effect._onBindObservable) {
  113330. effect._onBindObservable.notifyObservers(effect);
  113331. }
  113332. };
  113333. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  113334. if (zOffset === void 0) { zOffset = 0; }
  113335. if (reverseSide === void 0) { reverseSide = false; }
  113336. };
  113337. NullEngine.prototype.setIntArray = function (uniform, array) {
  113338. };
  113339. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  113340. };
  113341. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  113342. };
  113343. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  113344. };
  113345. NullEngine.prototype.setFloatArray = function (uniform, array) {
  113346. };
  113347. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  113348. };
  113349. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  113350. };
  113351. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  113352. };
  113353. NullEngine.prototype.setArray = function (uniform, array) {
  113354. };
  113355. NullEngine.prototype.setArray2 = function (uniform, array) {
  113356. };
  113357. NullEngine.prototype.setArray3 = function (uniform, array) {
  113358. };
  113359. NullEngine.prototype.setArray4 = function (uniform, array) {
  113360. };
  113361. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  113362. };
  113363. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  113364. };
  113365. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  113366. };
  113367. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  113368. };
  113369. NullEngine.prototype.setFloat = function (uniform, value) {
  113370. };
  113371. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  113372. };
  113373. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  113374. };
  113375. NullEngine.prototype.setBool = function (uniform, bool) {
  113376. };
  113377. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  113378. };
  113379. NullEngine.prototype.setColor3 = function (uniform, color3) {
  113380. };
  113381. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  113382. };
  113383. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  113384. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  113385. if (this._alphaMode === mode) {
  113386. return;
  113387. }
  113388. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  113389. if (!noDepthWriteChange) {
  113390. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  113391. }
  113392. this._alphaMode = mode;
  113393. };
  113394. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  113395. };
  113396. NullEngine.prototype.wipeCaches = function (bruteForce) {
  113397. if (this.preventCacheWipeBetweenFrames) {
  113398. return;
  113399. }
  113400. this.resetTextureCache();
  113401. this._currentEffect = null;
  113402. if (bruteForce) {
  113403. this._currentProgram = null;
  113404. this._stencilState.reset();
  113405. this._depthCullingState.reset();
  113406. this._alphaState.reset();
  113407. }
  113408. this._cachedVertexBuffers = null;
  113409. this._cachedIndexBuffer = null;
  113410. this._cachedEffectForVertexBuffers = null;
  113411. };
  113412. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  113413. };
  113414. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  113415. };
  113416. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  113417. };
  113418. /** @hidden */
  113419. NullEngine.prototype._createTexture = function () {
  113420. return {};
  113421. };
  113422. /** @hidden */
  113423. NullEngine.prototype._releaseTexture = function (texture) {
  113424. };
  113425. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  113426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113427. if (onLoad === void 0) { onLoad = null; }
  113428. if (onError === void 0) { onError = null; }
  113429. if (buffer === void 0) { buffer = null; }
  113430. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  113431. var url = String(urlArg);
  113432. texture.url = url;
  113433. texture.generateMipMaps = !noMipmap;
  113434. texture.samplingMode = samplingMode;
  113435. texture.invertY = invertY;
  113436. texture.baseWidth = this._options.textureSize;
  113437. texture.baseHeight = this._options.textureSize;
  113438. texture.width = this._options.textureSize;
  113439. texture.height = this._options.textureSize;
  113440. if (format) {
  113441. texture.format = format;
  113442. }
  113443. texture.isReady = true;
  113444. if (onLoad) {
  113445. onLoad();
  113446. }
  113447. this._internalTexturesCache.push(texture);
  113448. return texture;
  113449. };
  113450. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  113451. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  113452. if (options !== undefined && typeof options === "object") {
  113453. fullOptions.generateMipMaps = options.generateMipMaps;
  113454. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  113455. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  113456. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  113457. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  113458. }
  113459. else {
  113460. fullOptions.generateMipMaps = options;
  113461. fullOptions.generateDepthBuffer = true;
  113462. fullOptions.generateStencilBuffer = false;
  113463. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113464. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  113465. }
  113466. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  113467. var width = size.width || size;
  113468. var height = size.height || size;
  113469. texture._depthStencilBuffer = {};
  113470. texture._framebuffer = {};
  113471. texture.baseWidth = width;
  113472. texture.baseHeight = height;
  113473. texture.width = width;
  113474. texture.height = height;
  113475. texture.isReady = true;
  113476. texture.samples = 1;
  113477. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  113478. texture.samplingMode = fullOptions.samplingMode;
  113479. texture.type = fullOptions.type;
  113480. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  113481. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  113482. this._internalTexturesCache.push(texture);
  113483. return texture;
  113484. };
  113485. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  113486. texture.samplingMode = samplingMode;
  113487. };
  113488. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  113489. if (this._currentRenderTarget) {
  113490. this.unBindFramebuffer(this._currentRenderTarget);
  113491. }
  113492. this._currentRenderTarget = texture;
  113493. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  113494. if (this._cachedViewport && !forceFullscreenViewport) {
  113495. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  113496. }
  113497. };
  113498. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  113499. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  113500. this._currentRenderTarget = null;
  113501. if (onBeforeUnbind) {
  113502. if (texture._MSAAFramebuffer) {
  113503. this._currentFramebuffer = texture._framebuffer;
  113504. }
  113505. onBeforeUnbind();
  113506. }
  113507. this._currentFramebuffer = null;
  113508. };
  113509. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  113510. var vbo = {
  113511. capacity: 1,
  113512. references: 1,
  113513. is32Bits: false
  113514. };
  113515. return vbo;
  113516. };
  113517. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  113518. if (premulAlpha === void 0) { premulAlpha = false; }
  113519. };
  113520. /**
  113521. * @hidden
  113522. * Get the current error code of the webGL context
  113523. * @returns the error code
  113524. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  113525. */
  113526. NullEngine.prototype.getError = function () {
  113527. return 0;
  113528. };
  113529. /** @hidden */
  113530. NullEngine.prototype._getUnpackAlignement = function () {
  113531. return 1;
  113532. };
  113533. /** @hidden */
  113534. NullEngine.prototype._unpackFlipY = function (value) {
  113535. };
  113536. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  113537. if (offset === void 0) { offset = 0; }
  113538. };
  113539. /**
  113540. * Updates a dynamic vertex buffer.
  113541. * @param vertexBuffer the vertex buffer to update
  113542. * @param data the data used to update the vertex buffer
  113543. * @param byteOffset the byte offset of the data (optional)
  113544. * @param byteLength the byte length of the data (optional)
  113545. */
  113546. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  113547. };
  113548. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  113549. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  113550. this._boundTexturesCache[this._activeChannel] = texture;
  113551. return true;
  113552. }
  113553. return false;
  113554. };
  113555. /** @hidden */
  113556. NullEngine.prototype._bindTexture = function (channel, texture) {
  113557. if (channel < 0) {
  113558. return;
  113559. }
  113560. this._bindTextureDirectly(0, texture);
  113561. };
  113562. /** @hidden */
  113563. NullEngine.prototype._releaseBuffer = function (buffer) {
  113564. buffer.references--;
  113565. if (buffer.references === 0) {
  113566. return true;
  113567. }
  113568. return false;
  113569. };
  113570. NullEngine.prototype.releaseEffects = function () {
  113571. };
  113572. NullEngine.prototype.displayLoadingUI = function () {
  113573. };
  113574. NullEngine.prototype.hideLoadingUI = function () {
  113575. };
  113576. /** @hidden */
  113577. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  113578. if (faceIndex === void 0) { faceIndex = 0; }
  113579. if (lod === void 0) { lod = 0; }
  113580. };
  113581. /** @hidden */
  113582. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  113583. if (faceIndex === void 0) { faceIndex = 0; }
  113584. if (lod === void 0) { lod = 0; }
  113585. };
  113586. /** @hidden */
  113587. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  113588. if (faceIndex === void 0) { faceIndex = 0; }
  113589. if (lod === void 0) { lod = 0; }
  113590. };
  113591. /** @hidden */
  113592. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  113593. if (faceIndex === void 0) { faceIndex = 0; }
  113594. if (lod === void 0) { lod = 0; }
  113595. };
  113596. return NullEngine;
  113597. }(BABYLON.Engine));
  113598. BABYLON.NullEngine = NullEngine;
  113599. })(BABYLON || (BABYLON = {}));
  113600. //# sourceMappingURL=babylon.nullEngine.js.map
  113601. var BABYLON;
  113602. (function (BABYLON) {
  113603. /**
  113604. * This class can be used to get instrumentation data from a Babylon engine
  113605. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113606. */
  113607. var EngineInstrumentation = /** @class */ (function () {
  113608. /**
  113609. * Instantiates a new engine instrumentation.
  113610. * This class can be used to get instrumentation data from a Babylon engine
  113611. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113612. * @param engine Defines the engine to instrument
  113613. */
  113614. function EngineInstrumentation(
  113615. /**
  113616. * Define the instrumented engine.
  113617. */
  113618. engine) {
  113619. this.engine = engine;
  113620. this._captureGPUFrameTime = false;
  113621. this._gpuFrameTime = new BABYLON.PerfCounter();
  113622. this._captureShaderCompilationTime = false;
  113623. this._shaderCompilationTime = new BABYLON.PerfCounter();
  113624. // Observers
  113625. this._onBeginFrameObserver = null;
  113626. this._onEndFrameObserver = null;
  113627. this._onBeforeShaderCompilationObserver = null;
  113628. this._onAfterShaderCompilationObserver = null;
  113629. }
  113630. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  113631. // Properties
  113632. /**
  113633. * Gets the perf counter used for GPU frame time
  113634. */
  113635. get: function () {
  113636. return this._gpuFrameTime;
  113637. },
  113638. enumerable: true,
  113639. configurable: true
  113640. });
  113641. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  113642. /**
  113643. * Gets the GPU frame time capture status
  113644. */
  113645. get: function () {
  113646. return this._captureGPUFrameTime;
  113647. },
  113648. /**
  113649. * Enable or disable the GPU frame time capture
  113650. */
  113651. set: function (value) {
  113652. var _this = this;
  113653. if (value === this._captureGPUFrameTime) {
  113654. return;
  113655. }
  113656. this._captureGPUFrameTime = value;
  113657. if (value) {
  113658. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  113659. if (!_this._gpuFrameTimeToken) {
  113660. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  113661. }
  113662. });
  113663. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  113664. if (!_this._gpuFrameTimeToken) {
  113665. return;
  113666. }
  113667. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  113668. if (time > -1) {
  113669. _this._gpuFrameTimeToken = null;
  113670. _this._gpuFrameTime.fetchNewFrame();
  113671. _this._gpuFrameTime.addCount(time, true);
  113672. }
  113673. });
  113674. }
  113675. else {
  113676. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113677. this._onBeginFrameObserver = null;
  113678. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113679. this._onEndFrameObserver = null;
  113680. }
  113681. },
  113682. enumerable: true,
  113683. configurable: true
  113684. });
  113685. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  113686. /**
  113687. * Gets the perf counter used for shader compilation time
  113688. */
  113689. get: function () {
  113690. return this._shaderCompilationTime;
  113691. },
  113692. enumerable: true,
  113693. configurable: true
  113694. });
  113695. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  113696. /**
  113697. * Gets the shader compilation time capture status
  113698. */
  113699. get: function () {
  113700. return this._captureShaderCompilationTime;
  113701. },
  113702. /**
  113703. * Enable or disable the shader compilation time capture
  113704. */
  113705. set: function (value) {
  113706. var _this = this;
  113707. if (value === this._captureShaderCompilationTime) {
  113708. return;
  113709. }
  113710. this._captureShaderCompilationTime = value;
  113711. if (value) {
  113712. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  113713. _this._shaderCompilationTime.fetchNewFrame();
  113714. _this._shaderCompilationTime.beginMonitoring();
  113715. });
  113716. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  113717. _this._shaderCompilationTime.endMonitoring();
  113718. });
  113719. }
  113720. else {
  113721. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113722. this._onBeforeShaderCompilationObserver = null;
  113723. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113724. this._onAfterShaderCompilationObserver = null;
  113725. }
  113726. },
  113727. enumerable: true,
  113728. configurable: true
  113729. });
  113730. /**
  113731. * Dispose and release associated resources.
  113732. */
  113733. EngineInstrumentation.prototype.dispose = function () {
  113734. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113735. this._onBeginFrameObserver = null;
  113736. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113737. this._onEndFrameObserver = null;
  113738. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113739. this._onBeforeShaderCompilationObserver = null;
  113740. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113741. this._onAfterShaderCompilationObserver = null;
  113742. this.engine = null;
  113743. };
  113744. return EngineInstrumentation;
  113745. }());
  113746. BABYLON.EngineInstrumentation = EngineInstrumentation;
  113747. })(BABYLON || (BABYLON = {}));
  113748. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  113749. var BABYLON;
  113750. (function (BABYLON) {
  113751. /**
  113752. * This class can be used to get instrumentation data from a Babylon engine
  113753. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113754. */
  113755. var SceneInstrumentation = /** @class */ (function () {
  113756. /**
  113757. * Instantiates a new scene instrumentation.
  113758. * This class can be used to get instrumentation data from a Babylon engine
  113759. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113760. * @param scene Defines the scene to instrument
  113761. */
  113762. function SceneInstrumentation(
  113763. /**
  113764. * Defines the scene to instrument
  113765. */
  113766. scene) {
  113767. var _this = this;
  113768. this.scene = scene;
  113769. this._captureActiveMeshesEvaluationTime = false;
  113770. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  113771. this._captureRenderTargetsRenderTime = false;
  113772. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  113773. this._captureFrameTime = false;
  113774. this._frameTime = new BABYLON.PerfCounter();
  113775. this._captureRenderTime = false;
  113776. this._renderTime = new BABYLON.PerfCounter();
  113777. this._captureInterFrameTime = false;
  113778. this._interFrameTime = new BABYLON.PerfCounter();
  113779. this._captureParticlesRenderTime = false;
  113780. this._particlesRenderTime = new BABYLON.PerfCounter();
  113781. this._captureSpritesRenderTime = false;
  113782. this._spritesRenderTime = new BABYLON.PerfCounter();
  113783. this._capturePhysicsTime = false;
  113784. this._physicsTime = new BABYLON.PerfCounter();
  113785. this._captureAnimationsTime = false;
  113786. this._animationsTime = new BABYLON.PerfCounter();
  113787. this._captureCameraRenderTime = false;
  113788. this._cameraRenderTime = new BABYLON.PerfCounter();
  113789. // Observers
  113790. this._onBeforeActiveMeshesEvaluationObserver = null;
  113791. this._onAfterActiveMeshesEvaluationObserver = null;
  113792. this._onBeforeRenderTargetsRenderObserver = null;
  113793. this._onAfterRenderTargetsRenderObserver = null;
  113794. this._onAfterRenderObserver = null;
  113795. this._onBeforeDrawPhaseObserver = null;
  113796. this._onAfterDrawPhaseObserver = null;
  113797. this._onBeforeAnimationsObserver = null;
  113798. this._onBeforeParticlesRenderingObserver = null;
  113799. this._onAfterParticlesRenderingObserver = null;
  113800. this._onBeforeSpritesRenderingObserver = null;
  113801. this._onAfterSpritesRenderingObserver = null;
  113802. this._onBeforePhysicsObserver = null;
  113803. this._onAfterPhysicsObserver = null;
  113804. this._onAfterAnimationsObserver = null;
  113805. this._onBeforeCameraRenderObserver = null;
  113806. this._onAfterCameraRenderObserver = null;
  113807. // Before render
  113808. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  113809. if (_this._captureActiveMeshesEvaluationTime) {
  113810. _this._activeMeshesEvaluationTime.fetchNewFrame();
  113811. }
  113812. if (_this._captureRenderTargetsRenderTime) {
  113813. _this._renderTargetsRenderTime.fetchNewFrame();
  113814. }
  113815. if (_this._captureFrameTime) {
  113816. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  113817. _this._frameTime.beginMonitoring();
  113818. }
  113819. if (_this._captureInterFrameTime) {
  113820. _this._interFrameTime.endMonitoring();
  113821. }
  113822. if (_this._captureParticlesRenderTime) {
  113823. _this._particlesRenderTime.fetchNewFrame();
  113824. }
  113825. if (_this._captureSpritesRenderTime) {
  113826. _this._spritesRenderTime.fetchNewFrame();
  113827. }
  113828. if (_this._captureAnimationsTime) {
  113829. _this._animationsTime.beginMonitoring();
  113830. }
  113831. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  113832. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  113833. });
  113834. // After render
  113835. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  113836. if (_this._captureFrameTime) {
  113837. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  113838. _this._frameTime.endMonitoring();
  113839. }
  113840. if (_this._captureRenderTime) {
  113841. _this._renderTime.endMonitoring(false);
  113842. }
  113843. if (_this._captureInterFrameTime) {
  113844. _this._interFrameTime.beginMonitoring();
  113845. }
  113846. });
  113847. }
  113848. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  113849. // Properties
  113850. /**
  113851. * Gets the perf counter used for active meshes evaluation time
  113852. */
  113853. get: function () {
  113854. return this._activeMeshesEvaluationTime;
  113855. },
  113856. enumerable: true,
  113857. configurable: true
  113858. });
  113859. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  113860. /**
  113861. * Gets the active meshes evaluation time capture status
  113862. */
  113863. get: function () {
  113864. return this._captureActiveMeshesEvaluationTime;
  113865. },
  113866. /**
  113867. * Enable or disable the active meshes evaluation time capture
  113868. */
  113869. set: function (value) {
  113870. var _this = this;
  113871. if (value === this._captureActiveMeshesEvaluationTime) {
  113872. return;
  113873. }
  113874. this._captureActiveMeshesEvaluationTime = value;
  113875. if (value) {
  113876. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  113877. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  113878. _this._activeMeshesEvaluationTime.beginMonitoring();
  113879. });
  113880. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  113881. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  113882. _this._activeMeshesEvaluationTime.endMonitoring();
  113883. });
  113884. }
  113885. else {
  113886. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113887. this._onBeforeActiveMeshesEvaluationObserver = null;
  113888. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113889. this._onAfterActiveMeshesEvaluationObserver = null;
  113890. }
  113891. },
  113892. enumerable: true,
  113893. configurable: true
  113894. });
  113895. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  113896. /**
  113897. * Gets the perf counter used for render targets render time
  113898. */
  113899. get: function () {
  113900. return this._renderTargetsRenderTime;
  113901. },
  113902. enumerable: true,
  113903. configurable: true
  113904. });
  113905. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  113906. /**
  113907. * Gets the render targets render time capture status
  113908. */
  113909. get: function () {
  113910. return this._captureRenderTargetsRenderTime;
  113911. },
  113912. /**
  113913. * Enable or disable the render targets render time capture
  113914. */
  113915. set: function (value) {
  113916. var _this = this;
  113917. if (value === this._captureRenderTargetsRenderTime) {
  113918. return;
  113919. }
  113920. this._captureRenderTargetsRenderTime = value;
  113921. if (value) {
  113922. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  113923. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  113924. _this._renderTargetsRenderTime.beginMonitoring();
  113925. });
  113926. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  113927. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  113928. _this._renderTargetsRenderTime.endMonitoring(false);
  113929. });
  113930. }
  113931. else {
  113932. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113933. this._onBeforeRenderTargetsRenderObserver = null;
  113934. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113935. this._onAfterRenderTargetsRenderObserver = null;
  113936. }
  113937. },
  113938. enumerable: true,
  113939. configurable: true
  113940. });
  113941. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  113942. /**
  113943. * Gets the perf counter used for particles render time
  113944. */
  113945. get: function () {
  113946. return this._particlesRenderTime;
  113947. },
  113948. enumerable: true,
  113949. configurable: true
  113950. });
  113951. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  113952. /**
  113953. * Gets the particles render time capture status
  113954. */
  113955. get: function () {
  113956. return this._captureParticlesRenderTime;
  113957. },
  113958. /**
  113959. * Enable or disable the particles render time capture
  113960. */
  113961. set: function (value) {
  113962. var _this = this;
  113963. if (value === this._captureParticlesRenderTime) {
  113964. return;
  113965. }
  113966. this._captureParticlesRenderTime = value;
  113967. if (value) {
  113968. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  113969. BABYLON.Tools.StartPerformanceCounter("Particles");
  113970. _this._particlesRenderTime.beginMonitoring();
  113971. });
  113972. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  113973. BABYLON.Tools.EndPerformanceCounter("Particles");
  113974. _this._particlesRenderTime.endMonitoring(false);
  113975. });
  113976. }
  113977. else {
  113978. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  113979. this._onBeforeParticlesRenderingObserver = null;
  113980. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  113981. this._onAfterParticlesRenderingObserver = null;
  113982. }
  113983. },
  113984. enumerable: true,
  113985. configurable: true
  113986. });
  113987. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  113988. /**
  113989. * Gets the perf counter used for sprites render time
  113990. */
  113991. get: function () {
  113992. return this._spritesRenderTime;
  113993. },
  113994. enumerable: true,
  113995. configurable: true
  113996. });
  113997. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  113998. /**
  113999. * Gets the sprites render time capture status
  114000. */
  114001. get: function () {
  114002. return this._captureSpritesRenderTime;
  114003. },
  114004. /**
  114005. * Enable or disable the sprites render time capture
  114006. */
  114007. set: function (value) {
  114008. var _this = this;
  114009. if (value === this._captureSpritesRenderTime) {
  114010. return;
  114011. }
  114012. this._captureSpritesRenderTime = value;
  114013. if (!this.scene.spriteManagers) {
  114014. return;
  114015. }
  114016. if (value) {
  114017. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  114018. BABYLON.Tools.StartPerformanceCounter("Sprites");
  114019. _this._spritesRenderTime.beginMonitoring();
  114020. });
  114021. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  114022. BABYLON.Tools.EndPerformanceCounter("Sprites");
  114023. _this._spritesRenderTime.endMonitoring(false);
  114024. });
  114025. }
  114026. else {
  114027. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114028. this._onBeforeSpritesRenderingObserver = null;
  114029. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114030. this._onAfterSpritesRenderingObserver = null;
  114031. }
  114032. },
  114033. enumerable: true,
  114034. configurable: true
  114035. });
  114036. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  114037. /**
  114038. * Gets the perf counter used for physics time
  114039. */
  114040. get: function () {
  114041. return this._physicsTime;
  114042. },
  114043. enumerable: true,
  114044. configurable: true
  114045. });
  114046. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  114047. /**
  114048. * Gets the physics time capture status
  114049. */
  114050. get: function () {
  114051. return this._capturePhysicsTime;
  114052. },
  114053. /**
  114054. * Enable or disable the physics time capture
  114055. */
  114056. set: function (value) {
  114057. var _this = this;
  114058. if (value === this._capturePhysicsTime) {
  114059. return;
  114060. }
  114061. if (!this.scene.onBeforePhysicsObservable) {
  114062. return;
  114063. }
  114064. this._capturePhysicsTime = value;
  114065. if (value) {
  114066. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  114067. BABYLON.Tools.StartPerformanceCounter("Physics");
  114068. _this._physicsTime.beginMonitoring();
  114069. });
  114070. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  114071. BABYLON.Tools.EndPerformanceCounter("Physics");
  114072. _this._physicsTime.endMonitoring();
  114073. });
  114074. }
  114075. else {
  114076. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114077. this._onBeforePhysicsObserver = null;
  114078. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114079. this._onAfterPhysicsObserver = null;
  114080. }
  114081. },
  114082. enumerable: true,
  114083. configurable: true
  114084. });
  114085. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  114086. /**
  114087. * Gets the perf counter used for animations time
  114088. */
  114089. get: function () {
  114090. return this._animationsTime;
  114091. },
  114092. enumerable: true,
  114093. configurable: true
  114094. });
  114095. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  114096. /**
  114097. * Gets the animations time capture status
  114098. */
  114099. get: function () {
  114100. return this._captureAnimationsTime;
  114101. },
  114102. /**
  114103. * Enable or disable the animations time capture
  114104. */
  114105. set: function (value) {
  114106. var _this = this;
  114107. if (value === this._captureAnimationsTime) {
  114108. return;
  114109. }
  114110. this._captureAnimationsTime = value;
  114111. if (value) {
  114112. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  114113. _this._animationsTime.endMonitoring();
  114114. });
  114115. }
  114116. else {
  114117. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114118. this._onAfterAnimationsObserver = null;
  114119. }
  114120. },
  114121. enumerable: true,
  114122. configurable: true
  114123. });
  114124. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  114125. /**
  114126. * Gets the perf counter used for frame time capture
  114127. */
  114128. get: function () {
  114129. return this._frameTime;
  114130. },
  114131. enumerable: true,
  114132. configurable: true
  114133. });
  114134. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  114135. /**
  114136. * Gets the frame time capture status
  114137. */
  114138. get: function () {
  114139. return this._captureFrameTime;
  114140. },
  114141. /**
  114142. * Enable or disable the frame time capture
  114143. */
  114144. set: function (value) {
  114145. this._captureFrameTime = value;
  114146. },
  114147. enumerable: true,
  114148. configurable: true
  114149. });
  114150. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  114151. /**
  114152. * Gets the perf counter used for inter-frames time capture
  114153. */
  114154. get: function () {
  114155. return this._interFrameTime;
  114156. },
  114157. enumerable: true,
  114158. configurable: true
  114159. });
  114160. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  114161. /**
  114162. * Gets the inter-frames time capture status
  114163. */
  114164. get: function () {
  114165. return this._captureInterFrameTime;
  114166. },
  114167. /**
  114168. * Enable or disable the inter-frames time capture
  114169. */
  114170. set: function (value) {
  114171. this._captureInterFrameTime = value;
  114172. },
  114173. enumerable: true,
  114174. configurable: true
  114175. });
  114176. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  114177. /**
  114178. * Gets the perf counter used for render time capture
  114179. */
  114180. get: function () {
  114181. return this._renderTime;
  114182. },
  114183. enumerable: true,
  114184. configurable: true
  114185. });
  114186. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  114187. /**
  114188. * Gets the render time capture status
  114189. */
  114190. get: function () {
  114191. return this._captureRenderTime;
  114192. },
  114193. /**
  114194. * Enable or disable the render time capture
  114195. */
  114196. set: function (value) {
  114197. var _this = this;
  114198. if (value === this._captureRenderTime) {
  114199. return;
  114200. }
  114201. this._captureRenderTime = value;
  114202. if (value) {
  114203. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  114204. _this._renderTime.beginMonitoring();
  114205. BABYLON.Tools.StartPerformanceCounter("Main render");
  114206. });
  114207. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  114208. _this._renderTime.endMonitoring(false);
  114209. BABYLON.Tools.EndPerformanceCounter("Main render");
  114210. });
  114211. }
  114212. else {
  114213. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114214. this._onBeforeDrawPhaseObserver = null;
  114215. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114216. this._onAfterDrawPhaseObserver = null;
  114217. }
  114218. },
  114219. enumerable: true,
  114220. configurable: true
  114221. });
  114222. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  114223. /**
  114224. * Gets the perf counter used for camera render time capture
  114225. */
  114226. get: function () {
  114227. return this._cameraRenderTime;
  114228. },
  114229. enumerable: true,
  114230. configurable: true
  114231. });
  114232. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  114233. /**
  114234. * Gets the camera render time capture status
  114235. */
  114236. get: function () {
  114237. return this._captureCameraRenderTime;
  114238. },
  114239. /**
  114240. * Enable or disable the camera render time capture
  114241. */
  114242. set: function (value) {
  114243. var _this = this;
  114244. if (value === this._captureCameraRenderTime) {
  114245. return;
  114246. }
  114247. this._captureCameraRenderTime = value;
  114248. if (value) {
  114249. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  114250. _this._cameraRenderTime.beginMonitoring();
  114251. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  114252. });
  114253. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  114254. _this._cameraRenderTime.endMonitoring(false);
  114255. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  114256. });
  114257. }
  114258. else {
  114259. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114260. this._onBeforeCameraRenderObserver = null;
  114261. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114262. this._onAfterCameraRenderObserver = null;
  114263. }
  114264. },
  114265. enumerable: true,
  114266. configurable: true
  114267. });
  114268. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  114269. /**
  114270. * Gets the perf counter used for draw calls
  114271. */
  114272. get: function () {
  114273. return this.scene.getEngine()._drawCalls;
  114274. },
  114275. enumerable: true,
  114276. configurable: true
  114277. });
  114278. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  114279. /**
  114280. * Gets the perf counter used for texture collisions
  114281. */
  114282. get: function () {
  114283. return this.scene.getEngine()._textureCollisions;
  114284. },
  114285. enumerable: true,
  114286. configurable: true
  114287. });
  114288. /**
  114289. * Dispose and release associated resources.
  114290. */
  114291. SceneInstrumentation.prototype.dispose = function () {
  114292. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114293. this._onAfterRenderObserver = null;
  114294. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  114295. this._onBeforeActiveMeshesEvaluationObserver = null;
  114296. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  114297. this._onAfterActiveMeshesEvaluationObserver = null;
  114298. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  114299. this._onBeforeRenderTargetsRenderObserver = null;
  114300. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  114301. this._onAfterRenderTargetsRenderObserver = null;
  114302. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  114303. this._onBeforeAnimationsObserver = null;
  114304. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  114305. this._onBeforeParticlesRenderingObserver = null;
  114306. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  114307. this._onAfterParticlesRenderingObserver = null;
  114308. if (this._onBeforeSpritesRenderingObserver) {
  114309. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114310. this._onBeforeSpritesRenderingObserver = null;
  114311. }
  114312. if (this._onAfterSpritesRenderingObserver) {
  114313. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114314. this._onAfterSpritesRenderingObserver = null;
  114315. }
  114316. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114317. this._onBeforeDrawPhaseObserver = null;
  114318. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114319. this._onAfterDrawPhaseObserver = null;
  114320. if (this._onBeforePhysicsObserver) {
  114321. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114322. this._onBeforePhysicsObserver = null;
  114323. }
  114324. if (this._onAfterPhysicsObserver) {
  114325. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114326. this._onAfterPhysicsObserver = null;
  114327. }
  114328. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114329. this._onAfterAnimationsObserver = null;
  114330. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114331. this._onBeforeCameraRenderObserver = null;
  114332. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114333. this._onAfterCameraRenderObserver = null;
  114334. this.scene = null;
  114335. };
  114336. return SceneInstrumentation;
  114337. }());
  114338. BABYLON.SceneInstrumentation = SceneInstrumentation;
  114339. })(BABYLON || (BABYLON = {}));
  114340. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  114341. var BABYLON;
  114342. (function (BABYLON) {
  114343. /**
  114344. * @hidden
  114345. **/
  114346. var _TimeToken = /** @class */ (function () {
  114347. function _TimeToken() {
  114348. this._timeElapsedQueryEnded = false;
  114349. }
  114350. return _TimeToken;
  114351. }());
  114352. BABYLON._TimeToken = _TimeToken;
  114353. })(BABYLON || (BABYLON = {}));
  114354. //# sourceMappingURL=babylon.timeToken.js.map
  114355. var BABYLON;
  114356. (function (BABYLON) {
  114357. /**
  114358. * Background material defines definition.
  114359. * @hidden Mainly internal Use
  114360. */
  114361. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  114362. __extends(BackgroundMaterialDefines, _super);
  114363. /**
  114364. * Constructor of the defines.
  114365. */
  114366. function BackgroundMaterialDefines() {
  114367. var _this = _super.call(this) || this;
  114368. /**
  114369. * True if the diffuse texture is in use.
  114370. */
  114371. _this.DIFFUSE = false;
  114372. /**
  114373. * The direct UV channel to use.
  114374. */
  114375. _this.DIFFUSEDIRECTUV = 0;
  114376. /**
  114377. * True if the diffuse texture is in gamma space.
  114378. */
  114379. _this.GAMMADIFFUSE = false;
  114380. /**
  114381. * True if the diffuse texture has opacity in the alpha channel.
  114382. */
  114383. _this.DIFFUSEHASALPHA = false;
  114384. /**
  114385. * True if you want the material to fade to transparent at grazing angle.
  114386. */
  114387. _this.OPACITYFRESNEL = false;
  114388. /**
  114389. * True if an extra blur needs to be added in the reflection.
  114390. */
  114391. _this.REFLECTIONBLUR = false;
  114392. /**
  114393. * True if you want the material to fade to reflection at grazing angle.
  114394. */
  114395. _this.REFLECTIONFRESNEL = false;
  114396. /**
  114397. * True if you want the material to falloff as far as you move away from the scene center.
  114398. */
  114399. _this.REFLECTIONFALLOFF = false;
  114400. /**
  114401. * False if the current Webgl implementation does not support the texture lod extension.
  114402. */
  114403. _this.TEXTURELODSUPPORT = false;
  114404. /**
  114405. * True to ensure the data are premultiplied.
  114406. */
  114407. _this.PREMULTIPLYALPHA = false;
  114408. /**
  114409. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  114410. */
  114411. _this.USERGBCOLOR = false;
  114412. /**
  114413. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  114414. * stays aligned with the desired configuration.
  114415. */
  114416. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  114417. /**
  114418. * True to add noise in order to reduce the banding effect.
  114419. */
  114420. _this.NOISE = false;
  114421. /**
  114422. * is the reflection texture in BGR color scheme?
  114423. * Mainly used to solve a bug in ios10 video tag
  114424. */
  114425. _this.REFLECTIONBGR = false;
  114426. _this.IMAGEPROCESSING = false;
  114427. _this.VIGNETTE = false;
  114428. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  114429. _this.VIGNETTEBLENDMODEOPAQUE = false;
  114430. _this.TONEMAPPING = false;
  114431. _this.TONEMAPPING_ACES = false;
  114432. _this.CONTRAST = false;
  114433. _this.COLORCURVES = false;
  114434. _this.COLORGRADING = false;
  114435. _this.COLORGRADING3D = false;
  114436. _this.SAMPLER3DGREENDEPTH = false;
  114437. _this.SAMPLER3DBGRMAP = false;
  114438. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  114439. _this.EXPOSURE = false;
  114440. // Reflection.
  114441. _this.REFLECTION = false;
  114442. _this.REFLECTIONMAP_3D = false;
  114443. _this.REFLECTIONMAP_SPHERICAL = false;
  114444. _this.REFLECTIONMAP_PLANAR = false;
  114445. _this.REFLECTIONMAP_CUBIC = false;
  114446. _this.REFLECTIONMAP_PROJECTION = false;
  114447. _this.REFLECTIONMAP_SKYBOX = false;
  114448. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114449. _this.REFLECTIONMAP_EXPLICIT = false;
  114450. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114451. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114452. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114453. _this.INVERTCUBICMAP = false;
  114454. _this.REFLECTIONMAP_OPPOSITEZ = false;
  114455. _this.LODINREFLECTIONALPHA = false;
  114456. _this.GAMMAREFLECTION = false;
  114457. _this.RGBDREFLECTION = false;
  114458. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  114459. // Default BJS.
  114460. _this.MAINUV1 = false;
  114461. _this.MAINUV2 = false;
  114462. _this.UV1 = false;
  114463. _this.UV2 = false;
  114464. _this.CLIPPLANE = false;
  114465. _this.CLIPPLANE2 = false;
  114466. _this.CLIPPLANE3 = false;
  114467. _this.CLIPPLANE4 = false;
  114468. _this.POINTSIZE = false;
  114469. _this.FOG = false;
  114470. _this.NORMAL = false;
  114471. _this.NUM_BONE_INFLUENCERS = 0;
  114472. _this.BonesPerMesh = 0;
  114473. _this.INSTANCES = false;
  114474. _this.SHADOWFLOAT = false;
  114475. _this.rebuild();
  114476. return _this;
  114477. }
  114478. return BackgroundMaterialDefines;
  114479. }(BABYLON.MaterialDefines));
  114480. /**
  114481. * Background material used to create an efficient environement around your scene.
  114482. */
  114483. var BackgroundMaterial = /** @class */ (function (_super) {
  114484. __extends(BackgroundMaterial, _super);
  114485. /**
  114486. * Instantiates a Background Material in the given scene
  114487. * @param name The friendly name of the material
  114488. * @param scene The scene to add the material to
  114489. */
  114490. function BackgroundMaterial(name, scene) {
  114491. var _this = _super.call(this, name, scene) || this;
  114492. /**
  114493. * Key light Color (multiply against the environement texture)
  114494. */
  114495. _this.primaryColor = BABYLON.Color3.White();
  114496. _this._primaryColorShadowLevel = 0;
  114497. _this._primaryColorHighlightLevel = 0;
  114498. /**
  114499. * Reflection Texture used in the material.
  114500. * Should be author in a specific way for the best result (refer to the documentation).
  114501. */
  114502. _this.reflectionTexture = null;
  114503. /**
  114504. * Reflection Texture level of blur.
  114505. *
  114506. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  114507. * texture twice.
  114508. */
  114509. _this.reflectionBlur = 0;
  114510. /**
  114511. * Diffuse Texture used in the material.
  114512. * Should be author in a specific way for the best result (refer to the documentation).
  114513. */
  114514. _this.diffuseTexture = null;
  114515. _this._shadowLights = null;
  114516. /**
  114517. * Specify the list of lights casting shadow on the material.
  114518. * All scene shadow lights will be included if null.
  114519. */
  114520. _this.shadowLights = null;
  114521. /**
  114522. * Helps adjusting the shadow to a softer level if required.
  114523. * 0 means black shadows and 1 means no shadows.
  114524. */
  114525. _this.shadowLevel = 0;
  114526. /**
  114527. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  114528. * It is usually zero but might be interesting to modify according to your setup.
  114529. */
  114530. _this.sceneCenter = BABYLON.Vector3.Zero();
  114531. /**
  114532. * This helps specifying that the material is falling off to the sky box at grazing angle.
  114533. * This helps ensuring a nice transition when the camera goes under the ground.
  114534. */
  114535. _this.opacityFresnel = true;
  114536. /**
  114537. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  114538. * This helps adding a mirror texture on the ground.
  114539. */
  114540. _this.reflectionFresnel = false;
  114541. /**
  114542. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  114543. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  114544. */
  114545. _this.reflectionFalloffDistance = 0.0;
  114546. /**
  114547. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  114548. */
  114549. _this.reflectionAmount = 1.0;
  114550. /**
  114551. * This specifies the weight of the reflection at grazing angle.
  114552. */
  114553. _this.reflectionReflectance0 = 0.05;
  114554. /**
  114555. * This specifies the weight of the reflection at a perpendicular point of view.
  114556. */
  114557. _this.reflectionReflectance90 = 0.5;
  114558. /**
  114559. * Helps to directly use the maps channels instead of their level.
  114560. */
  114561. _this.useRGBColor = true;
  114562. /**
  114563. * This helps reducing the banding effect that could occur on the background.
  114564. */
  114565. _this.enableNoise = false;
  114566. _this._fovMultiplier = 1.0;
  114567. /**
  114568. * Enable the FOV adjustment feature controlled by fovMultiplier.
  114569. */
  114570. _this.useEquirectangularFOV = false;
  114571. _this._maxSimultaneousLights = 4;
  114572. /**
  114573. * Number of Simultaneous lights allowed on the material.
  114574. */
  114575. _this.maxSimultaneousLights = 4;
  114576. /**
  114577. * Keep track of the image processing observer to allow dispose and replace.
  114578. */
  114579. _this._imageProcessingObserver = null;
  114580. /**
  114581. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  114582. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  114583. */
  114584. _this.switchToBGR = false;
  114585. // Temp values kept as cache in the material.
  114586. _this._renderTargets = new BABYLON.SmartArray(16);
  114587. _this._reflectionControls = BABYLON.Vector4.Zero();
  114588. _this._white = BABYLON.Color3.White();
  114589. _this._primaryShadowColor = BABYLON.Color3.Black();
  114590. _this._primaryHighlightColor = BABYLON.Color3.Black();
  114591. // Setup the default processing configuration to the scene.
  114592. _this._attachImageProcessingConfiguration(null);
  114593. _this.getRenderTargetTextures = function () {
  114594. _this._renderTargets.reset();
  114595. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  114596. _this._renderTargets.push(_this._diffuseTexture);
  114597. }
  114598. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  114599. _this._renderTargets.push(_this._reflectionTexture);
  114600. }
  114601. return _this._renderTargets;
  114602. };
  114603. return _this;
  114604. }
  114605. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  114606. /**
  114607. * Experimental Internal Use Only.
  114608. *
  114609. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  114610. * This acts as a helper to set the primary color to a more "human friendly" value.
  114611. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  114612. * output color as close as possible from the chosen value.
  114613. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  114614. * part of lighting setup.)
  114615. */
  114616. get: function () {
  114617. return this.__perceptualColor;
  114618. },
  114619. set: function (value) {
  114620. this.__perceptualColor = value;
  114621. this._computePrimaryColorFromPerceptualColor();
  114622. this._markAllSubMeshesAsLightsDirty();
  114623. },
  114624. enumerable: true,
  114625. configurable: true
  114626. });
  114627. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  114628. /**
  114629. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  114630. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  114631. */
  114632. get: function () {
  114633. return this._primaryColorShadowLevel;
  114634. },
  114635. set: function (value) {
  114636. this._primaryColorShadowLevel = value;
  114637. this._computePrimaryColors();
  114638. this._markAllSubMeshesAsLightsDirty();
  114639. },
  114640. enumerable: true,
  114641. configurable: true
  114642. });
  114643. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  114644. /**
  114645. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  114646. * The primary color is used at the level chosen to define what the white area would look.
  114647. */
  114648. get: function () {
  114649. return this._primaryColorHighlightLevel;
  114650. },
  114651. set: function (value) {
  114652. this._primaryColorHighlightLevel = value;
  114653. this._computePrimaryColors();
  114654. this._markAllSubMeshesAsLightsDirty();
  114655. },
  114656. enumerable: true,
  114657. configurable: true
  114658. });
  114659. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  114660. /**
  114661. * Sets the reflection reflectance fresnel values according to the default standard
  114662. * empirically know to work well :-)
  114663. */
  114664. set: function (value) {
  114665. var reflectionWeight = value;
  114666. if (reflectionWeight < 0.5) {
  114667. reflectionWeight = reflectionWeight * 2.0;
  114668. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  114669. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  114670. }
  114671. else {
  114672. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  114673. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  114674. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  114675. }
  114676. },
  114677. enumerable: true,
  114678. configurable: true
  114679. });
  114680. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  114681. /**
  114682. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114683. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  114684. * Recommended to be keep at 1.0 except for special cases.
  114685. */
  114686. get: function () {
  114687. return this._fovMultiplier;
  114688. },
  114689. set: function (value) {
  114690. if (isNaN(value)) {
  114691. value = 1.0;
  114692. }
  114693. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  114694. },
  114695. enumerable: true,
  114696. configurable: true
  114697. });
  114698. /**
  114699. * Attaches a new image processing configuration to the PBR Material.
  114700. * @param configuration (if null the scene configuration will be use)
  114701. */
  114702. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  114703. var _this = this;
  114704. if (configuration === this._imageProcessingConfiguration) {
  114705. return;
  114706. }
  114707. // Detaches observer.
  114708. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  114709. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  114710. }
  114711. // Pick the scene configuration if needed.
  114712. if (!configuration) {
  114713. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  114714. }
  114715. else {
  114716. this._imageProcessingConfiguration = configuration;
  114717. }
  114718. // Attaches observer.
  114719. if (this._imageProcessingConfiguration) {
  114720. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  114721. _this._computePrimaryColorFromPerceptualColor();
  114722. _this._markAllSubMeshesAsImageProcessingDirty();
  114723. });
  114724. }
  114725. };
  114726. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  114727. /**
  114728. * Gets the image processing configuration used either in this material.
  114729. */
  114730. get: function () {
  114731. return this._imageProcessingConfiguration;
  114732. },
  114733. /**
  114734. * Sets the Default image processing configuration used either in the this material.
  114735. *
  114736. * If sets to null, the scene one is in use.
  114737. */
  114738. set: function (value) {
  114739. this._attachImageProcessingConfiguration(value);
  114740. // Ensure the effect will be rebuilt.
  114741. this._markAllSubMeshesAsTexturesDirty();
  114742. },
  114743. enumerable: true,
  114744. configurable: true
  114745. });
  114746. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  114747. /**
  114748. * Gets wether the color curves effect is enabled.
  114749. */
  114750. get: function () {
  114751. return this.imageProcessingConfiguration.colorCurvesEnabled;
  114752. },
  114753. /**
  114754. * Sets wether the color curves effect is enabled.
  114755. */
  114756. set: function (value) {
  114757. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  114758. },
  114759. enumerable: true,
  114760. configurable: true
  114761. });
  114762. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  114763. /**
  114764. * Gets wether the color grading effect is enabled.
  114765. */
  114766. get: function () {
  114767. return this.imageProcessingConfiguration.colorGradingEnabled;
  114768. },
  114769. /**
  114770. * Gets wether the color grading effect is enabled.
  114771. */
  114772. set: function (value) {
  114773. this.imageProcessingConfiguration.colorGradingEnabled = value;
  114774. },
  114775. enumerable: true,
  114776. configurable: true
  114777. });
  114778. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  114779. /**
  114780. * Gets wether tonemapping is enabled or not.
  114781. */
  114782. get: function () {
  114783. return this._imageProcessingConfiguration.toneMappingEnabled;
  114784. },
  114785. /**
  114786. * Sets wether tonemapping is enabled or not
  114787. */
  114788. set: function (value) {
  114789. this._imageProcessingConfiguration.toneMappingEnabled = value;
  114790. },
  114791. enumerable: true,
  114792. configurable: true
  114793. });
  114794. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  114795. /**
  114796. * The camera exposure used on this material.
  114797. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114798. * This corresponds to a photographic exposure.
  114799. */
  114800. get: function () {
  114801. return this._imageProcessingConfiguration.exposure;
  114802. },
  114803. /**
  114804. * The camera exposure used on this material.
  114805. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114806. * This corresponds to a photographic exposure.
  114807. */
  114808. set: function (value) {
  114809. this._imageProcessingConfiguration.exposure = value;
  114810. },
  114811. enumerable: true,
  114812. configurable: true
  114813. });
  114814. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  114815. /**
  114816. * Gets The camera contrast used on this material.
  114817. */
  114818. get: function () {
  114819. return this._imageProcessingConfiguration.contrast;
  114820. },
  114821. /**
  114822. * Sets The camera contrast used on this material.
  114823. */
  114824. set: function (value) {
  114825. this._imageProcessingConfiguration.contrast = value;
  114826. },
  114827. enumerable: true,
  114828. configurable: true
  114829. });
  114830. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  114831. /**
  114832. * Gets the Color Grading 2D Lookup Texture.
  114833. */
  114834. get: function () {
  114835. return this._imageProcessingConfiguration.colorGradingTexture;
  114836. },
  114837. /**
  114838. * Sets the Color Grading 2D Lookup Texture.
  114839. */
  114840. set: function (value) {
  114841. this.imageProcessingConfiguration.colorGradingTexture = value;
  114842. },
  114843. enumerable: true,
  114844. configurable: true
  114845. });
  114846. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  114847. /**
  114848. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114849. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114850. * 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;
  114851. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114852. */
  114853. get: function () {
  114854. return this.imageProcessingConfiguration.colorCurves;
  114855. },
  114856. /**
  114857. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114858. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114859. * 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;
  114860. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114861. */
  114862. set: function (value) {
  114863. this.imageProcessingConfiguration.colorCurves = value;
  114864. },
  114865. enumerable: true,
  114866. configurable: true
  114867. });
  114868. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  114869. /**
  114870. * Gets a boolean indicating that current material needs to register RTT
  114871. */
  114872. get: function () {
  114873. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114874. return true;
  114875. }
  114876. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114877. return true;
  114878. }
  114879. return false;
  114880. },
  114881. enumerable: true,
  114882. configurable: true
  114883. });
  114884. /**
  114885. * The entire material has been created in order to prevent overdraw.
  114886. * @returns false
  114887. */
  114888. BackgroundMaterial.prototype.needAlphaTesting = function () {
  114889. return true;
  114890. };
  114891. /**
  114892. * The entire material has been created in order to prevent overdraw.
  114893. * @returns true if blending is enable
  114894. */
  114895. BackgroundMaterial.prototype.needAlphaBlending = function () {
  114896. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  114897. };
  114898. /**
  114899. * Checks wether the material is ready to be rendered for a given mesh.
  114900. * @param mesh The mesh to render
  114901. * @param subMesh The submesh to check against
  114902. * @param useInstances Specify wether or not the material is used with instances
  114903. * @returns true if all the dependencies are ready (Textures, Effects...)
  114904. */
  114905. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  114906. var _this = this;
  114907. if (useInstances === void 0) { useInstances = false; }
  114908. if (subMesh.effect && this.isFrozen) {
  114909. if (this._wasPreviouslyReady) {
  114910. return true;
  114911. }
  114912. }
  114913. if (!subMesh._materialDefines) {
  114914. subMesh._materialDefines = new BackgroundMaterialDefines();
  114915. }
  114916. var scene = this.getScene();
  114917. var defines = subMesh._materialDefines;
  114918. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  114919. if (defines._renderId === scene.getRenderId()) {
  114920. return true;
  114921. }
  114922. }
  114923. var engine = scene.getEngine();
  114924. // Lights
  114925. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  114926. defines._needNormals = true;
  114927. // Textures
  114928. if (defines._areTexturesDirty) {
  114929. defines._needUVs = false;
  114930. if (scene.texturesEnabled) {
  114931. if (scene.getEngine().getCaps().textureLOD) {
  114932. defines.TEXTURELODSUPPORT = true;
  114933. }
  114934. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114935. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  114936. return false;
  114937. }
  114938. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  114939. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  114940. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  114941. defines.OPACITYFRESNEL = this._opacityFresnel;
  114942. }
  114943. else {
  114944. defines.DIFFUSE = false;
  114945. defines.DIFFUSEHASALPHA = false;
  114946. defines.GAMMADIFFUSE = false;
  114947. defines.OPACITYFRESNEL = false;
  114948. }
  114949. var reflectionTexture = this._reflectionTexture;
  114950. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114951. if (!reflectionTexture.isReadyOrNotBlocking()) {
  114952. return false;
  114953. }
  114954. defines.REFLECTION = true;
  114955. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  114956. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  114957. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  114958. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  114959. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  114960. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  114961. defines.REFLECTIONBGR = this.switchToBGR;
  114962. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  114963. defines.INVERTCUBICMAP = true;
  114964. }
  114965. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  114966. switch (reflectionTexture.coordinatesMode) {
  114967. case BABYLON.Texture.EXPLICIT_MODE:
  114968. defines.REFLECTIONMAP_EXPLICIT = true;
  114969. break;
  114970. case BABYLON.Texture.PLANAR_MODE:
  114971. defines.REFLECTIONMAP_PLANAR = true;
  114972. break;
  114973. case BABYLON.Texture.PROJECTION_MODE:
  114974. defines.REFLECTIONMAP_PROJECTION = true;
  114975. break;
  114976. case BABYLON.Texture.SKYBOX_MODE:
  114977. defines.REFLECTIONMAP_SKYBOX = true;
  114978. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  114979. break;
  114980. case BABYLON.Texture.SPHERICAL_MODE:
  114981. defines.REFLECTIONMAP_SPHERICAL = true;
  114982. break;
  114983. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  114984. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  114985. break;
  114986. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  114987. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  114988. break;
  114989. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  114990. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  114991. break;
  114992. case BABYLON.Texture.CUBIC_MODE:
  114993. case BABYLON.Texture.INVCUBIC_MODE:
  114994. default:
  114995. defines.REFLECTIONMAP_CUBIC = true;
  114996. break;
  114997. }
  114998. if (this.reflectionFresnel) {
  114999. defines.REFLECTIONFRESNEL = true;
  115000. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  115001. this._reflectionControls.x = this.reflectionAmount;
  115002. this._reflectionControls.y = this.reflectionReflectance0;
  115003. this._reflectionControls.z = this.reflectionReflectance90;
  115004. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  115005. }
  115006. else {
  115007. defines.REFLECTIONFRESNEL = false;
  115008. defines.REFLECTIONFALLOFF = false;
  115009. }
  115010. }
  115011. else {
  115012. defines.REFLECTION = false;
  115013. defines.REFLECTIONFRESNEL = false;
  115014. defines.REFLECTIONFALLOFF = false;
  115015. defines.REFLECTIONBLUR = false;
  115016. defines.REFLECTIONMAP_3D = false;
  115017. defines.REFLECTIONMAP_SPHERICAL = false;
  115018. defines.REFLECTIONMAP_PLANAR = false;
  115019. defines.REFLECTIONMAP_CUBIC = false;
  115020. defines.REFLECTIONMAP_PROJECTION = false;
  115021. defines.REFLECTIONMAP_SKYBOX = false;
  115022. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  115023. defines.REFLECTIONMAP_EXPLICIT = false;
  115024. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  115025. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  115026. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  115027. defines.INVERTCUBICMAP = false;
  115028. defines.REFLECTIONMAP_OPPOSITEZ = false;
  115029. defines.LODINREFLECTIONALPHA = false;
  115030. defines.GAMMAREFLECTION = false;
  115031. defines.RGBDREFLECTION = false;
  115032. }
  115033. }
  115034. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  115035. defines.USERGBCOLOR = this._useRGBColor;
  115036. defines.NOISE = this._enableNoise;
  115037. }
  115038. if (defines._areLightsDirty) {
  115039. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  115040. }
  115041. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  115042. if (!this._imageProcessingConfiguration.isReady()) {
  115043. return false;
  115044. }
  115045. this._imageProcessingConfiguration.prepareDefines(defines);
  115046. }
  115047. // Misc.
  115048. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  115049. // Values that need to be evaluated on every frame
  115050. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  115051. // Attribs
  115052. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  115053. if (mesh) {
  115054. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  115055. mesh.createNormals(true);
  115056. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  115057. }
  115058. }
  115059. }
  115060. // Get correct effect
  115061. if (defines.isDirty) {
  115062. defines.markAsProcessed();
  115063. scene.resetCachedMaterial();
  115064. // Fallbacks
  115065. var fallbacks = new BABYLON.EffectFallbacks();
  115066. if (defines.FOG) {
  115067. fallbacks.addFallback(0, "FOG");
  115068. }
  115069. if (defines.POINTSIZE) {
  115070. fallbacks.addFallback(1, "POINTSIZE");
  115071. }
  115072. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  115073. if (defines.NUM_BONE_INFLUENCERS > 0) {
  115074. fallbacks.addCPUSkinningFallback(0, mesh);
  115075. }
  115076. //Attributes
  115077. var attribs = [BABYLON.VertexBuffer.PositionKind];
  115078. if (defines.NORMAL) {
  115079. attribs.push(BABYLON.VertexBuffer.NormalKind);
  115080. }
  115081. if (defines.UV1) {
  115082. attribs.push(BABYLON.VertexBuffer.UVKind);
  115083. }
  115084. if (defines.UV2) {
  115085. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  115086. }
  115087. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  115088. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  115089. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  115090. "vFogInfos", "vFogColor", "pointSize",
  115091. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  115092. "vPrimaryColor", "vPrimaryColorShadow",
  115093. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  115094. "shadowLevel", "alpha",
  115095. "vBackgroundCenter", "vReflectionControl",
  115096. "vDiffuseInfos", "diffuseMatrix",
  115097. ];
  115098. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  115099. var uniformBuffers = ["Material", "Scene"];
  115100. if (BABYLON.ImageProcessingConfiguration) {
  115101. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  115102. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  115103. }
  115104. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  115105. uniformsNames: uniforms,
  115106. uniformBuffersNames: uniformBuffers,
  115107. samplers: samplers,
  115108. defines: defines,
  115109. maxSimultaneousLights: this._maxSimultaneousLights
  115110. });
  115111. var onCompiled = function (effect) {
  115112. if (_this.onCompiled) {
  115113. _this.onCompiled(effect);
  115114. }
  115115. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  115116. };
  115117. var join = defines.toString();
  115118. subMesh.setEffect(scene.getEngine().createEffect("background", {
  115119. attributes: attribs,
  115120. uniformsNames: uniforms,
  115121. uniformBuffersNames: uniformBuffers,
  115122. samplers: samplers,
  115123. defines: join,
  115124. fallbacks: fallbacks,
  115125. onCompiled: onCompiled,
  115126. onError: this.onError,
  115127. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  115128. }, engine), defines);
  115129. this.buildUniformLayout();
  115130. }
  115131. if (!subMesh.effect || !subMesh.effect.isReady()) {
  115132. return false;
  115133. }
  115134. defines._renderId = scene.getRenderId();
  115135. this._wasPreviouslyReady = true;
  115136. return true;
  115137. };
  115138. /**
  115139. * Compute the primary color according to the chosen perceptual color.
  115140. */
  115141. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  115142. if (!this.__perceptualColor) {
  115143. return;
  115144. }
  115145. this._primaryColor.copyFrom(this.__perceptualColor);
  115146. // Revert gamma space.
  115147. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  115148. // Revert image processing configuration.
  115149. if (this._imageProcessingConfiguration) {
  115150. // Revert Exposure.
  115151. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  115152. }
  115153. this._computePrimaryColors();
  115154. };
  115155. /**
  115156. * Compute the highlights and shadow colors according to their chosen levels.
  115157. */
  115158. BackgroundMaterial.prototype._computePrimaryColors = function () {
  115159. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  115160. return;
  115161. }
  115162. // Find the highlight color based on the configuration.
  115163. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  115164. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  115165. // Find the shadow color based on the configuration.
  115166. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  115167. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  115168. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  115169. };
  115170. /**
  115171. * Build the uniform buffer used in the material.
  115172. */
  115173. BackgroundMaterial.prototype.buildUniformLayout = function () {
  115174. // Order is important !
  115175. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  115176. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  115177. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  115178. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  115179. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  115180. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  115181. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  115182. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  115183. this._uniformBuffer.addUniform("pointSize", 1);
  115184. this._uniformBuffer.addUniform("shadowLevel", 1);
  115185. this._uniformBuffer.addUniform("alpha", 1);
  115186. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  115187. this._uniformBuffer.addUniform("vReflectionControl", 4);
  115188. this._uniformBuffer.create();
  115189. };
  115190. /**
  115191. * Unbind the material.
  115192. */
  115193. BackgroundMaterial.prototype.unbind = function () {
  115194. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  115195. this._uniformBuffer.setTexture("diffuseSampler", null);
  115196. }
  115197. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  115198. this._uniformBuffer.setTexture("reflectionSampler", null);
  115199. }
  115200. _super.prototype.unbind.call(this);
  115201. };
  115202. /**
  115203. * Bind only the world matrix to the material.
  115204. * @param world The world matrix to bind.
  115205. */
  115206. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  115207. this._activeEffect.setMatrix("world", world);
  115208. };
  115209. /**
  115210. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  115211. * @param world The world matrix to bind.
  115212. * @param subMesh The submesh to bind for.
  115213. */
  115214. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  115215. var scene = this.getScene();
  115216. var defines = subMesh._materialDefines;
  115217. if (!defines) {
  115218. return;
  115219. }
  115220. var effect = subMesh.effect;
  115221. if (!effect) {
  115222. return;
  115223. }
  115224. this._activeEffect = effect;
  115225. // Matrices
  115226. this.bindOnlyWorldMatrix(world);
  115227. // Bones
  115228. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  115229. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  115230. if (mustRebind) {
  115231. this._uniformBuffer.bindToEffect(effect, "Material");
  115232. this.bindViewProjection(effect);
  115233. var reflectionTexture = this._reflectionTexture;
  115234. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  115235. // Texture uniforms
  115236. if (scene.texturesEnabled) {
  115237. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115238. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  115239. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  115240. }
  115241. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115242. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  115243. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  115244. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  115245. }
  115246. }
  115247. if (this.shadowLevel > 0) {
  115248. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  115249. }
  115250. this._uniformBuffer.updateFloat("alpha", this.alpha);
  115251. // Point size
  115252. if (this.pointsCloud) {
  115253. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  115254. }
  115255. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  115256. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  115257. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  115258. }
  115259. else {
  115260. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  115261. }
  115262. }
  115263. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  115264. // Textures
  115265. if (scene.texturesEnabled) {
  115266. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  115267. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  115268. }
  115269. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  115270. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  115271. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  115272. }
  115273. else if (!defines.REFLECTIONBLUR) {
  115274. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  115275. }
  115276. else {
  115277. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  115278. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  115279. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  115280. }
  115281. if (defines.REFLECTIONFRESNEL) {
  115282. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  115283. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  115284. }
  115285. }
  115286. }
  115287. // Clip plane
  115288. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  115289. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  115290. }
  115291. if (mustRebind || !this.isFrozen) {
  115292. if (scene.lightsEnabled) {
  115293. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  115294. }
  115295. // View
  115296. this.bindView(effect);
  115297. // Fog
  115298. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  115299. // image processing
  115300. if (this._imageProcessingConfiguration) {
  115301. this._imageProcessingConfiguration.bind(this._activeEffect);
  115302. }
  115303. }
  115304. this._uniformBuffer.update();
  115305. this._afterBind(mesh, this._activeEffect);
  115306. };
  115307. /**
  115308. * Dispose the material.
  115309. * @param forceDisposeEffect Force disposal of the associated effect.
  115310. * @param forceDisposeTextures Force disposal of the associated textures.
  115311. */
  115312. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  115313. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  115314. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  115315. if (forceDisposeTextures) {
  115316. if (this.diffuseTexture) {
  115317. this.diffuseTexture.dispose();
  115318. }
  115319. if (this.reflectionTexture) {
  115320. this.reflectionTexture.dispose();
  115321. }
  115322. }
  115323. this._renderTargets.dispose();
  115324. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  115325. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  115326. }
  115327. _super.prototype.dispose.call(this, forceDisposeEffect);
  115328. };
  115329. /**
  115330. * Clones the material.
  115331. * @param name The cloned name.
  115332. * @returns The cloned material.
  115333. */
  115334. BackgroundMaterial.prototype.clone = function (name) {
  115335. var _this = this;
  115336. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  115337. };
  115338. /**
  115339. * Serializes the current material to its JSON representation.
  115340. * @returns The JSON representation.
  115341. */
  115342. BackgroundMaterial.prototype.serialize = function () {
  115343. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  115344. serializationObject.customType = "BABYLON.BackgroundMaterial";
  115345. return serializationObject;
  115346. };
  115347. /**
  115348. * Gets the class name of the material
  115349. * @returns "BackgroundMaterial"
  115350. */
  115351. BackgroundMaterial.prototype.getClassName = function () {
  115352. return "BackgroundMaterial";
  115353. };
  115354. /**
  115355. * Parse a JSON input to create back a background material.
  115356. * @param source The JSON data to parse
  115357. * @param scene The scene to create the parsed material in
  115358. * @param rootUrl The root url of the assets the material depends upon
  115359. * @returns the instantiated BackgroundMaterial.
  115360. */
  115361. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  115362. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  115363. };
  115364. /**
  115365. * Standard reflectance value at parallel view angle.
  115366. */
  115367. BackgroundMaterial.StandardReflectance0 = 0.05;
  115368. /**
  115369. * Standard reflectance value at grazing angle.
  115370. */
  115371. BackgroundMaterial.StandardReflectance90 = 0.5;
  115372. __decorate([
  115373. BABYLON.serializeAsColor3()
  115374. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  115375. __decorate([
  115376. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115377. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  115378. __decorate([
  115379. BABYLON.serializeAsColor3()
  115380. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  115381. __decorate([
  115382. BABYLON.serialize()
  115383. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  115384. __decorate([
  115385. BABYLON.serialize()
  115386. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  115387. __decorate([
  115388. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115389. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  115390. __decorate([
  115391. BABYLON.serializeAsTexture()
  115392. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  115393. __decorate([
  115394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115395. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  115396. __decorate([
  115397. BABYLON.serialize()
  115398. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  115399. __decorate([
  115400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115401. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  115402. __decorate([
  115403. BABYLON.serializeAsTexture()
  115404. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  115405. __decorate([
  115406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115407. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  115408. __decorate([
  115409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115410. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  115411. __decorate([
  115412. BABYLON.serialize()
  115413. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  115414. __decorate([
  115415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115416. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  115417. __decorate([
  115418. BABYLON.serializeAsVector3()
  115419. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  115420. __decorate([
  115421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115422. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  115423. __decorate([
  115424. BABYLON.serialize()
  115425. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  115426. __decorate([
  115427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115428. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  115429. __decorate([
  115430. BABYLON.serialize()
  115431. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  115432. __decorate([
  115433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115434. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  115435. __decorate([
  115436. BABYLON.serialize()
  115437. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  115438. __decorate([
  115439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115440. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  115441. __decorate([
  115442. BABYLON.serialize()
  115443. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  115444. __decorate([
  115445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115446. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  115447. __decorate([
  115448. BABYLON.serialize()
  115449. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  115450. __decorate([
  115451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115452. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  115453. __decorate([
  115454. BABYLON.serialize()
  115455. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  115456. __decorate([
  115457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115458. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  115459. __decorate([
  115460. BABYLON.serialize()
  115461. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  115462. __decorate([
  115463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115464. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  115465. __decorate([
  115466. BABYLON.serialize()
  115467. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  115468. __decorate([
  115469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115470. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  115471. __decorate([
  115472. BABYLON.serialize()
  115473. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  115474. __decorate([
  115475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115476. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  115477. __decorate([
  115478. BABYLON.serializeAsImageProcessingConfiguration()
  115479. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  115480. return BackgroundMaterial;
  115481. }(BABYLON.PushMaterial));
  115482. BABYLON.BackgroundMaterial = BackgroundMaterial;
  115483. })(BABYLON || (BABYLON = {}));
  115484. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  115485. var __assign = (this && this.__assign) || function () {
  115486. __assign = Object.assign || function(t) {
  115487. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115488. s = arguments[i];
  115489. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115490. t[p] = s[p];
  115491. }
  115492. return t;
  115493. };
  115494. return __assign.apply(this, arguments);
  115495. };
  115496. var BABYLON;
  115497. (function (BABYLON) {
  115498. /**
  115499. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  115500. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  115501. * It also helps with the default setup of your imageProcessing configuration.
  115502. */
  115503. var EnvironmentHelper = /** @class */ (function () {
  115504. /**
  115505. * constructor
  115506. * @param options
  115507. * @param scene The scene to add the material to
  115508. */
  115509. function EnvironmentHelper(options, scene) {
  115510. var _this = this;
  115511. this._errorHandler = function (message, exception) {
  115512. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  115513. };
  115514. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  115515. this._scene = scene;
  115516. this.onErrorObservable = new BABYLON.Observable();
  115517. this._setupBackground();
  115518. this._setupImageProcessing();
  115519. }
  115520. /**
  115521. * Creates the default options for the helper.
  115522. */
  115523. EnvironmentHelper._getDefaultOptions = function () {
  115524. return {
  115525. createGround: true,
  115526. groundSize: 15,
  115527. groundTexture: this._groundTextureCDNUrl,
  115528. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115529. groundOpacity: 0.9,
  115530. enableGroundShadow: true,
  115531. groundShadowLevel: 0.5,
  115532. enableGroundMirror: false,
  115533. groundMirrorSizeRatio: 0.3,
  115534. groundMirrorBlurKernel: 64,
  115535. groundMirrorAmount: 1,
  115536. groundMirrorFresnelWeight: 1,
  115537. groundMirrorFallOffDistance: 0,
  115538. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  115539. groundYBias: 0.00001,
  115540. createSkybox: true,
  115541. skyboxSize: 20,
  115542. skyboxTexture: this._skyboxTextureCDNUrl,
  115543. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115544. backgroundYRotation: 0,
  115545. sizeAuto: true,
  115546. rootPosition: BABYLON.Vector3.Zero(),
  115547. setupImageProcessing: true,
  115548. environmentTexture: this._environmentTextureCDNUrl,
  115549. cameraExposure: 0.8,
  115550. cameraContrast: 1.2,
  115551. toneMappingEnabled: true,
  115552. };
  115553. };
  115554. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  115555. /**
  115556. * Gets the root mesh created by the helper.
  115557. */
  115558. get: function () {
  115559. return this._rootMesh;
  115560. },
  115561. enumerable: true,
  115562. configurable: true
  115563. });
  115564. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  115565. /**
  115566. * Gets the skybox created by the helper.
  115567. */
  115568. get: function () {
  115569. return this._skybox;
  115570. },
  115571. enumerable: true,
  115572. configurable: true
  115573. });
  115574. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  115575. /**
  115576. * Gets the skybox texture created by the helper.
  115577. */
  115578. get: function () {
  115579. return this._skyboxTexture;
  115580. },
  115581. enumerable: true,
  115582. configurable: true
  115583. });
  115584. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  115585. /**
  115586. * Gets the skybox material created by the helper.
  115587. */
  115588. get: function () {
  115589. return this._skyboxMaterial;
  115590. },
  115591. enumerable: true,
  115592. configurable: true
  115593. });
  115594. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  115595. /**
  115596. * Gets the ground mesh created by the helper.
  115597. */
  115598. get: function () {
  115599. return this._ground;
  115600. },
  115601. enumerable: true,
  115602. configurable: true
  115603. });
  115604. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  115605. /**
  115606. * Gets the ground texture created by the helper.
  115607. */
  115608. get: function () {
  115609. return this._groundTexture;
  115610. },
  115611. enumerable: true,
  115612. configurable: true
  115613. });
  115614. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  115615. /**
  115616. * Gets the ground mirror created by the helper.
  115617. */
  115618. get: function () {
  115619. return this._groundMirror;
  115620. },
  115621. enumerable: true,
  115622. configurable: true
  115623. });
  115624. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  115625. /**
  115626. * Gets the ground mirror render list to helps pushing the meshes
  115627. * you wish in the ground reflection.
  115628. */
  115629. get: function () {
  115630. if (this._groundMirror) {
  115631. return this._groundMirror.renderList;
  115632. }
  115633. return null;
  115634. },
  115635. enumerable: true,
  115636. configurable: true
  115637. });
  115638. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  115639. /**
  115640. * Gets the ground material created by the helper.
  115641. */
  115642. get: function () {
  115643. return this._groundMaterial;
  115644. },
  115645. enumerable: true,
  115646. configurable: true
  115647. });
  115648. /**
  115649. * Updates the background according to the new options
  115650. * @param options
  115651. */
  115652. EnvironmentHelper.prototype.updateOptions = function (options) {
  115653. var newOptions = __assign({}, this._options, options);
  115654. if (this._ground && !newOptions.createGround) {
  115655. this._ground.dispose();
  115656. this._ground = null;
  115657. }
  115658. if (this._groundMaterial && !newOptions.createGround) {
  115659. this._groundMaterial.dispose();
  115660. this._groundMaterial = null;
  115661. }
  115662. if (this._groundTexture) {
  115663. if (this._options.groundTexture != newOptions.groundTexture) {
  115664. this._groundTexture.dispose();
  115665. this._groundTexture = null;
  115666. }
  115667. }
  115668. if (this._skybox && !newOptions.createSkybox) {
  115669. this._skybox.dispose();
  115670. this._skybox = null;
  115671. }
  115672. if (this._skyboxMaterial && !newOptions.createSkybox) {
  115673. this._skyboxMaterial.dispose();
  115674. this._skyboxMaterial = null;
  115675. }
  115676. if (this._skyboxTexture) {
  115677. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  115678. this._skyboxTexture.dispose();
  115679. this._skyboxTexture = null;
  115680. }
  115681. }
  115682. if (this._groundMirror && !newOptions.enableGroundMirror) {
  115683. this._groundMirror.dispose();
  115684. this._groundMirror = null;
  115685. }
  115686. if (this._scene.environmentTexture) {
  115687. if (this._options.environmentTexture != newOptions.environmentTexture) {
  115688. this._scene.environmentTexture.dispose();
  115689. }
  115690. }
  115691. this._options = newOptions;
  115692. this._setupBackground();
  115693. this._setupImageProcessing();
  115694. };
  115695. /**
  115696. * Sets the primary color of all the available elements.
  115697. * @param color the main color to affect to the ground and the background
  115698. */
  115699. EnvironmentHelper.prototype.setMainColor = function (color) {
  115700. if (this.groundMaterial) {
  115701. this.groundMaterial.primaryColor = color;
  115702. }
  115703. if (this.skyboxMaterial) {
  115704. this.skyboxMaterial.primaryColor = color;
  115705. }
  115706. if (this.groundMirror) {
  115707. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  115708. }
  115709. };
  115710. /**
  115711. * Setup the image processing according to the specified options.
  115712. */
  115713. EnvironmentHelper.prototype._setupImageProcessing = function () {
  115714. if (this._options.setupImageProcessing) {
  115715. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  115716. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  115717. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  115718. this._setupEnvironmentTexture();
  115719. }
  115720. };
  115721. /**
  115722. * Setup the environment texture according to the specified options.
  115723. */
  115724. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  115725. if (this._scene.environmentTexture) {
  115726. return;
  115727. }
  115728. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  115729. this._scene.environmentTexture = this._options.environmentTexture;
  115730. return;
  115731. }
  115732. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  115733. this._scene.environmentTexture = environmentTexture;
  115734. };
  115735. /**
  115736. * Setup the background according to the specified options.
  115737. */
  115738. EnvironmentHelper.prototype._setupBackground = function () {
  115739. if (!this._rootMesh) {
  115740. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  115741. }
  115742. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  115743. var sceneSize = this._getSceneSize();
  115744. if (this._options.createGround) {
  115745. this._setupGround(sceneSize);
  115746. this._setupGroundMaterial();
  115747. this._setupGroundDiffuseTexture();
  115748. if (this._options.enableGroundMirror) {
  115749. this._setupGroundMirrorTexture(sceneSize);
  115750. }
  115751. this._setupMirrorInGroundMaterial();
  115752. }
  115753. if (this._options.createSkybox) {
  115754. this._setupSkybox(sceneSize);
  115755. this._setupSkyboxMaterial();
  115756. this._setupSkyboxReflectionTexture();
  115757. }
  115758. this._rootMesh.position.x = sceneSize.rootPosition.x;
  115759. this._rootMesh.position.z = sceneSize.rootPosition.z;
  115760. this._rootMesh.position.y = sceneSize.rootPosition.y;
  115761. };
  115762. /**
  115763. * Get the scene sizes according to the setup.
  115764. */
  115765. EnvironmentHelper.prototype._getSceneSize = function () {
  115766. var _this = this;
  115767. var groundSize = this._options.groundSize;
  115768. var skyboxSize = this._options.skyboxSize;
  115769. var rootPosition = this._options.rootPosition;
  115770. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  115771. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115772. }
  115773. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  115774. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  115775. });
  115776. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  115777. if (this._options.sizeAuto) {
  115778. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  115779. this._scene.activeCamera.upperRadiusLimit) {
  115780. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  115781. skyboxSize = groundSize;
  115782. }
  115783. var sceneDiagonalLenght = sceneDiagonal.length();
  115784. if (sceneDiagonalLenght > groundSize) {
  115785. groundSize = sceneDiagonalLenght * 2;
  115786. skyboxSize = groundSize;
  115787. }
  115788. // 10 % bigger.
  115789. groundSize *= 1.1;
  115790. skyboxSize *= 1.5;
  115791. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  115792. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  115793. }
  115794. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115795. };
  115796. /**
  115797. * Setup the ground according to the specified options.
  115798. */
  115799. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  115800. var _this = this;
  115801. if (!this._ground || this._ground.isDisposed()) {
  115802. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  115803. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  115804. this._ground.parent = this._rootMesh;
  115805. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  115806. }
  115807. this._ground.receiveShadows = this._options.enableGroundShadow;
  115808. };
  115809. /**
  115810. * Setup the ground material according to the specified options.
  115811. */
  115812. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  115813. if (!this._groundMaterial) {
  115814. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  115815. }
  115816. this._groundMaterial.alpha = this._options.groundOpacity;
  115817. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  115818. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  115819. this._groundMaterial.primaryColor = this._options.groundColor;
  115820. this._groundMaterial.useRGBColor = false;
  115821. this._groundMaterial.enableNoise = true;
  115822. if (this._ground) {
  115823. this._ground.material = this._groundMaterial;
  115824. }
  115825. };
  115826. /**
  115827. * Setup the ground diffuse texture according to the specified options.
  115828. */
  115829. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  115830. if (!this._groundMaterial) {
  115831. return;
  115832. }
  115833. if (this._groundTexture) {
  115834. return;
  115835. }
  115836. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  115837. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  115838. return;
  115839. }
  115840. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115841. diffuseTexture.gammaSpace = false;
  115842. diffuseTexture.hasAlpha = true;
  115843. this._groundMaterial.diffuseTexture = diffuseTexture;
  115844. };
  115845. /**
  115846. * Setup the ground mirror texture according to the specified options.
  115847. */
  115848. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  115849. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115850. if (!this._groundMirror) {
  115851. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  115852. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  115853. this._groundMirror.anisotropicFilteringLevel = 1;
  115854. this._groundMirror.wrapU = wrapping;
  115855. this._groundMirror.wrapV = wrapping;
  115856. this._groundMirror.gammaSpace = false;
  115857. if (this._groundMirror.renderList) {
  115858. for (var i = 0; i < this._scene.meshes.length; i++) {
  115859. var mesh = this._scene.meshes[i];
  115860. if (mesh !== this._ground &&
  115861. mesh !== this._skybox &&
  115862. mesh !== this._rootMesh) {
  115863. this._groundMirror.renderList.push(mesh);
  115864. }
  115865. }
  115866. }
  115867. }
  115868. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  115869. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  115870. };
  115871. /**
  115872. * Setup the ground to receive the mirror texture.
  115873. */
  115874. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  115875. if (this._groundMaterial) {
  115876. this._groundMaterial.reflectionTexture = this._groundMirror;
  115877. this._groundMaterial.reflectionFresnel = true;
  115878. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  115879. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  115880. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  115881. }
  115882. };
  115883. /**
  115884. * Setup the skybox according to the specified options.
  115885. */
  115886. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  115887. var _this = this;
  115888. if (!this._skybox || this._skybox.isDisposed()) {
  115889. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  115890. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  115891. }
  115892. this._skybox.parent = this._rootMesh;
  115893. };
  115894. /**
  115895. * Setup the skybox material according to the specified options.
  115896. */
  115897. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  115898. if (!this._skybox) {
  115899. return;
  115900. }
  115901. if (!this._skyboxMaterial) {
  115902. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  115903. }
  115904. this._skyboxMaterial.useRGBColor = false;
  115905. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  115906. this._skyboxMaterial.enableNoise = true;
  115907. this._skybox.material = this._skyboxMaterial;
  115908. };
  115909. /**
  115910. * Setup the skybox reflection texture according to the specified options.
  115911. */
  115912. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  115913. if (!this._skyboxMaterial) {
  115914. return;
  115915. }
  115916. if (this._skyboxTexture) {
  115917. return;
  115918. }
  115919. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  115920. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  115921. return;
  115922. }
  115923. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115924. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115925. this._skyboxTexture.gammaSpace = false;
  115926. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  115927. };
  115928. /**
  115929. * Dispose all the elements created by the Helper.
  115930. */
  115931. EnvironmentHelper.prototype.dispose = function () {
  115932. if (this._groundMaterial) {
  115933. this._groundMaterial.dispose(true, true);
  115934. }
  115935. if (this._skyboxMaterial) {
  115936. this._skyboxMaterial.dispose(true, true);
  115937. }
  115938. this._rootMesh.dispose(false);
  115939. };
  115940. /**
  115941. * Default ground texture URL.
  115942. */
  115943. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  115944. /**
  115945. * Default skybox texture URL.
  115946. */
  115947. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  115948. /**
  115949. * Default environment texture URL.
  115950. */
  115951. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  115952. return EnvironmentHelper;
  115953. }());
  115954. BABYLON.EnvironmentHelper = EnvironmentHelper;
  115955. })(BABYLON || (BABYLON = {}));
  115956. //# sourceMappingURL=babylon.environmentHelper.js.map
  115957. var BABYLON;
  115958. (function (BABYLON) {
  115959. /** Internal class used to store shapes for emitters */
  115960. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  115961. function ParticleSystemSetEmitterCreationOptions() {
  115962. }
  115963. return ParticleSystemSetEmitterCreationOptions;
  115964. }());
  115965. /**
  115966. * Represents a set of particle systems working together to create a specific effect
  115967. */
  115968. var ParticleSystemSet = /** @class */ (function () {
  115969. function ParticleSystemSet() {
  115970. /**
  115971. * Gets the particle system list
  115972. */
  115973. this.systems = new Array();
  115974. }
  115975. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  115976. /**
  115977. * Gets the emitter node used with this set
  115978. */
  115979. get: function () {
  115980. return this._emitterNode;
  115981. },
  115982. enumerable: true,
  115983. configurable: true
  115984. });
  115985. /**
  115986. * Creates a new emitter mesh as a sphere
  115987. * @param options defines the options used to create the sphere
  115988. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  115989. * @param scene defines the hosting scene
  115990. */
  115991. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  115992. if (this._emitterNode) {
  115993. this._emitterNode.dispose();
  115994. }
  115995. this._emitterCreationOptions = {
  115996. kind: "Sphere",
  115997. options: options,
  115998. renderingGroupId: renderingGroupId
  115999. };
  116000. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  116001. emitterMesh.renderingGroupId = renderingGroupId;
  116002. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  116003. material.emissiveColor = options.color;
  116004. emitterMesh.material = material;
  116005. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116006. var system = _a[_i];
  116007. system.emitter = emitterMesh;
  116008. }
  116009. this._emitterNode = emitterMesh;
  116010. };
  116011. /**
  116012. * Starts all particle systems of the set
  116013. * @param emitter defines an optional mesh to use as emitter for the particle systems
  116014. */
  116015. ParticleSystemSet.prototype.start = function (emitter) {
  116016. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116017. var system = _a[_i];
  116018. if (emitter) {
  116019. system.emitter = emitter;
  116020. }
  116021. system.start();
  116022. }
  116023. };
  116024. /**
  116025. * Release all associated resources
  116026. */
  116027. ParticleSystemSet.prototype.dispose = function () {
  116028. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116029. var system = _a[_i];
  116030. system.dispose();
  116031. }
  116032. this.systems = [];
  116033. if (this._emitterNode) {
  116034. this._emitterNode.dispose();
  116035. this._emitterNode = null;
  116036. }
  116037. };
  116038. /**
  116039. * Serialize the set into a JSON compatible object
  116040. * @returns a JSON compatible representation of the set
  116041. */
  116042. ParticleSystemSet.prototype.serialize = function () {
  116043. var result = {};
  116044. result.systems = [];
  116045. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  116046. var system = _a[_i];
  116047. result.systems.push(system.serialize());
  116048. }
  116049. if (this._emitterNode) {
  116050. result.emitter = this._emitterCreationOptions;
  116051. }
  116052. return result;
  116053. };
  116054. /**
  116055. * Parse a new ParticleSystemSet from a serialized source
  116056. * @param data defines a JSON compatible representation of the set
  116057. * @param scene defines the hosting scene
  116058. * @param gpu defines if we want GPU particles or CPU particles
  116059. * @returns a new ParticleSystemSet
  116060. */
  116061. ParticleSystemSet.Parse = function (data, scene, gpu) {
  116062. if (gpu === void 0) { gpu = false; }
  116063. var result = new ParticleSystemSet();
  116064. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  116065. scene = scene || BABYLON.Engine.LastCreatedScene;
  116066. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  116067. var system = _a[_i];
  116068. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  116069. }
  116070. if (data.emitter) {
  116071. var options = data.emitter.options;
  116072. switch (data.emitter.kind) {
  116073. case "Sphere":
  116074. result.setEmitterAsSphere({
  116075. diameter: options.diameter,
  116076. segments: options.segments,
  116077. color: BABYLON.Color3.FromArray(options.color)
  116078. }, data.emitter.renderingGroupId, scene);
  116079. break;
  116080. }
  116081. }
  116082. return result;
  116083. };
  116084. return ParticleSystemSet;
  116085. }());
  116086. BABYLON.ParticleSystemSet = ParticleSystemSet;
  116087. })(BABYLON || (BABYLON = {}));
  116088. //# sourceMappingURL=babylon.particleSystemSet.js.map
  116089. var BABYLON;
  116090. (function (BABYLON) {
  116091. /**
  116092. * This class is made for on one-liner static method to help creating particle system set.
  116093. */
  116094. var ParticleHelper = /** @class */ (function () {
  116095. function ParticleHelper() {
  116096. }
  116097. /**
  116098. * Create a default particle system that you can tweak
  116099. * @param emitter defines the emitter to use
  116100. * @param capacity defines the system capacity (default is 500 particles)
  116101. * @param scene defines the hosting scene
  116102. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  116103. * @returns the new Particle system
  116104. */
  116105. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  116106. if (capacity === void 0) { capacity = 500; }
  116107. if (useGPU === void 0) { useGPU = false; }
  116108. var system;
  116109. if (useGPU) {
  116110. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  116111. }
  116112. else {
  116113. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  116114. }
  116115. system.emitter = emitter;
  116116. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  116117. system.createConeEmitter(0.1, Math.PI / 4);
  116118. // Particle color
  116119. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  116120. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  116121. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  116122. // Particle Size
  116123. system.minSize = 0.1;
  116124. system.maxSize = 0.1;
  116125. // Emission speed
  116126. system.minEmitPower = 2;
  116127. system.maxEmitPower = 2;
  116128. // Update speed
  116129. system.updateSpeed = 1 / 60;
  116130. system.emitRate = 30;
  116131. return system;
  116132. };
  116133. /**
  116134. * This is the main static method (one-liner) of this helper to create different particle systems
  116135. * @param type This string represents the type to the particle system to create
  116136. * @param scene The scene where the particle system should live
  116137. * @param gpu If the system will use gpu
  116138. * @returns the ParticleSystemSet created
  116139. */
  116140. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  116141. if (gpu === void 0) { gpu = false; }
  116142. if (!scene) {
  116143. scene = BABYLON.Engine.LastCreatedScene;
  116144. }
  116145. var token = {};
  116146. scene._addPendingData(token);
  116147. return new Promise(function (resolve, reject) {
  116148. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  116149. scene._removePendingData(token);
  116150. return reject("Particle system with GPU is not supported.");
  116151. }
  116152. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  116153. scene._removePendingData(token);
  116154. var newData = JSON.parse(data.toString());
  116155. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  116156. }, undefined, undefined, undefined, function (req, exception) {
  116157. scene._removePendingData(token);
  116158. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  116159. });
  116160. });
  116161. };
  116162. /**
  116163. * Static function used to export a particle system to a ParticleSystemSet variable.
  116164. * Please note that the emitter shape is not exported
  116165. * @param systems defines the particle systems to export
  116166. * @returns the created particle system set
  116167. */
  116168. ParticleHelper.ExportSet = function (systems) {
  116169. var set = new BABYLON.ParticleSystemSet();
  116170. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  116171. var system = systems_1[_i];
  116172. set.systems.push(system);
  116173. }
  116174. return set;
  116175. };
  116176. /**
  116177. * Gets or sets base Assets URL
  116178. */
  116179. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  116180. return ParticleHelper;
  116181. }());
  116182. BABYLON.ParticleHelper = ParticleHelper;
  116183. })(BABYLON || (BABYLON = {}));
  116184. //# sourceMappingURL=babylon.particleHelper.js.map
  116185. var BABYLON;
  116186. (function (BABYLON) {
  116187. /**
  116188. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  116189. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  116190. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  116191. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116192. */
  116193. var VideoDome = /** @class */ (function (_super) {
  116194. __extends(VideoDome, _super);
  116195. /**
  116196. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  116197. * @param name Element's name, child elements will append suffixes for their own names.
  116198. * @param urlsOrVideo defines the url(s) or the video element to use
  116199. * @param options An object containing optional or exposed sub element properties
  116200. */
  116201. function VideoDome(name, urlsOrVideo, options, scene) {
  116202. var _this = _super.call(this, name, scene) || this;
  116203. _this._useDirectMapping = false;
  116204. // set defaults and manage values
  116205. name = name || "videoDome";
  116206. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116207. options.clickToPlay = Boolean(options.clickToPlay);
  116208. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  116209. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  116210. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116211. if (options.useDirectMapping === undefined) {
  116212. _this._useDirectMapping = true;
  116213. }
  116214. else {
  116215. _this._useDirectMapping = options.useDirectMapping;
  116216. }
  116217. _this._setReady(false);
  116218. // create
  116219. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  116220. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116221. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  116222. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116223. texture.onLoadObservable.addOnce(function () {
  116224. _this._setReady(true);
  116225. });
  116226. // configure material
  116227. material.useEquirectangularFOV = true;
  116228. material.fovMultiplier = 1.0;
  116229. material.opacityFresnel = false;
  116230. if (_this._useDirectMapping) {
  116231. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116232. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116233. material.diffuseTexture = texture;
  116234. }
  116235. else {
  116236. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116237. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116238. material.reflectionTexture = texture;
  116239. }
  116240. // configure mesh
  116241. _this._mesh.material = material;
  116242. _this._mesh.parent = _this;
  116243. // optional configuration
  116244. if (options.clickToPlay) {
  116245. scene.onPointerUp = function () {
  116246. _this._videoTexture.video.play();
  116247. };
  116248. }
  116249. return _this;
  116250. }
  116251. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  116252. /**
  116253. * Gets the video texture being displayed on the sphere
  116254. */
  116255. get: function () {
  116256. return this._videoTexture;
  116257. },
  116258. enumerable: true,
  116259. configurable: true
  116260. });
  116261. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  116262. /**
  116263. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116264. * Also see the options.resolution property.
  116265. */
  116266. get: function () {
  116267. return this._material.fovMultiplier;
  116268. },
  116269. set: function (value) {
  116270. this._material.fovMultiplier = value;
  116271. },
  116272. enumerable: true,
  116273. configurable: true
  116274. });
  116275. /**
  116276. * Releases resources associated with this node.
  116277. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116278. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116279. */
  116280. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116281. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116282. this._videoTexture.dispose();
  116283. this._mesh.dispose();
  116284. this._material.dispose();
  116285. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116286. };
  116287. return VideoDome;
  116288. }(BABYLON.TransformNode));
  116289. BABYLON.VideoDome = VideoDome;
  116290. })(BABYLON || (BABYLON = {}));
  116291. //# sourceMappingURL=babylon.videoDome.js.map
  116292. var BABYLON;
  116293. (function (BABYLON) {
  116294. /**
  116295. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  116296. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  116297. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  116298. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116299. */
  116300. var PhotoDome = /** @class */ (function (_super) {
  116301. __extends(PhotoDome, _super);
  116302. /**
  116303. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  116304. * @param name Element's name, child elements will append suffixes for their own names.
  116305. * @param urlsOfPhoto defines the url of the photo to display
  116306. * @param options defines an object containing optional or exposed sub element properties
  116307. * @param onError defines a callback called when an error occured while loading the texture
  116308. */
  116309. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  116310. if (onError === void 0) { onError = null; }
  116311. var _this = _super.call(this, name, scene) || this;
  116312. _this._useDirectMapping = false;
  116313. /**
  116314. * Observable raised when an error occured while loading the 360 image
  116315. */
  116316. _this.onLoadErrorObservable = new BABYLON.Observable();
  116317. // set defaults and manage values
  116318. name = name || "photoDome";
  116319. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116320. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116321. if (options.useDirectMapping === undefined) {
  116322. _this._useDirectMapping = true;
  116323. }
  116324. else {
  116325. _this._useDirectMapping = options.useDirectMapping;
  116326. }
  116327. _this._setReady(false);
  116328. // create
  116329. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116330. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116331. // configure material
  116332. material.opacityFresnel = false;
  116333. material.useEquirectangularFOV = true;
  116334. material.fovMultiplier = 1.0;
  116335. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  116336. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  116337. if (onError) {
  116338. onError(message, exception);
  116339. }
  116340. });
  116341. _this.photoTexture.onLoadObservable.addOnce(function () {
  116342. _this._setReady(true);
  116343. });
  116344. // configure mesh
  116345. _this._mesh.material = material;
  116346. _this._mesh.parent = _this;
  116347. return _this;
  116348. }
  116349. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  116350. /**
  116351. * Gets or sets the texture being displayed on the sphere
  116352. */
  116353. get: function () {
  116354. return this._photoTexture;
  116355. },
  116356. set: function (value) {
  116357. if (this._photoTexture === value) {
  116358. return;
  116359. }
  116360. this._photoTexture = value;
  116361. if (this._useDirectMapping) {
  116362. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116363. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116364. this._material.diffuseTexture = this._photoTexture;
  116365. }
  116366. else {
  116367. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116368. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116369. this._material.reflectionTexture = this._photoTexture;
  116370. }
  116371. },
  116372. enumerable: true,
  116373. configurable: true
  116374. });
  116375. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  116376. /**
  116377. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116378. * Also see the options.resolution property.
  116379. */
  116380. get: function () {
  116381. return this._material.fovMultiplier;
  116382. },
  116383. set: function (value) {
  116384. this._material.fovMultiplier = value;
  116385. },
  116386. enumerable: true,
  116387. configurable: true
  116388. });
  116389. /**
  116390. * Releases resources associated with this node.
  116391. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116392. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116393. */
  116394. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116395. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116396. this._photoTexture.dispose();
  116397. this._mesh.dispose();
  116398. this._material.dispose();
  116399. this.onLoadErrorObservable.clear();
  116400. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116401. };
  116402. return PhotoDome;
  116403. }(BABYLON.TransformNode));
  116404. BABYLON.PhotoDome = PhotoDome;
  116405. })(BABYLON || (BABYLON = {}));
  116406. //# sourceMappingURL=babylon.photoDome.js.map
  116407. var BABYLON;
  116408. (function (BABYLON) {
  116409. /** @hidden */
  116410. var _OcclusionDataStorage = /** @class */ (function () {
  116411. function _OcclusionDataStorage() {
  116412. /** @hidden */
  116413. this.occlusionInternalRetryCounter = 0;
  116414. /** @hidden */
  116415. this.isOcclusionQueryInProgress = false;
  116416. /** @hidden */
  116417. this.isOccluded = false;
  116418. /** @hidden */
  116419. this.occlusionRetryCount = -1;
  116420. /** @hidden */
  116421. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  116422. /** @hidden */
  116423. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  116424. }
  116425. return _OcclusionDataStorage;
  116426. }());
  116427. BABYLON.Engine.prototype.createQuery = function () {
  116428. return this._gl.createQuery();
  116429. };
  116430. BABYLON.Engine.prototype.deleteQuery = function (query) {
  116431. this._gl.deleteQuery(query);
  116432. return this;
  116433. };
  116434. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  116435. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  116436. };
  116437. BABYLON.Engine.prototype.getQueryResult = function (query) {
  116438. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  116439. };
  116440. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  116441. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116442. this._gl.beginQuery(glAlgorithm, query);
  116443. return this;
  116444. };
  116445. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  116446. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116447. this._gl.endQuery(glAlgorithm);
  116448. return this;
  116449. };
  116450. BABYLON.Engine.prototype._createTimeQuery = function () {
  116451. var timerQuery = this.getCaps().timerQuery;
  116452. if (timerQuery.createQueryEXT) {
  116453. return timerQuery.createQueryEXT();
  116454. }
  116455. return this.createQuery();
  116456. };
  116457. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  116458. var timerQuery = this.getCaps().timerQuery;
  116459. if (timerQuery.deleteQueryEXT) {
  116460. timerQuery.deleteQueryEXT(query);
  116461. return;
  116462. }
  116463. this.deleteQuery(query);
  116464. };
  116465. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  116466. var timerQuery = this.getCaps().timerQuery;
  116467. if (timerQuery.getQueryObjectEXT) {
  116468. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  116469. }
  116470. return this.getQueryResult(query);
  116471. };
  116472. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  116473. var timerQuery = this.getCaps().timerQuery;
  116474. if (timerQuery.getQueryObjectEXT) {
  116475. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  116476. }
  116477. return this.isQueryResultAvailable(query);
  116478. };
  116479. BABYLON.Engine.prototype.startTimeQuery = function () {
  116480. var caps = this.getCaps();
  116481. var timerQuery = caps.timerQuery;
  116482. if (!timerQuery) {
  116483. return null;
  116484. }
  116485. var token = new BABYLON._TimeToken();
  116486. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116487. if (caps.canUseTimestampForTimerQuery) {
  116488. token._startTimeQuery = this._createTimeQuery();
  116489. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  116490. }
  116491. else {
  116492. if (this._currentNonTimestampToken) {
  116493. return this._currentNonTimestampToken;
  116494. }
  116495. token._timeElapsedQuery = this._createTimeQuery();
  116496. if (timerQuery.beginQueryEXT) {
  116497. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116498. }
  116499. else {
  116500. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116501. }
  116502. this._currentNonTimestampToken = token;
  116503. }
  116504. return token;
  116505. };
  116506. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  116507. var caps = this.getCaps();
  116508. var timerQuery = caps.timerQuery;
  116509. if (!timerQuery || !token) {
  116510. return -1;
  116511. }
  116512. if (caps.canUseTimestampForTimerQuery) {
  116513. if (!token._startTimeQuery) {
  116514. return -1;
  116515. }
  116516. if (!token._endTimeQuery) {
  116517. token._endTimeQuery = this._createTimeQuery();
  116518. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  116519. }
  116520. }
  116521. else if (!token._timeElapsedQueryEnded) {
  116522. if (!token._timeElapsedQuery) {
  116523. return -1;
  116524. }
  116525. if (timerQuery.endQueryEXT) {
  116526. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  116527. }
  116528. else {
  116529. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  116530. }
  116531. token._timeElapsedQueryEnded = true;
  116532. }
  116533. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116534. var available = false;
  116535. if (token._endTimeQuery) {
  116536. available = this._getTimeQueryAvailability(token._endTimeQuery);
  116537. }
  116538. else if (token._timeElapsedQuery) {
  116539. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  116540. }
  116541. if (available && !disjoint) {
  116542. var result = 0;
  116543. if (caps.canUseTimestampForTimerQuery) {
  116544. if (!token._startTimeQuery || !token._endTimeQuery) {
  116545. return -1;
  116546. }
  116547. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  116548. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  116549. result = timeEnd - timeStart;
  116550. this._deleteTimeQuery(token._startTimeQuery);
  116551. this._deleteTimeQuery(token._endTimeQuery);
  116552. token._startTimeQuery = null;
  116553. token._endTimeQuery = null;
  116554. }
  116555. else {
  116556. if (!token._timeElapsedQuery) {
  116557. return -1;
  116558. }
  116559. result = this._getTimeQueryResult(token._timeElapsedQuery);
  116560. this._deleteTimeQuery(token._timeElapsedQuery);
  116561. token._timeElapsedQuery = null;
  116562. token._timeElapsedQueryEnded = false;
  116563. this._currentNonTimestampToken = null;
  116564. }
  116565. return result;
  116566. }
  116567. return -1;
  116568. };
  116569. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  116570. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  116571. };
  116572. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  116573. get: function () {
  116574. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  116575. },
  116576. enumerable: false,
  116577. configurable: true
  116578. });
  116579. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  116580. get: function () {
  116581. if (!this.__occlusionDataStorage) {
  116582. this.__occlusionDataStorage = new _OcclusionDataStorage();
  116583. }
  116584. return this.__occlusionDataStorage;
  116585. },
  116586. enumerable: false,
  116587. configurable: true
  116588. });
  116589. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  116590. get: function () {
  116591. return this._occlusionDataStorage.isOccluded;
  116592. },
  116593. set: function (value) {
  116594. this._occlusionDataStorage.isOccluded = value;
  116595. },
  116596. enumerable: true,
  116597. configurable: true
  116598. });
  116599. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  116600. get: function () {
  116601. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  116602. },
  116603. set: function (value) {
  116604. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  116605. },
  116606. enumerable: true,
  116607. configurable: true
  116608. });
  116609. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  116610. get: function () {
  116611. return this._occlusionDataStorage.occlusionType;
  116612. },
  116613. set: function (value) {
  116614. this._occlusionDataStorage.occlusionType = value;
  116615. },
  116616. enumerable: true,
  116617. configurable: true
  116618. });
  116619. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  116620. get: function () {
  116621. return this._occlusionDataStorage.occlusionRetryCount;
  116622. },
  116623. set: function (value) {
  116624. this._occlusionDataStorage.occlusionRetryCount = value;
  116625. },
  116626. enumerable: true,
  116627. configurable: true
  116628. });
  116629. // We also need to update AbstractMesh as there is a portion of the code there
  116630. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  116631. var dataStorage = this._occlusionDataStorage;
  116632. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  116633. dataStorage.isOccluded = false;
  116634. return false;
  116635. }
  116636. var engine = this.getEngine();
  116637. if (engine.webGLVersion < 2) {
  116638. dataStorage.isOccluded = false;
  116639. return false;
  116640. }
  116641. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  116642. dataStorage.isOccluded = false;
  116643. return false;
  116644. }
  116645. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  116646. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  116647. if (isOcclusionQueryAvailable) {
  116648. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  116649. dataStorage.isOcclusionQueryInProgress = false;
  116650. dataStorage.occlusionInternalRetryCounter = 0;
  116651. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  116652. }
  116653. else {
  116654. dataStorage.occlusionInternalRetryCounter++;
  116655. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  116656. dataStorage.isOcclusionQueryInProgress = false;
  116657. dataStorage.occlusionInternalRetryCounter = 0;
  116658. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  116659. // if strict continue the last state of the object.
  116660. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  116661. }
  116662. else {
  116663. return false;
  116664. }
  116665. }
  116666. }
  116667. var scene = this.getScene();
  116668. if (scene.getBoundingBoxRenderer) {
  116669. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  116670. if (!this._occlusionQuery) {
  116671. this._occlusionQuery = engine.createQuery();
  116672. }
  116673. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  116674. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  116675. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  116676. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  116677. }
  116678. return dataStorage.isOccluded;
  116679. };
  116680. })(BABYLON || (BABYLON = {}));
  116681. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  116682. var BABYLON;
  116683. (function (BABYLON) {
  116684. /**
  116685. * Class used to generate noise procedural textures
  116686. */
  116687. var NoiseProceduralTexture = /** @class */ (function (_super) {
  116688. __extends(NoiseProceduralTexture, _super);
  116689. /**
  116690. * Creates a new NoiseProceduralTexture
  116691. * @param name defines the name fo the texture
  116692. * @param size defines the size of the texture (default is 256)
  116693. * @param scene defines the hosting scene
  116694. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  116695. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  116696. */
  116697. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  116698. if (size === void 0) { size = 256; }
  116699. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  116700. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  116701. _this._time = 0;
  116702. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  116703. _this.brightness = 0.2;
  116704. /** Defines the number of octaves to process */
  116705. _this.octaves = 3;
  116706. /** Defines the level of persistence (0.8 by default) */
  116707. _this.persistence = 0.8;
  116708. /** Gets or sets animation speed factor (default is 1) */
  116709. _this.animationSpeedFactor = 1;
  116710. _this._updateShaderUniforms();
  116711. return _this;
  116712. }
  116713. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  116714. var scene = this.getScene();
  116715. if (!scene) {
  116716. return;
  116717. }
  116718. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  116719. this.setFloat("brightness", this.brightness);
  116720. this.setFloat("persistence", this.persistence);
  116721. this.setFloat("timeScale", this._time);
  116722. };
  116723. NoiseProceduralTexture.prototype._getDefines = function () {
  116724. return "#define OCTAVES " + (this.octaves | 0);
  116725. };
  116726. /** Generate the current state of the procedural texture */
  116727. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  116728. this._updateShaderUniforms();
  116729. _super.prototype.render.call(this, useCameraPostProcess);
  116730. };
  116731. /**
  116732. * Serializes this noise procedural texture
  116733. * @returns a serialized noise procedural texture object
  116734. */
  116735. NoiseProceduralTexture.prototype.serialize = function () {
  116736. var serializationObject = {};
  116737. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  116738. serializationObject.brightness = this.brightness;
  116739. serializationObject.octaves = this.octaves;
  116740. serializationObject.persistence = this.persistence;
  116741. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  116742. serializationObject.size = this.getSize().width;
  116743. serializationObject.generateMipMaps = this._generateMipMaps;
  116744. return serializationObject;
  116745. };
  116746. /**
  116747. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  116748. * @param parsedTexture defines parsed texture data
  116749. * @param scene defines the current scene
  116750. * @param rootUrl defines the root URL containing noise procedural texture information
  116751. * @returns a parsed NoiseProceduralTexture
  116752. */
  116753. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  116754. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  116755. texture.brightness = parsedTexture.brightness;
  116756. texture.octaves = parsedTexture.octaves;
  116757. texture.persistence = parsedTexture.persistence;
  116758. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  116759. return texture;
  116760. };
  116761. return NoiseProceduralTexture;
  116762. }(BABYLON.ProceduralTexture));
  116763. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  116764. })(BABYLON || (BABYLON = {}));
  116765. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  116766. var __assign = (this && this.__assign) || function () {
  116767. __assign = Object.assign || function(t) {
  116768. for (var s, i = 1, n = arguments.length; i < n; i++) {
  116769. s = arguments[i];
  116770. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  116771. t[p] = s[p];
  116772. }
  116773. return t;
  116774. };
  116775. return __assign.apply(this, arguments);
  116776. };
  116777. var BABYLON;
  116778. (function (BABYLON) {
  116779. /**
  116780. * This can helps recording videos from BabylonJS.
  116781. * This is based on the available WebRTC functionalities of the browser.
  116782. *
  116783. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  116784. */
  116785. var VideoRecorder = /** @class */ (function () {
  116786. /**
  116787. * Create a new VideoCapture object which can help converting what you see in Babylon to
  116788. * a video file.
  116789. * @param engine Defines the BabylonJS Engine you wish to record
  116790. * @param options Defines options that can be used to customized the capture
  116791. */
  116792. function VideoRecorder(engine, options) {
  116793. if (options === void 0) { options = null; }
  116794. if (!VideoRecorder.IsSupported(engine)) {
  116795. throw "Your browser does not support recording so far.";
  116796. }
  116797. var canvas = engine.getRenderingCanvas();
  116798. if (!canvas) {
  116799. throw "The babylon engine must have a canvas to be recorded";
  116800. }
  116801. this._canvas = canvas;
  116802. this._canvas.isRecording = false;
  116803. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  116804. var stream = this._canvas.captureStream(this._options.fps);
  116805. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  116806. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  116807. this._mediaRecorder.onerror = this._handleError.bind(this);
  116808. this._mediaRecorder.onstop = this._handleStop.bind(this);
  116809. }
  116810. /**
  116811. * Returns wehther or not the VideoRecorder is available in your browser.
  116812. * @param engine Defines the Babylon Engine to check the support for
  116813. * @returns true if supported otherwise false
  116814. */
  116815. VideoRecorder.IsSupported = function (engine) {
  116816. var canvas = engine.getRenderingCanvas();
  116817. return (!!canvas && typeof canvas.captureStream === "function");
  116818. };
  116819. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  116820. /**
  116821. * True wether a recording is already in progress.
  116822. */
  116823. get: function () {
  116824. return !!this._canvas && this._canvas.isRecording;
  116825. },
  116826. enumerable: true,
  116827. configurable: true
  116828. });
  116829. /**
  116830. * Stops the current recording before the default capture timeout passed in the startRecording
  116831. * functions.
  116832. */
  116833. VideoRecorder.prototype.stopRecording = function () {
  116834. if (!this._canvas || !this._mediaRecorder) {
  116835. return;
  116836. }
  116837. if (!this.isRecording) {
  116838. return;
  116839. }
  116840. this._canvas.isRecording = false;
  116841. this._mediaRecorder.stop();
  116842. };
  116843. /**
  116844. * Starts recording the canvas for a max duration specified in parameters.
  116845. * @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.
  116846. * @param maxDuration Defines the maximum recording time in seconds.
  116847. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  116848. * @return a promise callback at the end of the recording with the video data in Blob.
  116849. */
  116850. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  116851. var _this = this;
  116852. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  116853. if (maxDuration === void 0) { maxDuration = 7; }
  116854. if (!this._canvas || !this._mediaRecorder) {
  116855. throw "Recorder has already been disposed";
  116856. }
  116857. if (this.isRecording) {
  116858. throw "Recording already in progress";
  116859. }
  116860. if (maxDuration > 0) {
  116861. setTimeout(function () {
  116862. _this.stopRecording();
  116863. }, maxDuration * 1000);
  116864. }
  116865. this._fileName = fileName;
  116866. this._recordedChunks = [];
  116867. this._resolve = null;
  116868. this._reject = null;
  116869. this._canvas.isRecording = true;
  116870. this._mediaRecorder.start(this._options.recordChunckSize);
  116871. return new Promise(function (resolve, reject) {
  116872. _this._resolve = resolve;
  116873. _this._reject = reject;
  116874. });
  116875. };
  116876. /**
  116877. * Releases internal resources used during the recording.
  116878. */
  116879. VideoRecorder.prototype.dispose = function () {
  116880. this._canvas = null;
  116881. this._mediaRecorder = null;
  116882. this._recordedChunks = [];
  116883. this._fileName = null;
  116884. this._resolve = null;
  116885. this._reject = null;
  116886. };
  116887. VideoRecorder.prototype._handleDataAvailable = function (event) {
  116888. if (event.data.size > 0) {
  116889. this._recordedChunks.push(event.data);
  116890. }
  116891. };
  116892. VideoRecorder.prototype._handleError = function (event) {
  116893. this.stopRecording();
  116894. if (this._reject) {
  116895. this._reject(event.error);
  116896. }
  116897. else {
  116898. throw new event.error();
  116899. }
  116900. };
  116901. VideoRecorder.prototype._handleStop = function () {
  116902. this.stopRecording();
  116903. var superBuffer = new Blob(this._recordedChunks);
  116904. if (this._resolve) {
  116905. this._resolve(superBuffer);
  116906. }
  116907. window.URL.createObjectURL(superBuffer);
  116908. if (this._fileName) {
  116909. BABYLON.Tools.Download(superBuffer, this._fileName);
  116910. }
  116911. };
  116912. VideoRecorder._defaultOptions = {
  116913. mimeType: "video/webm",
  116914. fps: 25,
  116915. recordChunckSize: 3000
  116916. };
  116917. return VideoRecorder;
  116918. }());
  116919. BABYLON.VideoRecorder = VideoRecorder;
  116920. })(BABYLON || (BABYLON = {}));
  116921. //# sourceMappingURL=babylon.videoRecorder.js.map
  116922. var BABYLON;
  116923. (function (BABYLON) {
  116924. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  116925. if (replace === void 0) { replace = false; }
  116926. // Dispose existing light in replace mode.
  116927. if (replace) {
  116928. if (this.lights) {
  116929. for (var i = 0; i < this.lights.length; i++) {
  116930. this.lights[i].dispose();
  116931. }
  116932. }
  116933. }
  116934. // Light
  116935. if (this.lights.length === 0) {
  116936. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  116937. }
  116938. };
  116939. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  116940. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116941. if (replace === void 0) { replace = false; }
  116942. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116943. // Dispose existing camera in replace mode.
  116944. if (replace) {
  116945. if (this.activeCamera) {
  116946. this.activeCamera.dispose();
  116947. this.activeCamera = null;
  116948. }
  116949. }
  116950. // Camera
  116951. if (!this.activeCamera) {
  116952. var worldExtends = this.getWorldExtends();
  116953. var worldSize = worldExtends.max.subtract(worldExtends.min);
  116954. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  116955. var camera;
  116956. var radius = worldSize.length() * 1.5;
  116957. // empty scene scenario!
  116958. if (!isFinite(radius)) {
  116959. radius = 1;
  116960. worldCenter.copyFromFloats(0, 0, 0);
  116961. }
  116962. if (createArcRotateCamera) {
  116963. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  116964. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  116965. arcRotateCamera.wheelPrecision = 100 / radius;
  116966. camera = arcRotateCamera;
  116967. }
  116968. else {
  116969. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  116970. freeCamera.setTarget(worldCenter);
  116971. camera = freeCamera;
  116972. }
  116973. camera.minZ = radius * 0.01;
  116974. camera.maxZ = radius * 1000;
  116975. camera.speed = radius * 0.2;
  116976. this.activeCamera = camera;
  116977. var canvas = this.getEngine().getRenderingCanvas();
  116978. if (attachCameraControls && canvas) {
  116979. camera.attachControl(canvas);
  116980. }
  116981. }
  116982. };
  116983. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  116984. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116985. if (replace === void 0) { replace = false; }
  116986. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116987. this.createDefaultLight(replace);
  116988. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  116989. };
  116990. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  116991. if (pbr === void 0) { pbr = false; }
  116992. if (scale === void 0) { scale = 1000; }
  116993. if (blur === void 0) { blur = 0; }
  116994. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  116995. if (!environmentTexture) {
  116996. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  116997. return null;
  116998. }
  116999. if (setGlobalEnvTexture) {
  117000. if (environmentTexture) {
  117001. this.environmentTexture = environmentTexture;
  117002. }
  117003. }
  117004. // Skybox
  117005. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  117006. if (pbr) {
  117007. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  117008. hdrSkyboxMaterial.backFaceCulling = false;
  117009. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  117010. if (hdrSkyboxMaterial.reflectionTexture) {
  117011. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117012. }
  117013. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  117014. hdrSkyboxMaterial.disableLighting = true;
  117015. hdrSkyboxMaterial.twoSidedLighting = true;
  117016. hdrSkybox.infiniteDistance = true;
  117017. hdrSkybox.material = hdrSkyboxMaterial;
  117018. }
  117019. else {
  117020. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  117021. skyboxMaterial.backFaceCulling = false;
  117022. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  117023. if (skyboxMaterial.reflectionTexture) {
  117024. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  117025. }
  117026. skyboxMaterial.disableLighting = true;
  117027. hdrSkybox.infiniteDistance = true;
  117028. hdrSkybox.material = skyboxMaterial;
  117029. }
  117030. return hdrSkybox;
  117031. };
  117032. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  117033. if (BABYLON.EnvironmentHelper) {
  117034. return new BABYLON.EnvironmentHelper(options, this);
  117035. }
  117036. return null;
  117037. };
  117038. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  117039. if (webVROptions === void 0) { webVROptions = {}; }
  117040. return new BABYLON.VRExperienceHelper(this, webVROptions);
  117041. };
  117042. })(BABYLON || (BABYLON = {}));
  117043. //# sourceMappingURL=babylon.sceneHelpers.js.map
  117044. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  117045. 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};"};
  117046. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  117047. globalObject["BABYLON"] = BABYLON;
  117048. //backwards compatibility
  117049. if(typeof earcut !== 'undefined') {
  117050. globalObject["Earcut"] = {
  117051. earcut: earcut
  117052. };
  117053. }
  117054. return BABYLON;
  117055. });